Programs & Examples On #Null test

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Define static method in source-file with declaration in header-file in C++

You don't need to have static in function definition

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

IllegalMonitorStateException on wait() call

Those who are using Java 7.0 or below version can refer the code which I used here and it works.

public class WaitTest {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void waitHere(long waitTime) {
        System.out.println("wait started...");
        lock.lock();
        try {
            condition.await(waitTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("wait ends here...");
    }

    public static void main(String[] args) {
        //Your Code
        new WaitTest().waitHere(10);
        //Your Code
    }

}

Git push error '[remote rejected] master -> master (branch is currently checked out)'

I had the same issue. For me, I use Git push to move code to my servers. I never change the code on the server side, so this is safe.

In the repository, you are pushing to type:

git config receive.denyCurrentBranch ignore

This will allow you to change the repository while it's a working copy.

After you run a Git push, go to the remote machine and type this:

git checkout -f

This will make the changes you pushed be reflected in the working copy of the remote machine.

Please note, this isn't always safe if you make changes on in the working copy that you're pushing to.

WordPress Get the Page ID outside the loop

Use this global $post instead:

global $post;
echo $post->ID;

OS X Framework Library not loaded: 'Image not found'

[Xcode 11+]

The only thing to do is to add the framework to the General->Frameworks, Libraries And Embedded Content section in the General tab of your app target.

Make sure you select the 'Embed & Sign' option.

enter image description here

[Xcode v6 -> Xcode v10]

The only thing to do is to add the framework to the Embedded binaries section in the General tab of your app target.

Screenshot from Xcode

Printing a char with printf

Yes, it prints GARBAGE unless you are lucky.

VERY IMPORTANT.

The type of the printf/sprintf/fprintf argument MUST match the associated format type char.

If the types don't match and it compiles, the results are very undefined.

Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.

If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).

printf("%d\n", (int) ch)

In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.

printf("%d", (int) sizeof('\n'))

How to get a list of images on docker registry v2

Install registry:2.1.1 or later (you can check the last one, here) and use GET /v2/_catalog to get list.

https://github.com/docker/distribution/blob/master/docs/spec/api.md#listing-repositories

Lista all images by Shell script example: https://gist.github.com/OndrejP/a2386d08e5308b0776c0

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Execute dump query in terminal then it will work

mysql -u root -p  <Database_Name> > <path of the input file>

How to implement a Keyword Search in MySQL?

SELECT 
    *
FROM 
    yourtable
WHERE 
    id LIKE '%keyword%' 
    OR position LIKE '%keyword%'
    OR category LIKE '%keyword%'
    OR location LIKE '%keyword%'
    OR description LIKE '%keyword%'
    OR refno LIKE '%keyword%';

Check time difference in Javascript

You can use moment js for this purpose. momentJs 'fromNow()' will give you any time difference from current time.

var m1 = any date time on moment format;

console.log(m1.fromNow());

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

If you are using C# 3.0 or higher you can do the following

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
  ..
}

Without C# 3.0 you can do the following

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {
    ...
  }
}

Or even better, write OfType in C# 2.0.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;
    }
  }
}

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
  ..
}

What does the question mark in Java generics' type parameter mean?

Perhaps a contrived "real world" example would help.

At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish> and Bin<RecylcableRubbish>. The type system needs to make sure I can't put my HalfEatenSandwichRubbish into either of these types, but it can go into a general rubbish bin Bin<Rubbish>. If I wanted to talk about a Bin of Rubbish which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>.

(Note: ? extends does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)

Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

How to find the sum of an array of numbers

Anyone looking for a functional oneliner like me? Take this:

sum = arr.reduce((a, b) => a + b, 0);

(If you happen to have to support ye olde IE without arrow functions:)

sum = arr.reduce(function (a, b) {return a + b;}, 0);

Angular: conditional class with *ngClass

with the following examples you can use 'IF ELSE'

<p class="{{condition ? 'checkedClass' : 'uncheckedClass'}}">
<p [ngClass]="condition ? 'checkedClass' : 'uncheckedClass'">
<p [ngClass]="[condition ? 'checkedClass' : 'uncheckedClass']">

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

I am using VS 2008 and I got this error. I tried everything else suggested here and on some other web sites but nothing worked.

The solution was quite simple and there were two other solutions mentioned on this page that put me in the right area.

  1. Go to Project menu and click on Properties (you can also right click on the Project name in the Solution Explorer and select Properties).

  2. Select Compile tab on the left.

  3. In the "Build output path:" textbox make sure it that you have "bin\" in the textbox.

In my situation it was pointing to another bin folder on the network and that is what caused the breakpoints to fail. You want it looking at your project's current Bin folder.

How to get a list of programs running with nohup

Instead of nohup, you should use screen. It achieves the same result - your commands are running "detached". However, you can resume screen sessions and get back into their "hidden" terminal and see recent progress inside that terminal.

screen has a lot of options. Most often I use these:

To start first screen session or to take over of most recent detached one:

screen -Rd 

To detach from current session: Ctrl+ACtrl+D

You can also start multiple screens - read the docs.

Simplest way to wait some asynchronous tasks complete, in Javascript?

If you are using Babel or such transpilers and using async/await you could do :

function onDrop() {
   console.log("dropped");
}

async function dropAll( collections ) {
   const drops = collections.map(col => conn.collection(col).drop(onDrop) );
   await drops;
   console.log("all dropped");
}

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

What's the difference between Visual Studio Community and other, paid versions?

Visual Studio Community is same (almost) as professional edition. What differs is that VS community do not have TFS features, and the licensing is different. As stated by @Stefan.

The different versions on VS are compared here - https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs

enter image description here

How to select only the first rows for each unique value of a column?

You can use the row_numer() over(partition by ...) syntax like so:

select * from
(
select *
, ROW_NUMBER() OVER(PARTITION BY CName ORDER BY AddressLine) AS row
from myTable
) as a
where row = 1

What this does is that it creates a column called row, which is a counter that increments every time it sees the same CName, and indexes those occurrences by AddressLine. By imposing where row = 1, one can select the CName whose AddressLine comes first alphabetically. If the order by was desc, then it would pick the CName whose AddressLine comes last alphabetically.

Return Result from Select Query in stored procedure to a List

SqlConnection con = new SqlConnection("Data Source=DShp;Initial Catalog=abc;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("data", con);

da.SelectCommand.CommandType= CommandType.StoredProcedure;

DataSet ds=new DataSet();

da.Fill(ds, "data");
GridView1.DataSource = ds.Tables["data"];
GridView1.DataBind();

Vagrant error : Failed to mount folders in Linux guest

One more step I had to complete after following the first suggestion that kenzie made was to run the mount commands listed in the error message with sudo from the Ubuntu command line [14.04 Server]. After that, everything was good to go!

XPath to select Element by attribute value

You need to remove the / before the [. Predicates (the parts in [ ]) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text() at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.

//Employee[@id='4']

Edit: As Jens points out in the comments, // can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:

/Employees/Employee[@id='4']

How to hide collapsible Bootstrap 4 navbar on click

I am using Angular 5 with Boostrap 4. It works for me in this way.

_x000D_
_x000D_
 $(document).on('click', '.navbar-nav>li>a, .navbar-brand, .dropdown-menu>a', function (e) {_x000D_
      if ( $(e.target).is('a') && $(e.target).attr('class') != 'nav-link dropdown-toggle' ) {_x000D_
        $('.navbar-collapse').collapse('hide');_x000D_
      }_x000D_
    });_x000D_
   }
_x000D_
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">_x000D_
  <a class="navbar-brand" [routerLink]="['/home']">FbShareTool</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarColor01">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active" *ngIf="_myAuthService.isAuthenticated()">_x000D_
        <a class="nav-link" [routerLink]="['/dashboard']">Dashboard <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown" *ngIf="_myAuthService.isAuthenticated()">_x000D_
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
            Manage_x000D_
          </a>_x000D_
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
            <a class="dropdown-item" [routerLink]="['/fbgroup']">Facebook Group</a>_x000D_
            <div class="dropdown-divider"></div>_x000D_
            <a class="dropdown-item" href="#">Fetch Data</a>_x000D_
          </div>_x000D_
      </li>_x000D_
    </ul>_x000D_
_x000D_
    <ul class="navbar-nav navbar-right navbar-right-link">_x000D_
        <li class="nav-item" *ngIf="!_myAuthService.isAuthenticated()" >_x000D_
            <a class="nav-link" (click)="logIn()">Login</a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
           <a class="nav-link">{{ _myAuthService.userDetails.displayName }}</a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated() && _myAuthService.userDetails.photoURL">_x000D_
            <a>_x000D_
              <img [src]="_myAuthService.userDetails.photoURL" alt="profile-photo" class="img-fluid rounded" width="40px;">_x000D_
            </a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
            <a class="nav-link" (click)="logOut()">Logout</a>_x000D_
        </li>_x000D_
    </ul>_x000D_
_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to switch between frames in Selenium WebDriver using Java

WebDriver's driver.switchTo().frame() method takes one of the three possible arguments:

  • A number.

    Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index 0, the second at index 1 and the third at index 2. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

  • A name or ID.

    Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.

  • A previously found WebElement.

    Select a frame using its previously located WebElement.

Get the frame by it's id/name or locate it by driver.findElement() and you'll be good.

How to reduce the image file size using PIL

The main image manager in PIL is PIL's Image module.

from PIL import Image
import math

foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)

You can add optimize=True to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's. For other image extensions, you could decrease the quality of the new saved image. You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully. I defined this size:

x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)

just to show you what is (almost) normally done with horizontal images. For vertical images you might do:

x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)

. Remember, you can still delete that bit of code and define a new size.

How to get element value in jQuery

A li doesn't have a value. Only form-related elements such as input, textarea and select have values.

Margin-Top not working for span element?

Looks like you missed some options, try to add:

position: relative;
top: 25px;

How to send an email from JavaScript

Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

You seem to not be depending on "@angular/core". This is an error

This happened to me when I was mixing package managers. My project was generated with Yarn, and after that, I added a couple of dependencies using npm install (this created the package-lock.json with only added dependencies).

Apparently, ng serve used package-lock.json and couldn't find Angular dependencies there. After I started using only Yarn, i.e. yarn add instead of npm install, the error was gone.

Return current date plus 7 days

strtotime will automatically use the current unix timestamp to base your string annotation off of.

Just do:

$date = strtotime("+7 day");
echo date('M d, Y', $date);

Added Info For Future Visitors: If you need to pass a timestamp to the function, the below will work.

This will calculate 7 days from yesterday:

$timestamp = time()-86400;

$date = strtotime("+7 day", $timestamp);
echo date('M d, Y', $date);

Auto-increment on partial primary key with Entity Framework Core

Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

How to make html table vertically scrollable

Try this one.. It is working... Here JSBIN

table tbody { height:300px; overflow-y:scroll; display:block; }
table thead { display:block; }

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

How to show the Project Explorer window in Eclipse

If you are on either Eclipse or Spring tool suite then follow the below steps.

(1) Go to 'Window' on the top of the editor. Click on it
(2) Select show view. You should see an option 'Project Explorer'. Click on it.
You should be able to do it.

enter image description here

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

Convert number to month name in PHP

Just because everyone is using strtotime() and date() functions, I will show DateTime example:

$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');

Delete all local git branches

Try the following shell command:

git branch | grep -v "master" | xargs git branch -D

Explanation:

  • Get all branches (except for the master) via git branch | grep -v "master" command
  • Select every branch with xargs command
  • Delete branch with xargs git branch -D

Send mail via Gmail with PowerShell V2's Send-MailMessage

I haven't used PowerShell V2's Send-MailMessage, but I have used System.Net.Mail.SMTPClient class in V1 to send messages to a Gmail account for demo purposes. This might be overkill, but I run an SMTP server on my Windows Vista laptop (see this link). If you're in an enterprise you will already have a mail relay server, and this step isn't necessary. Having an SMTP server I'm able to send email to my Gmail account with the following code:

$smtpmail = [System.Net.Mail.SMTPClient]("127.0.0.1")
$smtpmail.Send("[email protected]", "[email protected]", "Test Message", "Message via local SMTP")

Reading a file line by line in Go

// strip '\n' or read until EOF, return error if read error  
func readline(reader io.Reader) (line []byte, err error) {   
    line = make([]byte, 0, 100)                              
    for {                                                    
        b := make([]byte, 1)                                 
        n, er := reader.Read(b)                              
        if n > 0 {                                           
            c := b[0]                                        
            if c == '\n' { // end of line                    
                break                                        
            }                                                
            line = append(line, c)                           
        }                                                    
        if er != nil {                                       
            err = er                                         
            return                                           
        }                                                    
    }                                                        
    return                                                   
}                                    

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

How do I delete all messages from a single queue using the CLI?

rabbitmqadmin is the perfect tool for this

rabbitmqadmin purge queue name=name_of_the_queue_to_be_purged

View not attached to window manager crash

Firstly,the crash reason is decorView's index is -1,we can knew it from Android source code ,there is code snippet:

class:android.view.WindowManagerGlobal

file:WindowManagerGlobal.java

private int findViewLocked(View view, boolean required) {
        final int index = mViews.indexOf(view);
//here, view is decorView,comment by OF
        if (required && index < 0) {
            throw new IllegalArgumentException("View=" + view + " not attached to window manager");
        }
        return index;
    }

so we get follow resolution,just judge decorView's index,if it more than 0 then continue or just return and give up dismiss,code as follow:

try {
            Class<?> windowMgrGloable = Class.forName("android.view.WindowManagerGlobal");
            try {
                Method mtdGetIntance = windowMgrGloable.getDeclaredMethod("getInstance");
                mtdGetIntance.setAccessible(true);
                try {
                    Object windownGlobal = mtdGetIntance.invoke(null,null);
                    try {
                        Field mViewField = windowMgrGloable.getDeclaredField("mViews");
                        mViewField.setAccessible(true);
                        ArrayList<View> mViews = (ArrayList<View>) mViewField.get(windownGlobal);
                        int decorViewIndex = mViews.indexOf(pd.getWindow().getDecorView());
                        Log.i(TAG,"check index:"+decorViewIndex);
                        if (decorViewIndex < 0) {
                            return;
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (pd.isShowing()) {
            pd.dismiss();
        }

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

Logical operator in a handlebars.js {{#if}} conditional

You can use the following code:

{{#if selection1}}
    doSomething1
{{else}}
   {{#if selection2}}
       doSomething2
   {{/if}}
{{/if}}

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

Lets say, you wanted to have some CGAL-Demos portable. So you'd have a folder "CGAL", and in it, 1 subfolder called "lib": all (common) support-dlls for any programs in the CGAL-folder go here. In our example, this would be the Dll-Download: simply unzip into the "lib" directory. The further you scroll down on the demos-page, the more impressive the content. In my case, the polyhedron-demo seemed about right. If this runs on my 10+ yo notebook, I'm impressed. So I created a folder "demo" in the "CGAL"-directory, alongside "lib". Now create a .cmd-file in that folder. I named mine "Polyhedron.cmd". So we have a directory structure like this:

 CGAL - the bag for all the goodies
  lib - all libraries for all CGAL-packages
 demo - all the demos I'm interested in
[...] - certainly some other collections, several apps per folder...
Polyhedron.cmd - and a little script for every Qt-exe to make it truly portable.

In this little example, "Polyhedron.cmd" contains the following text:

@echo off
set "me=%~dp0"
set PATH=%me%lib
set "QT_PLUGIN_PATH=%me%lib\plugins"
start /b "CGAL Polyhedron Demo" "%me%demo\polyhedron\polyhedron_3.exe"

All scripts can be the same apart from the last line, obviously. The only caveat is: the "DOS-Window" stays open for as long as you use the actual program. Close the shell-window, and you kill the *.exe as well. Whereever you copy the "CGAL"-folder, as the weird "%~dp0"-wriggle represents the full path to the *.cmd-file that we started, with trailing "\". So "%me%lib" is always the full path to the actual library ("CGAL\lib" in my case). The next 2 lines tell Qt where its "runtime" files are. This will be at least the file "qwindows.dll" for Windows-Qt programs plus any number of *.dlls. If I remember rightly, the Dll-library (at least when I downloaded it) had a little "bug" since it contains the "platforms"-directory with qwindows.dll in it. So when you open the lib directory, you need to create a folder "plugins" next to "platforms", and then move into "plugins". If a Qt-app, any Qt-app, doesn't find "qwindows.dll", it cannot find "windows". And it expects it in a directory named "platforms" in the "plugins" directory, which it has to get told by the OS its running on...and if the "QT_PLUGIN_PATH" is not exactly pointing to all the helper-dlls you need, some Qt-programs will still run with no probs. And some complain about missing *.dlls you've never heard off...

Pytorch tensor to numpy array

While other answers perfectly explained the question I will add some real life examples converting tensors to numpy array:

Example: Shared storage

PyTorch tensor residing on CPU shares the same storage as numpy array na

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
tensor([[10.,  1.]])

Example: Eliminate effect of shared storage, copy numpy array first

To avoid the effect of shared storage we need to copy() the numpy array na to a new numpy array nac. Numpy copy() method creates the new separate storage.

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
nac = na.copy()
nac[0][0]=10
?print(nac)
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
[[1. 1.]]
tensor([[1., 1.]])

Now, just the nac numpy array will be altered with the line nac[0][0]=10, na and a will remain as is.

Example: CPU tensor with requires_grad=True

import torch
a = torch.ones((1,2), requires_grad=True)
print(a)
na = a.detach().numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], requires_grad=True)
[[10.  1.]]
tensor([[10.,  1.]], requires_grad=True)

In here we call:

na = a.numpy() 

This would cause: RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead., because tensors that require_grad=True are recorded by PyTorch AD. Note that tensor.detach() is the new way for tensor.data.

This explains why we need to detach() them first before converting using numpy().

Example: CUDA tensor with requires_grad=False

a = torch.ones((1,2), device='cuda')
print(a)
na = a.to('cpu').numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0')
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0')

?

Example: CUDA tensor with requires_grad=True

a = torch.ones((1,2), device='cuda', requires_grad=True)
print(a)
na = a.detach().to('cpu').numpy()
na[0][0]=10
?print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0', requires_grad=True)
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0', requires_grad=True)

Without detach() method the error RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead. will be set.

Without .to('cpu') method TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. will be set.

You could use cpu() but instead of to('cpu') but I prefer the newer to('cpu').

Scrolling a div with jQuery

I don't know if this is exactly what you want, but did you know you can use the CSS overflow property to create scrollbars?

CSS:

div.box{
  width: 200px;
  height: 200px;
  overflow: scroll;
}

HTML:

<div class="box">
  All your text content...
</div>

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

How to populate HTML dropdown list with values from database

My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

Simplest JQuery validation rules example

The input in the markup is missing "type", the input (text I assume) has the attribute name="name" and ID="cname", the provided code by Ayo calls the input named "cname"* where it should be "name".

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

Paramiko's SSHClient with SFTP

paramiko.SFTPClient

Sample Usage:

import paramiko
paramiko.util.log_to_file("paramiko.log")

# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"
transport.connect(None,username,password)

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)

# Close
if sftp: sftp.close()
if transport: transport.close()

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

How to set delay in android?

Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.

    public void fadeImageFunction(View view) {

    backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
    backgroundImage.animate().alpha(0f).setDuration(2000);

    // A new thread with a 2-second delay before changing the background image
    new Timer().schedule(
            new TimerTask(){
                @Override
                public void run(){
                    // you cannot touch the UI from another thread. This thread now calls a function on the main thread
                    changeBackgroundImage();
                }
            }, 2000);
   }

// this function runs on the main ui thread
private void changeBackgroundImage(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
            backgroundImage.setImageResource(R.drawable.supes);
            backgroundImage.animate().alpha(1f).setDuration(2000);
        }
    });
}

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

Convert List<String> to List<Integer> directly

No, you will have to iterate over each element:

for(String number : numbers) {
   numberList.add(Integer.parseInt(number)); 
}

The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car object and a Person object. You can't convert a List<Car> into a List<Person> directly since it doesn't really make sense.

Angular 5 Button Submit On Enter Key Press

In case anyone is wondering what input value

<input (keydown.enter)="search($event.target.value)" />

How to get the containing form of an input?

Every input has a form property which points to the form the input belongs to, so simply:

function doSomething(element) {
  var form = element.form;
}

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

How to solve java.lang.NoClassDefFoundError?

Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:

1.firstly, create the instance of class in a simple thread and catch the crash.

2.then call the field method of Class in main thread, you will get the NoClassDefFoundError.

here is the test code:

public class MyClass{
       private static  Handler mHandler = new Handler();
       public static int num = 0;
}

in your onCrete method of Main activity, add test code part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //test code start
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MyClass myClass = new MyClass();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }).start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    MyClass.num = 3;
    // end of test code
}

there is a simple way to fix it using a handlerThread to init handler:

private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
    handlerThread.start();
    mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}

how to change namespace of entire project?

I know its quite late but for anyone looking to do it from now on, I hope this answer proves of some help. If you have CodeRush Express (free version, and a 'must have') installed, it offers a simple way to change a project wide namespace. You just place your cursor on the namespace that you want to change and it shall display a smart tag (a little blue box) underneath namespace string. You can either click that box or press Ctrl + keys to see the Rename option. Select it and then type in the new name for the project wide namespace, click Apply and select what places in your project you'd want it to change, in the new dialog and OK it. Done! :-)

What command shows all of the topics and offsets of partitions in Kafka?

You might want to try kt. It's also quite faster than the bundled kafka-topics.

This is the current most complete info description you can get out of a topic with kt:

kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas

It also outputs as JSON, so you can pipe it to jq for further flexibility.

How do I use a Boolean in Python?

The boolean builtins are capitalized: True and False.

Note also that you can do checker = bool(some_decision) as a bit of shorthand -- bool will only ever return True or False.

It's good to know for future reference that classes defining __nonzero__ or __len__ will be True or False depending on the result of those functions, but virtually every other object's boolean result will be True (except for the None object, empty sequences, and numeric zeros).

How to install SQL Server Management Studio 2012 (SSMS) Express?

When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe

I had to choose the following options to get the management Tools:

  1. "New SQL Server stand-alone installation or add features to an existing installation."
  2. "Add features to an existing instance of SQL Server 2012"
  3. Accept the license.
  4. Check the box for "Management Tools - Basic".
  5. Wait a long time as it installs.

When I was done I had an option "SQL Server Management Studio" within my Start Menu.

Searching for "Management" pulled it up faster within the Start Menu.

How to bind 'touchstart' and 'click' events but not respond to both?

I am also working on an Android/iPad web app, and it seems that if only using "touchmove" is enough to "move components" ( no need touchstart ). By disabling touchstart, you can use .click(); from jQuery. It's actually working because it hasn't be overloaded by touchstart.

Finally, you can binb .live("touchstart", function(e) { e.stopPropagation(); }); to ask the touchstart event to stop propagating, living room to click() to get triggered.

It worked for me.

How to paginate with Mongoose in Node.js?

You can do using mongoose-paginate-v2. For more info click here

const mongoose         = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');

const mySchema = new mongoose.Schema({
    // your schema code
}); 
mySchema.plugin(mongoosePaginate); 
const myModel = mongoose.model('SampleModel',  mySchema);

myModel.paginate().then({}) // Usage

What does the term "canonical form" or "canonical representation" in Java mean?

Canonical Data in RDBMS, Graph Data;
Think as "Normalization" or "Normal form" of a data in a RDBMS. Same data exists in different tables, represented with a unique identifier and mapped it in different tables.
or
Think a single form of a data in Graph Database that represented in many triples.

Major benefit of it is to make Dml (Data manipulation) more efficient since you can upsert (insert/update) only one value instead of many.

Extract subset of key-value pairs from Python dictionary object?

You could try:

dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):

{k: bigdict[k] for k in ('l', 'm', 'n')}

Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict to map to None, you can do:

{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:

{k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}

Could not open input file: artisan

If it is your first install of laravel then create another directory/folder inside the laravel directory and then move to that empty folder and create another project using the command below:

composer create-project --prefer-dist laravel/laravel blog

This will create a new project named "blog", then go back to parent laravel directory and now you can run this command:

php artisan serve

You will receive the return such as:

laravel deployment server started: http://localhost:8000

See attached image enter image description here

cv2.imshow command doesn't work properly in opencv-python

I had the same 215 error, which I was able to overcome by giving the full path to the image, as in, C:\Folder1\Folder2\filename.ext

SQL Server format decimal places with commas

From a related SO question: Format a number with commas but without decimals in SQL Server 2008 R2?

SELECT CONVERT(varchar, CAST(1112 AS money), 1)

This was tested in SQL Server 2008 R2.

String.format() to format double in java

Use DecimalFormat

 NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
 DecimalFormat decimalFormatter = (DecimalFormat) nf;
 decimalFormatter.applyPattern("#,###,###.##");
 String fString = decimalFormatter.format(myDouble);
 System.out.println(fString);

ngFor with index as value in attribute

The other answers are correct but you can omit the [attr.data-index] altogether and just use

<ul>
    <li *ngFor="let item of items; let i = index">{{i + 1}}</li>
</ul

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

How to initialize an array in Java?

data[10] = {10,20,30,40,50,60,71,80,90,91};

The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element.

If you want to initialize an array, try using Array Initializer:

int[] data = {10,20,30,40,50,60,71,80,90,91};

// or

int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};

Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used.

Even if you correct the syntax, accessing data[10] is still incorrect (You can only access data[0] to data[9] because index of arrays in Java is 0-based). Accessing data[10] will throw an ArrayIndexOutOfBoundsException.

How to TryParse for Enum value?

In the end you have to implement this around Enum.GetNames:

public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
    // Can't make this a type constraint...
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Type parameter must be an enum");
    }
    var names = Enum.GetNames(typeof(T));
    value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
    foreach (var name in names) {
        if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
            value = (T)Enum.Parse(typeof(T), name);
            return true;
        }
    }
    return false;
}

Additional notes:

  • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
  • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

show dbs gives "Not Authorized to execute command" error

It was Docker running in the background in my case. If you have Docker installed, you may wanna close it and try again.

How does bitshifting work in Java?

Shift Operators

The binary 32 bits for 00101011 is

00000000 00000000 00000000 00101011, and the result is:

  00000000 00000000 00000000 00101011   >> 2(times)
 \\                                 \\
  00000000 00000000 00000000 00001010

Shifts the bits of 43 to right by distance 2; fills with highest(sign) bit on the left side.

Result is 00001010 with decimal value 10.

00001010
    8+2 = 10

What Does This Mean in PHP -> or =>

The double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

I had the same problem on Windows 7.

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

The solution turned out to be very simple - right click on command prompt shortcut and choose "Run as Administrator". After that, the problem disappeared)

Read file from aws s3 bucket using node fs

I couldn't figure why yet, but the createReadStream/pipe approach didn't work for me. I was trying to download a large CSV file (300MB+) and I got duplicated lines. It seemed a random issue. The final file size varied in each attempt to download it.

I ended up using another way, based on AWS JS SDK examples:

var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');

s3.getObject(params).
    on('httpData', function(chunk) { file.write(chunk); }).
    on('httpDone', function() { file.end(); }).
    send();

This way, it worked like a charm.

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

Git - remote: Repository not found

This issue here is you local git is not able to push the changes to the remote Check your remote is set correctly by

git remote -v

if it is not set properly try setting your remote as

git remote set-url origin https://[email protected]/MyRepo/project.git

Then try pushing using

git push -u origin master

Also there is a possibility of your local git has different credentials, please check that also.

How to add and remove classes in Javascript without jQuery

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

Check if multiple strings exist in another string

Just to add some diversity with regex:

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

or if your list is too long - any(re.findall(r'|'.join(a), str, re.IGNORECASE))

Get key by value in dictionary

we can get the Key of dict by :

def getKey(dct,value):
     return [key for key in dct if (dct[key] == value)]

How can I check if a View exists in a Database?

FOR SQL SERVER

IF EXISTS(select * FROM sys.views where name = '')

jQuery set radio button

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Node.js global variables

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

Use a JavaScript file and then use module exports.

Example:

File globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

var globals = require('globals'); // << globals.js path
globals.domain // << Domain.

How do I get the row count of a Pandas DataFrame?

How do I get the row count of a Pandas DataFrame?

This table summarises the different situations in which you'd want to count something in a DataFrame (or Series, for completeness), along with the recommended method(s).

Enter image description here

Footnotes

  1. DataFrame.count returns counts for each column as a Series since the non-null count varies by column.
  2. DataFrameGroupBy.size returns a Series, since all columns in the same group share the same row-count.
  3. DataFrameGroupBy.count returns a DataFrame, since the non-null count could differ across columns in the same group. To get the group-wise non-null count for a specific column, use df.groupby(...)['x'].count() where "x" is the column to count.

#Minimal Code Examples

Below, I show examples of each of the methods described in the table above. First, the setup -

df = pd.DataFrame({
    'A': list('aabbc'), 'B': ['x', 'x', np.nan, 'x', np.nan]})
s = df['B'].copy()

df

   A    B
0  a    x
1  a    x
2  b  NaN
3  b    x
4  c  NaN

s

0      x
1      x
2    NaN
3      x
4    NaN
Name: B, dtype: object

Row Count of a DataFrame: len(df), df.shape[0], or len(df.index)

len(df)
# 5

df.shape[0]
# 5

len(df.index)
# 5

It seems silly to compare the performance of constant time operations, especially when the difference is on the level of "seriously, don't worry about it". But this seems to be a trend with other answers, so I'm doing the same for completeness.

Of the three methods above, len(df.index) (as mentioned in other answers) is the fastest.

Note

  • All the methods above are constant time operations as they are simple attribute lookups.
  • df.shape (similar to ndarray.shape) is an attribute that returns a tuple of (# Rows, # Cols). For example, df.shape returns (8, 2) for the example here.

Column Count of a DataFrame: df.shape[1], len(df.columns)

df.shape[1]
# 2

len(df.columns)
# 2

Analogous to len(df.index), len(df.columns) is the faster of the two methods (but takes more characters to type).

Row Count of a Series: len(s), s.size, len(s.index)

len(s)
# 5

s.size
# 5

len(s.index)
# 5

s.size and len(s.index) are about the same in terms of speed. But I recommend len(df).

Note size is an attribute, and it returns the number of elements (=count of rows for any Series). DataFrames also define a size attribute which returns the same result as df.shape[0] * df.shape[1].

Non-Null Row Count: DataFrame.count and Series.count

The methods described here only count non-null values (meaning NaNs are ignored).

Calling DataFrame.count will return non-NaN counts for each column:

df.count()

A    5
B    3
dtype: int64

For Series, use Series.count to similar effect:

s.count()
# 3

Group-wise Row Count: GroupBy.size

For DataFrames, use DataFrameGroupBy.size to count the number of rows per group.

df.groupby('A').size()

A
a    2
b    2
c    1
dtype: int64

Similarly, for Series, you'll use SeriesGroupBy.size.

s.groupby(df.A).size()

A
a    2
b    2
c    1
Name: B, dtype: int64

In both cases, a Series is returned. This makes sense for DataFrames as well since all groups share the same row-count.

Group-wise Non-Null Row Count: GroupBy.count

Similar to above, but use GroupBy.count, not GroupBy.size. Note that size always returns a Series, while count returns a Series if called on a specific column, or else a DataFrame.

The following methods return the same thing:

df.groupby('A')['B'].size()
df.groupby('A').size()

A
a    2
b    2
c    1
Name: B, dtype: int64

Meanwhile, for count, we have

df.groupby('A').count()

   B
A
a  2
b  1
c  0

...called on the entire GroupBy object, vs.,

df.groupby('A')['B'].count()

A
a    2
b    1
c    0
Name: B, dtype: int64

Called on a specific column.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

Checking if a textbox is empty in Javascript

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.

Resolution:

The directory /usr/include/c++/4.4.6/x86_64-redhat-linux was missing.

I did the following:

cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32

I'm now able to compile 32bit binaries on a 64bit OS.

JavaScript: IIF like statement

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

How to load URL in UIWebView in Swift?

In Swift 4 or 4.2 You can use like:

  1. Add WKWebView & connect to you view comtroller.
  2. Your view is like bellow:

     import UIKit
     import WebKit
    
    class ViewController: UIViewController {
    
       @IBOutlet weak var wkwebview: WKWebView!
    
        override func viewDidLoad() {
           super.viewDidLoad()
    
          let request = URLRequest(url: URL(string: "**your URL**")!)        
          wkwebview?.load(request)
    
      }
    
    }
    
  3. Allow Allow Arbitrary Loads true info.plist

      <key>NSAppTransportSecurity</key>
         <dict>
           <key>Allow Arbitrary Loads</key>
              <true/>
        </dict>
    

    Note info.plist will look like bellow

enter image description here

How to loop through an array of objects in swift

The photos property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count property of the array):

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

removing table border

Use Firebug to inspect the table in question, and see where does it inherit the border from. (check the right column). Try setting on-the-fly inline style border:none; to see if you get rid of it. Could also be the browsers default stylesheets. In this case, use a CSS reset. http://developer.yahoo.com/yui/reset/

Making sure at least one checkbox is checked

if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
            || ($("#checkboxid3").is(":checked"))) {
 //Your Code here
}

You can use this code to verify that checkbox is checked at least one.

Thanks!!

refresh leaflet map: map container is already initialized

I had the same problem on angular when switching page. I had to add this code before leaving the page to make it works:

    $scope.$on('$locationChangeStart', function( event ) {
    if(map != undefined)
    {
      map.remove();
      map = undefined
      document.getElementById('mapLayer').innerHTML = "";
    }
});

Without document.getElementById('mapLayer').innerHTML = "" the map was not displayed on the next page.

Failed to load resource: the server responded with a status of 404 (Not Found)

Note the failing URL:

Failed ... http://localhost:8080/RetailSmart/jsp/Jquery/jquery.multiselect.css

Now examine one of your links:

<link href="../Jquery/jquery.multiselect.css" rel="stylesheet"/>

The "../" is shorthand for "The containing directory", or "Up one directory". This is a relative URL. At a guess, you have a file in /jsp/<somefolder>/ which contains the <link /> and <style /> elements.

I recommend using an absolute URL:

<link href="/RetailSmart/Jquery/jquery.multiselect.css" rel="stylesheet"/>

The reason for using an absolute url is that I'm guessing the links are contained in some common file. If you attempt to correct your relative pathing by adding a second "../", you may break any files contained in /jsp.

Pick a random value from an enum?

Letter lettre = Letter.values()[(int)(Math.random()*Letter.values().length)];

A function to convert null to string

Convert.ToString(object) converts to string. If the object is null, Convert.ToString converts it to an empty string.

Calling .ToString() on an object with a null value throws a System.NullReferenceException.

EDIT:

Two exceptions to the rules:

1) ConvertToString(string) on a null string will always return null.

2) ToString(Nullable<T>) on a null value will return "" .

Code Sample:

// 1) Objects:

object obj = null;

//string valX1 = obj.ToString();           // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);    

Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False


// 2) Strings

String str = null;
//string valX2 = str.ToString();    // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str); 

Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True            


// 3) Nullable types:

long? num = null;
string val3 = num.ToString();  // ok, no error

Console.WriteLine(num == null); // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False 

val3 = Convert.ToString(num);  

Console.WriteLine(num == null);  // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False

Differences between socket.io and websockets

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

Print "hello world" every X seconds

Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.

public class RemindTask extends TimerTask {
    public void run() {
      System.out.println(" Hello World!");
    }
    public static void main(String[] args){
       Timer timer = new Timer();
       timer.schedule(new RemindTask(), 3000,3000);
    }
  }

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

How to properly highlight selected item on RecyclerView?

@zIronManBox answer works flawlessly. Although it doesn't have the capability for unselection and unseleted items in the recyclerView.

SO

add, as before, a private int selectedPos = RecyclerView.NO_POSITION; in the RecyclerView Adapter class, and under onBindViewHolder method :

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {   
    viewHolder.itemView.setSelected(selectedPos == position);

}

And also in your OnClick event :

@Override
public void onClick(View view) {
     notifyItemChanged(selectedPos);
     selectedPos = getLayoutPosition();
     notifyItemChanged(selectedPos); 
}

Also add the following selector (drawable) in your layout , which includes a state_selected="false" with a transparent color:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@color/pressed_color" android:state_pressed="true"/>
  <item android:drawable="@color/selected_color" android:state_selected="true"/>
  <item android:drawable="@color/focused_color" android:state_focused="true"/>
  <item android:drawable="@android:color/transparent" android:state_selected="false"/>
</selector>

Otherwise setSelected(..) will do nothing, rendering this solution useless.

How to get all properties values of a JavaScript Object (without knowing the keys)?

ES5 Object.keys

var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]

JavaScript, getting value of a td with id name

Again with getElementById, but instead .value, use .innerText

<td id="test">Chicken</td>
document.getElementById('test').innerText; //the value of this will be 'Chicken'

python dictionary sorting in descending order based on values

List

dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv

Dictionary

d = []
l = len(sv)
while l != 0 :
    d.append(sv[l - 1])
    l = l - 1
print d`

How to drop a database with Mongoose?

To drop all documents in a collection:

await mongoose.connection.db.dropDatabase();

This answer is based off the mongoose index.d.ts file:

dropDatabase(): Promise<any>;

6 digits regular expression

^[0-9]{1,6}$ should do it. I don't know VB.NET good enough to know if it's the same there.

For examples, have a look at the Wikipedia.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

SHA512 vs. Blowfish and Bcrypt

It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.

If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.

Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.


Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".

Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.

If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.

Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.

In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.

So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.

Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.

If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.

So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.

How do I initialize a TypeScript Object with a JSON-Object?

I personally prefer option #3 of @Ingo Bürk. And I improved his codes to support an array of complex data and Array of primitive data.

interface IDeserializable {
  getTypes(): Object;
}

class Utility {
  static deserializeJson<T>(jsonObj: object, classType: any): T {
    let instanceObj = new classType();
    let types: IDeserializable;
    if (instanceObj && instanceObj.getTypes) {
      types = instanceObj.getTypes();
    }

    for (var prop in jsonObj) {
      if (!(prop in instanceObj)) {
        continue;
      }

      let jsonProp = jsonObj[prop];
      if (this.isObject(jsonProp)) {
        instanceObj[prop] =
          types && types[prop]
            ? this.deserializeJson(jsonProp, types[prop])
            : jsonProp;
      } else if (this.isArray(jsonProp)) {
        instanceObj[prop] = [];
        for (let index = 0; index < jsonProp.length; index++) {
          const elem = jsonProp[index];
          if (this.isObject(elem) && types && types[prop]) {
            instanceObj[prop].push(this.deserializeJson(elem, types[prop]));
          } else {
            instanceObj[prop].push(elem);
          }
        }
      } else {
        instanceObj[prop] = jsonProp;
      }
    }

    return instanceObj;
  }

  //#region ### get types ###
  /**
   * check type of value be string
   * @param {*} value
   */
  static isString(value: any) {
    return typeof value === "string" || value instanceof String;
  }

  /**
   * check type of value be array
   * @param {*} value
   */
  static isNumber(value: any) {
    return typeof value === "number" && isFinite(value);
  }

  /**
   * check type of value be array
   * @param {*} value
   */
  static isArray(value: any) {
    return value && typeof value === "object" && value.constructor === Array;
  }

  /**
   * check type of value be object
   * @param {*} value
   */
  static isObject(value: any) {
    return value && typeof value === "object" && value.constructor === Object;
  }

  /**
   * check type of value be boolean
   * @param {*} value
   */
  static isBoolean(value: any) {
    return typeof value === "boolean";
  }
  //#endregion
}

// #region ### Models ###
class Hotel implements IDeserializable {
  id: number = 0;
  name: string = "";
  address: string = "";
  city: City = new City(); // complex data
  roomTypes: Array<RoomType> = []; // array of complex data
  facilities: Array<string> = []; // array of primitive data

  // getter example
  get nameAndAddress() {
    return `${this.name} ${this.address}`;
  }

  // function example
  checkRoom() {
    return true;
  }

  // this function will be use for getting run-time type information
  getTypes() {
    return {
      city: City,
      roomTypes: RoomType
    };
  }
}

class RoomType implements IDeserializable {
  id: number = 0;
  name: string = "";
  roomPrices: Array<RoomPrice> = [];

  // getter example
  get totalPrice() {
    return this.roomPrices.map(x => x.price).reduce((a, b) => a + b, 0);
  }

  getTypes() {
    return {
      roomPrices: RoomPrice
    };
  }
}

class RoomPrice {
  price: number = 0;
  date: string = "";
}

class City {
  id: number = 0;
  name: string = "";
}
// #endregion

// #region ### test code ###
var jsonObj = {
  id: 1,
  name: "hotel1",
  address: "address1",
  city: {
    id: 1,
    name: "city1"
  },
  roomTypes: [
    {
      id: 1,
      name: "single",
      roomPrices: [
        {
          price: 1000,
          date: "2020-02-20"
        },
        {
          price: 1500,
          date: "2020-02-21"
        }
      ]
    },
    {
      id: 2,
      name: "double",
      roomPrices: [
        {
          price: 2000,
          date: "2020-02-20"
        },
        {
          price: 2500,
          date: "2020-02-21"
        }
      ]
    }
  ],
  facilities: ["facility1", "facility2"]
};

var hotelInstance = Utility.deserializeJson<Hotel>(jsonObj, Hotel);

console.log(hotelInstance.city.name);
console.log(hotelInstance.nameAndAddress); // getter
console.log(hotelInstance.checkRoom()); // function
console.log(hotelInstance.roomTypes[0].totalPrice); // getter
// #endregion

How to escape apostrophe (') in MySql?

Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.

'He said, "Don''t!"'

What exactly is OAuth (Open Authorization)?

OAuth is all about delegating Authorization (choosing someone who can do Authorization for you). Note that Authentication and Authorization are different things. OAuth is Authorization (Access control), and if you want to implement Authentication (ID verification) also, OpenID protocol can be used on top of OAuth.

All big companies like Facebook, Google, Github,... use this kind of authentication/authorization nowadays. For example, I just signed in on this website using my Google account, this means Stackoverflow doesn't know my password, it receives the allowance from Google where my password (hashed obviously) is saved. This gives a lot of benefits, one of them is; In the near future you won't have to make several accounts on every website. One website (which you trust most) can be used to login to all other websites. So you'll only have to remember one password.

How can I rollback a git repository to a specific commit?

In github, the easy way is to delete the remote branch in the github UI, under branches tab. You have to make sure remove following settings to make the branch deletable:

  1. Not a default branch
  2. No opening poll requests.
  3. The branch is not protected.

Now recreate it in your local repository to point to the previous commit point. and add it back to remote repo.

git checkout -b master 734c2b9b   # replace with your commit point

Then push the local branch to remote

git push -u origin master

Add back the default branch and branch protection, etc.

Is it possible to cherry-pick a commit from another git repository?

If you want to cherry-pick multiple commits for a given file until you reach a given commit, then use the following.

# Directory from which to cherry-pick
GIT_DIR=...
# Pick changes only for this file
FILE_PATH=...
# Apply changes from this commit
FIST_COMMIT=master
# Apply changes until you reach this commit
LAST_COMMIT=...

for sha in $(git --git-dir=$GIT_DIR log --reverse --topo-order --format=%H $LAST_COMMIT_SHA..master -- $FILE_PATH ) ; do 
  git --git-dir=$GIT_DIR  format-patch -k -1 --stdout $sha -- $FILE_PATH | 
    git am -3 -k
done

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

MySQL root password change

Please follow the below steps.

  1. sudo service mysql stop
  2. sudo mysqld_safe --skip-grant-tables
  3. sudo service mysql start
  4. sudo mysql -u root
  5. use mysql;
  6. show tables;
  7. describe user;
  8. update user set authentication_string=password('1111') where user='root';

login with password 1111

Custom "confirm" dialog in JavaScript?

_x000D_
_x000D_
var confirmBox = '<div class="modal fade confirm-modal">' +_x000D_
    '<div class="modal-dialog modal-sm" role="document">' +_x000D_
    '<div class="modal-content">' +_x000D_
    '<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +_x000D_
    '<span aria-hidden="true">&times;</span>' +_x000D_
    '</button>' +_x000D_
    '<div class="modal-body pb-5"></div>' +_x000D_
    '<div class="modal-footer pt-3 pb-3">' +_x000D_
    '<a href="#" class="btn btn-primary yesBtn btn-sm">OK</a>' +_x000D_
    '<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>';_x000D_
_x000D_
var dialog = function(el, text, trueCallback, abortCallback) {_x000D_
_x000D_
    el.click(function(e) {_x000D_
_x000D_
        var thisConfirm = $(confirmBox).clone();_x000D_
_x000D_
        thisConfirm.find('.modal-body').text(text);_x000D_
_x000D_
        e.preventDefault();_x000D_
        $('body').append(thisConfirm);_x000D_
        $(thisConfirm).modal('show');_x000D_
_x000D_
        if (abortCallback) {_x000D_
            $(thisConfirm).find('.abortBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                abortCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        if (trueCallback) {_x000D_
            $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                trueCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        } else {_x000D_
_x000D_
            if (el.prop('nodeName') == 'A') {_x000D_
                $(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));_x000D_
            }_x000D_
_x000D_
            if (el.attr('type') == 'submit') {_x000D_
                $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                    e.preventDefault();_x000D_
                    el.off().click();_x000D_
                });_x000D_
            }_x000D_
        }_x000D_
_x000D_
        $(thisConfirm).on('hidden.bs.modal', function(e) {_x000D_
            $(this).remove();_x000D_
        });_x000D_
_x000D_
    });_x000D_
}_x000D_
_x000D_
// custom confirm_x000D_
$(function() {_x000D_
    $('[data-confirm]').each(function() {_x000D_
        dialog($(this), $(this).attr('data-confirm'));_x000D_
    });_x000D_
_x000D_
    dialog($('#customCallback'), "dialog with custom callback", function() {_x000D_
_x000D_
        alert("hi there");_x000D_
_x000D_
    });_x000D_
_x000D_
});
_x000D_
.test {_x000D_
  display:block;_x000D_
  padding: 5p 10px;_x000D_
  background:orange;_x000D_
  color:white;_x000D_
  border-radius:4px;_x000D_
  margin:0;_x000D_
  border:0;_x000D_
  width:150px;_x000D_
  text-align:center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
example 1_x000D_
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>_x000D_
_x000D_
_x000D_
example 2_x000D_
<form action="">_x000D_
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>_x000D_
</form><br><br>_x000D_
_x000D_
example 3_x000D_
<span class="test"  id="customCallback">with callback</span>
_x000D_
_x000D_
_x000D_

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

if variable contains

You can use a regex:

if (/ST1/i.test(code))

HTML Form: Select-Option vs Datalist-Option

I noticed that there is no selected feature in datalist. It only gives you choice but can't have a default option. You can't show the selected option on the next page either.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Here the steps I used to fix the warning:

  • Unload project in VS
  • Edit .csproj file
  • Search for all references to Newtonsoft.Json assembly
    • Found two, one to v6 and one to v5
    • Replace the reference to v5 with v6
  • Reload project
  • Build and notice assembly reference failure
  • View References and see that there are now two to Newtonsoft.Json. Remove the one that's failing to resolve.
  • Rebuild - no warnings

Checking password match while typing

The onkeyup event does "work" as you intend:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
function checkPasswordMatch() {
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();

    if (password != confirmPassword)
        $("#divCheckPasswordMatch").html("Passwords do not match!");
    else
        $("#divCheckPasswordMatch").html("Passwords match.");
}
//--></script>
</head>
<body>

<div class="td">
    <input type="password" id="txtNewPassword" />
</div>
<div class="td">
    <input type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();" />
</div>
    <div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>

</body>
</html>

Is it not possible to define multiple constructors in Python?

The easiest way is through keyword arguments:

class City():
  def __init__(self, city=None):
    pass

someCity = City(city="Berlin")

This is pretty basic stuff. Maybe look at the Python documentation?

Android studio doesn't list my phone under "Choose Device"

I've had this problem many times before with my Galaxy Nexus. Despite having the Android SDK's USB drivers installed, it did not seem to suffice.

I've always solved this by installing a program called PdaNet. While I don't know exactly what it is used for and where it gets its drivers - it comes with the drivers that has always fixed the problem for me. You can uninstall the program itself once it has finished.

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <buildDirectory>${project.build.directory}</buildDirectory>
            [...]
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:

<project>
  ...
  <plugins>
    ...
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         ...
         <systemProperties>
            <systemProperty>
              <name>propertyName</name>
              <value>propertyValue</value>
            </systemProperty>
            ...
         </systemProperties>
        </configuration>
      </plugin>
  </plugins>
</project>

ASP.Net MVC - Read File from HttpPostedFileBase without save

An alternative is to use StreamReader.

public void FunctionName(HttpPostedFileBase file)
{
    string result = new StreamReader(file.InputStream).ReadToEnd();
}

Map implementation with duplicate keys

what about such a MultiMap impl?

public class MultiMap<K, V> extends HashMap<K, Set<V>> {
  private static final long serialVersionUID = 1L;
  private Map<K, Set<V>> innerMap = new HashMap<>();

  public Set<V> put(K key, V value) {
    Set<V> valuesOld = this.innerMap.get(key);
    HashSet<V> valuesNewTotal = new HashSet<>();
    if (valuesOld != null) {
      valuesNewTotal.addAll(valuesOld);
    }
    valuesNewTotal.add(value);
    this.innerMap.put(key, valuesNewTotal);
    return valuesOld;
  }

  public void putAll(K key, Set<V> values) {
    for (V value : values) {
      put(key, value);
    }
  }

  @Override
  public Set<V> put(K key, Set<V> value) {
    Set<V> valuesOld = this.innerMap.get(key);
    putAll(key, value);
    return valuesOld;
  }

  @Override
  public void putAll(Map<? extends K, ? extends Set<V>> mapOfValues) {
    for (Map.Entry<? extends K, ? extends Set<V>> valueEntry : mapOfValues.entrySet()) {
      K key = valueEntry.getKey();
      Set<V> value = valueEntry.getValue();
      putAll(key, value);
    }
  }

  @Override
  public Set<V> putIfAbsent(K key, Set<V> value) {
    Set<V> valueOld = this.innerMap.get(key);
    if (valueOld == null) {
      putAll(key, value);
    }
    return valueOld;
  }

  @Override
  public Set<V> get(Object key) {
    return this.innerMap.get(key);
  }

  @Override
  etc. etc. override all public methods size(), clear() .....

}

Apply .gitignore on an existing repository already tracking large number of files

I think this is an easy way for adding a .gitignore file to an existing repository.

Prerequisite:

You need a browser to access your github account.

Steps

  1. Create a new file in your required (existing) project and name it .gitignore. You will a get suggestive prompt for .gitignore templates as soon as you name the file as .gitignore. Either use these templates or use gitignore.io to generate the content of your gitignore file.
  2. Commit the changes.
  3. Now clone this repository.

Have fun!

MySQL command line client for Windows

Its pretty simple. I saved the mysql community server in my D:\ drive. Hence this is how i did it.

Goto D:\mysql-5.7.18-winx64\bin and in the address bar type cmd and press enter, so command prompt will open. Now if you're using it for the first time type as mysql -u root -ppress enter. Then it will ask for password, again press enter. Thats it you are connected to the mysql server.

Before this make sure wamp or xampp any of the local server is running because i couldn't able to connect to mysql wihthout xampp running. enter image description here

enter image description here

Happy Coding.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Check your connection first.

Then if you want to fetch the exact value from the database then you should write:

$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");

Or you want to fetch the LIKE type of value then you should write:

$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");

How to get main window handle from process id?

Just to make sure you are not confusing the tid (thread id) and the pid (process id):

DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);

Mutex example / tutorial?

You are supposed to check the mutex variable before using the area protected by the mutex. So your pthread_mutex_lock() could (depending on implementation) wait until mutex1 is released or return a value indicating that the lock could not be obtained if someone else has already locked it.

Mutex is really just a simplified semaphore. If you read about them and understand them, you understand mutexes. There are several questions regarding mutexes and semaphores in SO. Difference between binary semaphore and mutex, When should we use mutex and when should we use semaphore and so on. The toilet example in the first link is about as good an example as one can think of. All code does is to check if the key is available and if it is, reserves it. Notice that you don't really reserve the toilet itself, but the key.

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

How do you set up use HttpOnly cookies in PHP

Explanation here from Ilia... 5.2 only though

httpOnly cookie flag support in PHP 5.2

As stated in that article, you can set the header yourself in previous versions of PHP

header("Set-Cookie: hidden=value; httpOnly");

Can you issue pull requests from the command line on GitHub?

Git now ships with a subcommand 'git request-pull' [-p] <start> <url> [<end>]

You can see the docs here

You may find this useful but it is not exactly the same as GitHub's feature.

How do we check if a pointer is NULL pointer?

First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.

In the end, there are three widespread ways to check for a null pointer:

if ( p != NULL ) ...

if ( p != 0 ) ...

if ( p ) ...

All work, regardless of the representation of a null pointer on the machine. And all, in some way or another, are misleading; which one you choose is a question of choosing the least bad. Formally, the first two are indentical for the compiler; the constant NULL or 0 is converted to a null pointer of the type of p, and the results of the conversion are compared to p. Regardless of the representation of a null pointer.

The third is slightly different: p is implicitly converted to bool. But the implicit conversion is defined as the results of p != 0, so you end up with the same thing. (Which means that there's really no valid argument for using the third style—it obfuscates with an implicit conversion, without any offsetting benefit.)

Which one of the first two you prefer is largely a matter of style, perhaps partially dictated by your programming style elsewhere: depending on the idiom involved, one of the lies will be more bothersome than the other. If it were only a question of comparison, I think most people would favor NULL, but in something like f( NULL ), the overload which will be chosen is f( int ), and not an overload with a pointer. Similarly, if f is a function template, f( NULL ) will instantiate the template on int. (Of course, some compilers, like g++, will generate a warning if NULL is used in a non-pointer context; if you use g++, you really should use NULL.)

In C++11, of course, the preferred idiom is:

if ( p != nullptr ) ...

, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)

wait until all threads finish their work in java

Store the Thread-objects into some collection (like a List or a Set), then loop through the collection once the threads are started and call join() on the Threads.

Specifying number of decimal places in Python

You don't show the code for display_data, but here's what you need to do:

print "$%0.02f" %amount

This is a format specifier for the variable amount.

Since this is beginner topic, I won't get into floating point rounding error, but it's good to be aware that it exists.

How to center an unordered list?

http://jsfiddle.net/psbu2/3/

If it is possible for you to use your own list bullets

Try this:

<html>
    <head>
        <style type="text/css">

            ul {
                margin:0;
                padding:0;
                text-align: center;
                list-style:none;                
            }
            ul  li {
                padding: 2px 5px;               
            }

            ul li:before {
                content:url(http://www.un.org/en/oaj/unjs/efiling/added/images/bullet-list-icon-blue.jpg);;
            }
        </style>
    </head>
    <body>

            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
            </ul>

    </body>
</html>

How to display image from database using php

<?php
    $conn = mysql_connect ("localhost:3306","root","");
    $db = mysql_select_db ("database_name", $conn);

    if(!$db) {
        echo mysql_error();
    }

    $q = "SELECT image FROM table_name where id=4";
    $r = mysql_query ("$q",$conn);
    if($r) {
         while($row = mysql_fetch_array($r)) {
            header ("Content-type: image/jpeg");       
    echo $row ["image"];
        }
    }else{
        echo mysql_error();
    }
    ?>

sometimes problem may  occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306" 
in case if you have installed two mysql servers on same system then write port according to that

in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query 
4.write correct table name inside the query
5.and last is traverse through data

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

Prepend text to beginning of string

You could do it this way ..

_x000D_
_x000D_
var mystr = 'is my name.';_x000D_
mystr = mystr.replace (/^/,'John ');_x000D_
_x000D_
console.log(mystr);
_x000D_
_x000D_
_x000D_

disclaimer: http://xkcd.com/208/


Wait, forgot to escape a space.  Wheeeeee[taptaptap]eeeeee.

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

Using SVG as background image

You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.

Multiple conditions in a C 'for' loop

Do not use this code; whoever wrote it clearly has a fundamental misunderstanding of the language and is not trustworthy. The expression:

j >= 0, i <= 5

evaluates "j >= 0", then throws it away and does nothing with it. Then it evaluates "i <= 5" and uses that, and only that, as the condition for ending the loop. The comma operator can be used meaningfully in a loop condition when the left operand has side effects; you'll often see things like:

for (i = 0, j = 0; i < 10; ++i, ++j) . . .

in which the comma is used to sneak in extra initialization and increment statements. But the code shown is not doing that, or anything else meaningful.

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

Remove everything before <?xml version="1.0" encoding="utf-8"?>

Sometimes, there is some "invisible" (not visible in all text editors). Some programs add this.

It's called BOM, you can read more about it here: https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Well, I guess that Flex' implementation of the SOAP Encoder seems to serialize null values incorrectly. Serializing them as a String Null doesn't seem to be a good solution. The formally correct version seems to be to pass a null value as:

<childtag2 xsi:nil="true" />

So the value of "Null" would be nothing else than a valid string, which is exactly what you are looking for.

I guess getting this fixed in Apache Flex shouldn't be that hard to get done. I would recommend opening a Jira issue or to contact the guys of the apache-flex mailinglist. However this would only fix the client side. I can't say if ColdFusion will be able to work with null values encoded this way.

See also Radu Cotescu's blog post How to send null values in soapUI requests.

bootstrap popover not showing on top of all elements

When you have some styles on a parent element that interfere with a popover, you’ll want to specify a custom container so that the popover’s HTML appears within that element instead.

For instance say the parent for a popover is body then you can use.

    <a href="#" data-toggle="tooltip" data-container="body"> Popover One </a>

Other case might be when popover is placed inside some other element and you want to show popover over that element, then you'll need to specify that element in data-container. ex: Suppose, we have popover inside a bootstrap modal with id as 'modal-two', then you'll need to set 'data-container' to 'modal-two'.

    <a href="#" data-toggle="tooltip" data-container="#modal-two"> Popover Two </a>

Set height of chart in Chart.js

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How to generate a random string in Ruby

This solution needs external dependency, but seems prettier than another.

  1. Install gem faker
  2. Faker::Lorem.characters(10) # => "ang9cbhoa8"

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

You don't have the right to execute it, although you have enough permissions to create it.

For more information, see GRANT Object Permissions (Transact-SQL)

What are "named tuples" in Python?

named tuples allow backward compatibility with code that checks for the version like this

>>> sys.version_info[0:2]
(3, 1)

while allowing future code to be more explicit by using this syntax

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

javac option to compile all java files under a given directory recursively

If your shell supports it, would something like this work ?

javac com/**/*.java 

If your shell does not support **, then maybe

javac com/*/*/*.java

works (for all packages with 3 components - adapt for more or less).

jquery - is not a function error

I solved it by renaming my function.

Changed

function editForm(value)

to

function editTheForm(value)

Works perfectly.

transform object to array with lodash

For me, this worked:

_.map(_.toPairs(data), d => _.fromPairs([d]));

It turns

{"a":"b", "c":"d", "e":"f"} 

into

[{"a":"b"}, {"c":"d"}, {"e":"f"}]

Get event listeners attached to node using addEventListener

Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):

var ListenerTracker=new function(){
    var is_active=false;
    // listener tracking datas
    var _elements_  =[];
    var _listeners_ =[];
    this.init=function(){
        if(!is_active){//avoid duplicate call
            intercep_events_listeners();
        }
        is_active=true;
    };
    // register individual element an returns its corresponding listeners
    var register_element=function(element){
        if(_elements_.indexOf(element)==-1){
            // NB : split by useCapture to make listener easier to find when removing
            var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
            _elements_.push(element);
            _listeners_.push(elt_listeners);
        }
        return _listeners_[_elements_.indexOf(element)];
    };
    var intercep_events_listeners = function(){
        // backup overrided methods
        var _super_={
            "addEventListener"      : HTMLElement.prototype.addEventListener,
            "removeEventListener"   : HTMLElement.prototype.removeEventListener
        };

        Element.prototype["addEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["addEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;

            if(!listeners[useCapture][type])listeners[useCapture][type]=[];
            listeners[useCapture][type].push(listener);
        };
        Element.prototype["removeEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["removeEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;
            if(!listeners[useCapture][type])return;
            var lid = listeners[useCapture][type].indexOf(listener);
            if(lid>-1)listeners[useCapture][type].splice(lid,1);
        };
        Element.prototype["getEventListeners"]=function(type){
            var listeners=register_element(this);
            // convert to listener datas list
            var result=[];
            for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
                if(typeof(type)=="string"){// filtered by type
                    if(list[type]){
                        for(var id in list[type]){
                            result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
                        }
                    }
                }else{// all
                    for(var _type in list){
                        for(var id in list[_type]){
                            result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
                        }
                    }
                }
            }
            return result;
        };
    };
}();
ListenerTracker.init();

What possibilities can cause "Service Unavailable 503" error?

If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.

How to add text at the end of each line in Vim?

The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>. This means that the substitute command will operate on the visual selection, like so:

:'<,'>s/$/,/

And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:

:'<,'>s/\s*$/,/

This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.

The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/, or for the entire buffer: :%s/$/,/.

Insert a string at a specific index

Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

RecyclerView: Inconsistency detected. Invalid item position

You only need to clear your list on OnPostExecute() and not while doing Pull to Refresh

// Setup refresh listener which triggers new data loading
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                AsyncTask<String,Void,String> task = new get_listings();
                task.execute(); // clear listing inside onPostExecute

            }
        });

I discovered that this happens when you scroll during a pull to refresh, since I was clearing the list before the async task , resulting to java.lang.IndexOutOfBoundsException: Inconsistency detected.

        swipeContainer.setRefreshing(false);
        //TODO : This is very crucial , You need to clear before populating new items 
        listings.clear();

That way you won't end with an inconsistency

HttpClient won't import in Android Studio

If you want import some class like :

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

You can add the following line in the build.gradle (Gradle dependencies)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:support-v4:27.1.0'

    .
    .
    .

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

}

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

How to create a global variable?

From the official Swift programming guide:

Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.

 var yourVariable = "someString"

You can access this from anywhere in the current module.

However you should avoid this as Global variables are not good for application state and mainly reason of bugs.

As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

You can use this variable in any class or anywhere

let string = MyVariables.yourVariable
println("Global variable:\(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

javascript clear field value input

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How to retrieve element value of XML using Java?

Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.

See the XML how-to

Can't update data-attribute value

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');

// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).data('fruit','7');

// But when you get the value again, it will return old value. 
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7'); 

Read this documentation for vanilla js or this documentation for jquery

How to center a View inside of an Android Layout?

I use android:layout_centerInParent="true" and it worked

How do I fill arrays in Java?

An array can be initialized by using the new Object {} syntax.

For example, an array of String can be declared by either:

String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};

Primitives can also be similarly initialized either by:

int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};

Or an array of some Object:

Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};

All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.

Count number of occurrences by month

For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:

=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))

Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.

Postman: sending nested JSON object

Select the body tab and select application/json in the Content-Type drop-down and add a body like this:

{
  "Username":"ABC",
  "Password":"ABC"
}

enter image description here

What is the best way to detect a mobile device?

The screen may be on desktop with a small resolution or a mobile with a wide resolution, as so, combining two answers found here in this question

const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
    console.log('is_mobile')
}

The name 'InitializeComponent' does not exist in the current context

There's a very specific reason for this, and it's in the project settings. This usually happens whenever you try to add a WPF control/window to a .NET 2.0 class library or project. The reason for this error is that the project does not know it's building a WPF control or window and therefore tries to build it as a C# 2.0 project.

The solution involves editing the .csproj file. Right click on the project causing the problem and select “Unload Project”. Right click the unloaded project and select “Edit .csproj”. The .csproj file will open and you can see the XML. look for the following line:

<Import Project=…..

It's near the end of the file, and the only line that you have is probably

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

This tells Visual Studio to build the project as a .NET 2.0 project. What we want to do is to tell Visual Studio that this is actually a WPF project, so we have to add the following line:

<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

This line will tell Visual Studio to build the project as a WPF project. Now your .csproj file bottom should look like this:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

Save the .csproj file, right click it in Solution Explorer and select “Reload Project” compile and that's it, you're all done!

iText - add content to existing PDF file

Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("E:/TextFieldForm.pdf"));
    document.open();

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;      

    // Code 2, add name TextField       
    table.addCell("Name"); 
    TextField nameField = new TextField(writer, 
        new Rectangle(0,0,200,10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);               
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 
        200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript(
        "var nameField = this.getField('nameField');" +
        "nameField.setAction('Keystroke'," +
        "'forceUpperCase()');" +
        "" +
        "function forceUpperCase(){" +
        "if(!event.willCommit)event.change = " +
        "event.change.toUpperCase();" +
        "}");


    // Code 3, add empty row
    table.addCell("");
    table.addCell("");


    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0,
         0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 
        30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript(
        "var ageField = this.getField('ageField');" +
        "ageField.setAction('Validate','checkAge()');" +
        "function checkAge(){" +
        "if(event.value < 12){" +
        "app.alert('Warning! Applicant\\'s age can not" +
        " be younger than 12.');" +
        "event.value = 12;" +
        "}}");      



    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, 
        new Rectangle(0, 0,200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 
        200, writer));
    table.addCell(cell);


    // check comment characters length javascript
    writer.addJavaScript(
        "var commentField = " +
        "this.getField('commentField');" +
        "commentField" +
        ".setAction('Keystroke','checkLength()');" +
        "function checkLength(){" +
        "if(!event.willCommit && " +
        "event.value.length > 100){" +
        "app.alert('Warning! Comment can not " +
        "be more than 100 characters.');" +
        "event.change = '';" +
        "}}");          

    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 6, add submit button    
    PushbuttonField submitBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15),"submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.
        setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.
        VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction
    .createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));

    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);



    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(
        PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn
    .setOptions(
        PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);        

    document.add(table);
    document.close();
}


class FieldCell implements PdfPCellEvent{

    PdfFormField formField;
    PdfWriter writer;
    int width;

    public FieldCell(PdfFormField formField, int width, 
        PdfWriter writer){
        this.formField = formField;
        this.width = width;
        this.writer = writer;
    }

    public void cellLayout(PdfPCell cell, Rectangle rect, 
        PdfContentByte[] canvas){
        try{
            // delete cell border
            PdfContentByte cb = canvas[PdfPTable
                .LINECANVAS];
            cb.reset();

            formField.setWidget(
                new Rectangle(rect.left(), 
                    rect.bottom(), 
                    rect.left()+width, 
                    rect.top()), 
                    PdfAnnotation
                    .HIGHLIGHT_NONE);

            writer.addAnnotation(formField);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

xcopy file, rename, suppress "Does xxx specify a file name..." message

So, there is a simple fix for this. It is admittedly awkward, but it works. xcopy will not prompt to find out if the destination is a directory or file IF the new file(filename) already exists. If you precede your xcopy command with a simple echo to the new filename, it will overwrite the empty file. Example

echo.>newfile.txt
xcopy oldfile.txt newfile.txt /Y

How to trigger event when a variable's value is changed?

just use a property

int  _theVariable;
public int TheVariable{
  get{return _theVariable;}
  set{
    _theVariable = value; 
    if ( _theVariable == 1){
      //Do stuff here.
    }
  }
}

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How do I match any character across multiple lines in a regular expression?

Try this:

((.|\n)*)<FooBar>

It basically says "any character or a newline" repeated zero or more times.

What is a wrapper class?

It might also be valuable to note that in some environments, much of what wrapper classes might do is being replaced by aspects.

EDIT:

In general a wrapper is going to expand on what the wrappee does, without being concerned about the implementation of the wrappee, otherwise there's no point of wrapping versus extending the wrapped class. A typical example is to add timing information or logging functionality around some other service interface, as opposed to adding it to every implementation of that interface.

This then ends up being a typical example for Aspect programming. Rather than going through an interface function by function and adding boilerplate logging, in aspect programming you define a pointcut, which is a kind of regular expression for methods, and then declare methods that you want to have executed before, after or around all methods matching the pointcut. Its probably fair to say that aspect programming is a kind of use of the Decorator pattern, which wrapper classes can also be used for, but that both technologies have other uses.