SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

ERROR: Error 1005: Can't create table (errno: 121)

You can login to mysql and type

mysql> SHOW INNODB STATUS\G

You will have all the output and you should have a better idea of what the error is.

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

How do I animate constraint changes?

I appreciate the answer provided, but I think it would be nice to take it a bit further.

The basic block animation from the documentation

[containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
[UIView animateWithDuration:1.0 animations:^{
     // Make all constraint changes here
     [containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
}];

but really this is a very simplistic scenario. What if I want to animate subview constraints via the updateConstraints method?

An animation block that calls the subviews updateConstraints method

[self.view layoutIfNeeded];
[self.subView setNeedsUpdateConstraints];
[self.subView updateConstraintsIfNeeded];
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionLayoutSubviews animations:^{
    [self.view layoutIfNeeded];
} completion:nil];

The updateConstraints method is overridden in the UIView subclass and must call super at the end of the method.

- (void)updateConstraints
{
    // Update some constraints

    [super updateConstraints];
}

The AutoLayout Guide leaves much to be desired but it is worth reading. I myself am using this as part of a UISwitch that toggles a subview with a pair of UITextFields with a simple and subtle collapse animation (0.2 seconds long). The constraints for the subview are being handled in the UIView subclasses updateConstraints methods as described above.

No connection string named 'MyEntities' could be found in the application config file

are you using more than one project on your solution?

Because if you are, the web config you must check is the one on the same project as de .edmx file

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

Rounding a variable to two decimal places C#

Use Math.Round and specify the number of decimal places.

Math.Round(pay,2);

Math.Round Method (Double, Int32)

Rounds a double-precision floating-point value to a specified number of fractional digits.

Or Math.Round Method (Decimal, Int32)

Rounds a decimal value to a specified number of fractional digits.

How does Java import work?

Java's import statement is pure syntactical sugar. import is only evaluated at compile time to indicate to the compiler where to find the names in the code.

You may live without any import statement when you always specify the full qualified name of classes. Like this line needs no import statement at all:

javax.swing.JButton but = new  javax.swing.JButton();

The import statement will make your code more readable like this:

import javax.swing.*;

JButton but = new JButton();

Remote Procedure call failed with sql server 2008 R2

I just had the same issue and was able to solve it by installing Service Pack 1.

Programmatically set TextBlock Foreground Color

You could use Brushes.White to set the foreground.

myTextBlock.Foreground = Brushes.White;

The Brushes class is located in System.Windows.Media namespace.

Or, you can press Ctrl+. while the cursor is on the unknown class name to automatically add using directive.

Remove Array Value By index in jquery

delete arr[1]

Try this out, it should work if you have an array like var arr =["","",""]

Print to standard printer from Python?

To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.

Please have a look at the below link that should give a good start:

http://frank.zinepal.com/printing-directly-to-a-network-printer

Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.

http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165

Replacing instances of a character in a string

If you are replacing by an index value specified in variable 'n', then try the below:

def missing_char(str, n):
 str=str.replace(str[n],":")
 return str

UTF-8 encoding in JSP page

This are special characters in html. Why dont you encode it? Check it out: http://www.degraeve.com/reference/specialcharacters.php

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I have faced this error a lot of time, also research why this error occurs and finally, I caught this error, this error a silly error which occurs when we misspelled .xib file name.

NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];

At this point, I misspelled TableViewCell as TabelViewCell , because the perception of some time we read it as correct, this is the most common problem. Just copy your .xib file name, and paste it.

How do I use floating-point division in bash?

i know it's old, but too tempting. so, the answer is: you can't... but you kind of can. let's try this:

$IMG_WIDTH=1024
$IMG2_WIDTH=2048

$RATIO="$(( IMG_WIDTH / $IMG2_WIDTH )).$(( (IMG_WIDTH * 100 / IMG2_WIDTH) % 100 ))

like that you get 2 digits after the point, truncated (call it rounding to the lower, haha) in pure bash (no need to launch other processes). of course, if you only need one digit after the point you multiply by 10 and do modulo 10.

what this does:

  • first $((...)) does integer division;
  • second $((...)) does integer division on something 100 times larger, essentially moving your 2 digits to the left of the point, then (%) getting you only those 2 digits by doing modulo.

bonus track: bc version x 1000 took 1,8 seconds on my laptop, while the pure bash one took 0,016 seconds.

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

Best practice to validate null and empty collection in Java

That is the best way to check it. You could write a helper method to do it:

public static boolean isNullOrEmpty( final Collection< ? > c ) {
    return c == null || c.isEmpty();
}

public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
    return m == null || m.isEmpty();
}

PostgreSQL: How to change PostgreSQL user password?

Then type:

$ sudo -u postgres psql

Then:

\password postgres

Then to quit psql:

\q

If that does not work, reconfigure authentication.

Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

    local   all             all                                     peer

to:

    local   all             all                                     md5

Then restart the server:

$ sudo service postgresql restart

No visible cause for "Unexpected token ILLEGAL"

The error

When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.

The same error is raised if, for example, you try to run a js file with a rogue @ character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)) and so on.

A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisible illegal character. That's what this answer is about.

But I can't see anything illegal!

There is an invisible character in the code, right after the semicolon. It's the Unicode U+200B Zero-width space character (a.k.a. ZWSP, HTML entity &#8203;). That character is known to cause the Unexpected token ILLEGAL JavaScript syntax error.

And where did it come from?

I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200B characters. It seems the tool uses that character to control word-wrapping on long strings.

UPDATE 2013-01-07

After the latest jsfiddle update, it's now showing the character as a red dot like codepen does. Apparently, it's also not inserting U+200B characters on its own anymore, so this problem should be less frequent from now on.

UPDATE 2015-03-17

Vagrant appears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog post is to set sendfile off; in your nginx config, or EnableSendfile Off if you use Apache.

It's also been reported that code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).

How can I spot it?

The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSP shows as <u200b>. You can also debug it online: jsbin displays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.

Related problems

That character is not something bad, it can actually be quite useful. This example on Wikipedia demonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValue of a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim).

ZWSP can also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div> elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.

Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as ​ in latin1, for example).

If ZWSP is present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).

The ECMAScript Specification

I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3 and 5.1). The current version mentions similar characters (U+200C and U+200D) on Section 7.1, which says they should be treated as IdentifierParts when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c; indeed works).

Section 7.2 lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200B should be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Stylesheet not updating

In my case, since I could not append a cache busting timestamp to the css url it turned out that I had to manually refresh the application pool in IIS 7.5.7600.

Every other avenue was pursued, right down to disabling the caching entirely for the site and also for the local browser (like ENTIRELY disabled for both), still didn't do the trick. Also "restarting" the website did nothing.

Same position as me? [Site Name] > "Application Pool" > "Recycle" is your last resort...

What is Linux’s native GUI API?

I suppose the question is more like "What is linux's native GUI API".

In most cases X (aka X11) will be used for that: http://en.wikipedia.org/wiki/X_Window_System.

You can find the API documentation here

How to display Woocommerce Category image?

To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src():

<?php 

$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );

// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );

// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />'; 

// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';

?>

EDIT: Fixed variable name and missing quote

Count lines in large files

Let us assume:

  • Your file system is distributed
  • Your file system can easily fill the network connection to a single node
  • You access your files like normal files

then you really want to chop the files into parts, count parts in parallel on multiple nodes and sum up the results from there (this is basically @Chris White's idea).

Here is how you do that with GNU Parallel (version > 20161222). You need to list the nodes in ~/.parallel/my_cluster_hosts and you must have ssh access to all of them:

parwc() {
    # Usage:
    #   parwc -l file                                                                

    # Give one chunck per host                                                     
    chunks=$(cat ~/.parallel/my_cluster_hosts|wc -l)
    # Build commands that take a chunk each and do 'wc' on that                    
    # ("map")                                                                      
    parallel -j $chunks --block -1 --pipepart -a "$2" -vv --dryrun wc "$1" |
        # For each command                                                         
        #   log into a cluster host                                                
        #   cd to current working dir                                              
        #   execute the command                                                    
        parallel -j0 --slf my_cluster_hosts --wd . |
        # Sum up the number of lines                                               
        # ("reduce")                                                               
        perl -ne '$sum += $_; END { print $sum,"\n" }'
}

Use as:

parwc -l myfile
parwc -w myfile
parwc -c myfile

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

How to check if a character in a string is a digit or letter

char charInt=character.charAt(0);   
if(charInt>=48 && charInt<=57){
    System.out.println("not character");
}
else
    System.out.println("Character");

Look for ASCII table to see how the int value are hardcoded .

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

Exception from HRESULT: 0x800A03EC Error

I got this error when calling this code: wks.Range[startCell, endCell] where the startCell Range and endCell Range were pointing to different worksheet then the variable wks.

Function in JavaScript that can be called only once

if (!window.doesThisOnce){
  function myFunction() {
    // do something
    window.doesThisOnce = true;
  };
};

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

How to specify a local file within html using the file: scheme?

The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.

Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...

I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.

How do I dynamically assign properties to an object in TypeScript?

Index types

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows.

interface LooseObject {
    [key: string]: any
}

var obj: LooseObject = {};

OR to make it compact:

var obj: {[k: string]: any} = {};

LooseObject can accept fields with any string as key and any type as value.

obj.prop = "value";
obj.prop2 = 88;

The real elegance of this solution is that you can include typesafe fields in the interface.

interface MyType {
    typesafeProp1?: number,
    requiredProp1: string,
    [key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;

Record<Keys,Type> utility type

Update (August 2020): @transang brought this up in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known. It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics. IMO, this makes it worth mentioning here

For comparison,

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {
    typesafeProp1?: number,
    requiredProp1: string,
}

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

How to convert uint8 Array to base64 Encoded String?

function Uint8ToBase64(u8Arr){
  var CHUNK_SIZE = 0x8000; //arbitrary number
  var index = 0;
  var length = u8Arr.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  return btoa(result);
}

You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

How to create own dynamic type or dynamic object in C#?

dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};

How do you explicitly set a new property on `window` in TypeScript?

Here's how to do it, if you're using TypeScript Definition Manager!

npm install typings --global

Create typings/custom/window.d.ts:

interface Window {
  MyNamespace: any;
}

declare var window: Window;

Install your custom typing:

typings install file:typings/custom/window.d.ts --save --global

Done, use it‌! Typescript won't complain anymore:

window.MyNamespace = window.MyNamespace || {};

Difference between arguments and parameters in Java

Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.

You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments

PHP form send email to multiple recipients

If i understood correct try this one

$headers = "Bcc: [email protected]";

or

$headers = "Cc: [email protected]";

How to Increase Import Size Limit in phpMyAdmin

if you're using xampp, find the php.ini (in xampp folder itself), go to line 735 and change the post_max_size to the value you wish. ex: if you want to upgrade to 80MiB,

post_max_size = 80M

make sure to restart apache after changing the value.

That's it...

How to set the holo dark theme in a Android app?

According the android.com, you only need to set it in the AndroidManifest.xml file:

http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme

Adding the theme attribute to your application element worked for me:

--AndroidManifest.xml--

...

<application ...

  android:theme="@android:style/Theme.Holo"/>
  ...

</application>

Spring REST Service: how to configure to remove null objects in json response

For all you non-xml config folks:

ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
HttpMessageConverter msgConverter = new MappingJackson2HttpMessageConverter(objMapper);
restTemplate.setMessageConverters(Collections.singletonList(msgConverter));

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

How to group subarrays by a column value?

This array_group_by function achieves what you are looking for:

$grouped = array_group_by($arr, 'id');

It even supports multi-level groupings:

$grouped = array_group_by($arr, 'id', 'part_no');

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

Bulk Insertion in Laravel using eloquent ORM

Problem solved... Alter table for migrate

$table->timestamp('created_at')->nullable()->useCurrent();

Solution:

Schema::create('spider_news', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('source')->nullable();
    $table->string('title')->nullable();
    $table->string('description')->nullable();
    $table->string('daterss')->nullable();

    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});

Iterate through a C++ Vector using a 'for' loop

There's a couple of strong reasons to use iterators, some of which are mentioned here:

Switching containers later doesn't invalidate your code.

i.e., if you go from a std::vector to a std::list, or std::set, you can't use numerical indices to get at your contained value. Using an iterator is still valid.

Runtime catching of invalid iteration

If you modify your container in the middle of your loop, the next time you use your iterator it will throw an invalid iterator exception.

Constructor overload in TypeScript

I know this is an old question, but new in 1.4 is union types; use these for all function overloads (including constructors). Example:

class foo {
    private _name: any;
    constructor(name: string | number) {
        this._name = name;
    }
}
var f1 = new foo("bar");
var f2 = new foo(1);

try/catch with InputMismatchException creates infinite loop

You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

       catch (Exception e) {
            System.out.println("Error!");
           input.next();// Move to next other wise exception
        }

Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

    Scanner scanner = new Scanner(System.in);
    int n1 = 0, n2 = 0;
    boolean bError = true;
    while (bError) {
        if (scanner.hasNextInt())
            n1 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        if (scanner.hasNextInt())
            n2 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        bError = false;
    }
    System.out.println(n1);
    System.out.println(n2);

Javadoc of Scanner

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

How to make a node.js application run permanently?

If you just want to run your node app in the terminal always, just use screen.

Install on ubuntu/ debian:

sudo apt-get install screen

Usage:

$ screen
$ node /path/to/app.js

ctrl + a and then ctrl + d to dismiss

To get is back:

One screen: screen -r

If there's more than one you can list all the screens with: screen -ls

And then: screen -r pid_number

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked />

HTML5 does not require attributes to have values

Format telephone and credit card numbers in AngularJS

I took aberke's solution and modified it to suit my taste.

  • It produces a single input element
  • It optionally accepts extensions
  • For US numbers it skips the leading country code
  • Standard naming conventions
  • Uses class from using code; doesn't make up a class
  • Allows use of any other attributes allowed on an input element

My Code Pen

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('exampleController',_x000D_
  function exampleController($scope) {_x000D_
    $scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}};_x000D_
    $scope.homePhonePrompt = "Home Phone";_x000D_
  });_x000D_
_x000D_
myApp_x000D_
/*_x000D_
    Intended use:_x000D_
    <phone-number placeholder='prompt' model='someModel.phonenumber' />_x000D_
    Where: _x000D_
      someModel.phonenumber: {String} value which to bind formatted or unformatted phone number_x000D_
_x000D_
    prompt: {String} text to keep in placeholder when no numeric input entered_x000D_
*/_x000D_
.directive('phoneNumber',_x000D_
  ['$filter',_x000D_
  function ($filter) {_x000D_
    function link(scope, element, attributes) {_x000D_
_x000D_
      // scope.inputValue is the value of input element used in template_x000D_
      scope.inputValue = scope.phoneNumberModel;_x000D_
_x000D_
      scope.$watch('inputValue', function (value, oldValue) {_x000D_
_x000D_
        value = String(value);_x000D_
        var number = value.replace(/[^0-9]+/g, '');_x000D_
        scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension);_x000D_
        scope.phoneNumberModel = scope.inputValue;_x000D_
      });_x000D_
    }_x000D_
_x000D_
    return {_x000D_
      link: link,_x000D_
      restrict: 'E',_x000D_
      replace: true,_x000D_
      scope: {_x000D_
        phoneNumberPlaceholder: '@placeholder',_x000D_
        phoneNumberModel: '=model',_x000D_
        allowExtension: '=extension'_x000D_
      },_x000D_
      template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />'_x000D_
    };_x000D_
  }_x000D_
  ]_x000D_
)_x000D_
/* _x000D_
    Format phonenumber as: (aaa) ppp-nnnnxeeeee_x000D_
    or as close as possible if phonenumber length is not 10_x000D_
    does not allow country code or extensions > 5 characters long_x000D_
*/_x000D_
.filter('phoneNumber', _x000D_
  function() {_x000D_
    return function(number, allowExtension) {_x000D_
      /* _x000D_
      @param {Number | String} number - Number that will be formatted as telephone number_x000D_
      Returns formatted number: (###) ###-#### x #####_x000D_
      if number.length < 4: ###_x000D_
      else if number.length < 7: (###) ###_x000D_
      removes country codes_x000D_
      */_x000D_
      if (!number) {_x000D_
        return '';_x000D_
      }_x000D_
_x000D_
      number = String(number);_x000D_
      number = number.replace(/[^0-9]+/g, '');_x000D_
      _x000D_
      // Will return formattedNumber. _x000D_
      // If phonenumber isn't longer than an area code, just show number_x000D_
      var formattedNumber = number;_x000D_
_x000D_
      // if the first character is '1', strip it out _x000D_
      var c = (number[0] == '1') ? '1 ' : '';_x000D_
      number = number[0] == '1' ? number.slice(1) : number;_x000D_
_x000D_
      // (###) ###-#### as (areaCode) prefix-endxextension_x000D_
      var areaCode = number.substring(0, 3);_x000D_
      var prefix = number.substring(3, 6);_x000D_
      var end = number.substring(6, 10);_x000D_
      var extension = number.substring(10, 15);_x000D_
_x000D_
      if (prefix) {_x000D_
        //formattedNumber = (c + "(" + area + ") " + front);_x000D_
        formattedNumber = ("(" + areaCode + ") " + prefix);_x000D_
      }_x000D_
      if (end) {_x000D_
        formattedNumber += ("-" + end);_x000D_
      }_x000D_
      if (allowExtension && extension) {_x000D_
        formattedNumber += ("x" + extension);_x000D_
      }_x000D_
      return formattedNumber;_x000D_
    };_x000D_
  }_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="exampleController">_x000D_
  <p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p>_x000D_
  <p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p>_x000D_
        <phone-number id="homePhone"_x000D_
                      class="form-control" _x000D_
                      placeholder="Home Phone" _x000D_
                      model="user.profile.HomePhone"_x000D_
                      ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

TextFX menu is missing in Notepad++

Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.

How to display special characters in PHP

After much banging-head-on-table, I have a bit better understanding of the issue that I wanted to post for anyone else who may have had this issue.

While the UTF-8 character set will display special characters on the client, the server, on the other hand, may not be so accomodating and would print special characters such as à and è as ? and ?.

To make sure your server will print them correctly, use the ISO-8859-1 charset:

<?php
    /*Just for your server-side code*/
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"><!-- Your HTML file can still use UTF-8-->
        <title>Untitled Document</title>
    </head>
    <body>
        <?= "àè" ?>
    </body>
</html>

This will print correctly: àè


Edit (4 years later):

I have a little better understanding now. The reason this works is that the client (browser) is being told, through the response header(), to expect an ISO-8859-1 text/html file. (As others have mentioned, you can also do this by updating your .ini or .htaccess files.) Then, once the browser begins to parse that given file into the DOM, the output will obey any <meta charset=""> rule but keep your ISO characters intact.

How do I pass options to the Selenium Chrome driver using Python?

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')

# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())

Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.

get launchable activity name of package from adb

#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'

sample:

getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI

How do I find files with a path length greater than 260 characters in Windows?

From http://www.powershellmagazine.com/2012/07/24/jaap-brassers-favorite-powershell-tips-and-tricks/:

Get-ChildItem –Force –Recurse –ErrorAction SilentlyContinue –ErrorVariable AccessDenied

the first part just iterates through this and sub-folders; using -ErrorVariable AccessDenied means push the offending items into the powershell variable AccessDenied.

You can then scan through the variable like so

$AccessDenied |
Where-Object { $_.Exception -match "must be less than 260 characters" } |
ForEach-Object { $_.TargetObject }

If you don't care about these files (may be applicable in some cases), simply drop the -ErrorVariable AccessDenied part.

sed edit file in place

If you are replacing the same amount of characters and after carefully reading “In-place” editing of files...

You can also use the redirection operator <> to open the file to read and write:

sed 's/foo/bar/g' file 1<> file

See it live:

$ cat file
hello
i am here                           # see "here"
$ sed 's/here/away/' file 1<> file  # Run the `sed` command
$ cat file
hello
i am away                           # this line is changed now

From Bash Reference Manual ? 3.6.10 Opening File Descriptors for Reading and Writing:

The redirection operator

[n]<>word

causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.

What is TypeScript and why would I use it in place of JavaScript?

Ecma script 5 (ES5) which all browser support and precompiled. ES6/ES2015 and ES/2016 came this year with lots of changes so to pop up these changes there is something in between which should take cares about so TypeScript.

• TypeScript is Types -> Means we have to define datatype of each property and methods. If you know C# then Typescript is easy to understand.

• Big advantage of TypeScript is we identify Type related issues early before going to production. This allows unit tests to fail if there is any type mismatch.

Setting font on NSAttributedString on UITextView disregards line spacing

//For proper line spacing

NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];

UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];

[attributedString1 appendAttributedString:attributedString2];

How to send JSON instead of a query string with $.ajax?

While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!

Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:

 var data = {USER : localProfile,  
        INSTANCE : "HTHACKNEY",  
        PAGE : $('select[name="PAGE"]').val(), 
        TITLE : $("input[name='TITLE']").val(), 
        HTML : html,
        STARTDATE : $("input[name='STARTDATE']").val(), 
        ENDDATE : $("input[name='ENDDATE']").val(),
        ARCHIVE : $("input[name='ARCHIVE']").val(), 
        ACTIVE : $("input[name='ACTIVE']").val(), 
        URGENT : $("input[name='URGENT']").val(), 
        AUTHLST :  authStr};
        //console.log(data);
       $.ajax({
            type: "POST",
           url:   "http://www.domian.com/webservicepgm?callback=?",
           data:  data,
           dataType:'jsonp'
       }).
       done(function(data){
         //handle data.WHATEVER
       });

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Difference between web server, web container and application server

A Web application runs within a Web container of a Web server. The Web container provides the runtime environment through components that provide naming context and life cycle management. Some Web servers may also provide additional services such as security and concurrency control. A Web server may work with an EJB server to provide some of those services. A Web server, however, does not need to be located on the same machine as an EJB server.

Web applications are composed of web components and other data such as HTML pages. Web components can be servlets, JSP pages created with the JavaServer Pages™ technology, web filters, and web event listeners. These components typically execute in a web server and may respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used to generate HTML pages that are an application’s user interface. They may also be used to generate XML or other format data that is consumed by other application components.

Source: http://www.service-architecture.com/articles/application-servers/j2ee_web_server_or_container.html

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).

For more information try this link.

How to create enum like type in TypeScript?

Just another note that you can a id/string enum with the following:

class EnumyObjects{
    public static BOUNCE={str:"Bounce",id:1};
    public static DROP={str:"Drop",id:2};
    public static FALL={str:"Fall",id:3};


}

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

I would look for an existing mapping of your 3rd party JS libraries that support Script# or SharpKit. Users of these C# to .js cross compilers will have faced the problem you now face and might have published an open source program to scan your 3rd party lib and convert into skeleton C# classes. If so hack the scanner program to generate TypeScript in place of C#.

Failing that, translating a C# public interface for your 3rd party lib into TypeScript definitions might be simpler than doing the same by reading the source JavaScript.

My special interest is Sencha's ExtJS RIA framework and I know there have been projects published to generate a C# interpretation for Script# or SharpKit

How to get selected path and name of the file opened with file dialog?

The below command is enough to get the path of the file from a dialog box -

my_FileName = Application.GetOpenFilename("Excel Files (*.tsv), *.txt")

TypeScript: casting HTMLElement

Rather than using a type assertion, type guard, or any to work around the issue, a more elegant solution would be to use generics to indicate the type of element you're selecting.

Unfortunately, getElementsByName is not generic, but querySelector and querySelectorAll are. (querySelector and querySelectorAll are also far more flexible, and so might be preferable in most cases.)

If you pass a tag name alone into querySelector or querySelectorAll, it will automatically be typed properly due to the following line in lib.dom.d.ts:

querySelector<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;

For example, to select the first script tag on the page, as in your question, you can do:

const script = document.querySelector('script')!;

And that's it - TypeScript can now infer that script is now an HTMLScriptElement.

Use querySelector when you need to select a single element. If you need to select multiple elements, use querySelectorAll. For example:

document.querySelectorAll('script')

results in a type of NodeListOf<HTMLScriptElement>.

If you need a more complicated selector, you can pass a type parameter to indicate the type of the element you're going to select. For example:

const ageInput = document.querySelector<HTMLInputElement>('form input[name="age"]')!;

results in ageInput being typed as an HTMLInputElement.

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

Error TF30063: You are not authorized to access ... \DefaultCollection

What isn't officially an answer here, but worked for me (the other answers didn't help): Click Team Explorer tab -> Connect hyperlink - connect\choose repository. And it works.

Twitter API returns error 215, Bad Authentication Data

FOUND A SOLUTION - using the Abraham TwitterOAuth library. If you are using an older implementation, the following lines should be added after the new TwitterOAuth object is instantiated:

$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';

The first 2 lines are now documented in Abraham library Readme file, but the 3rd one is not. Also make sure that your oauth_version is still 1.0.

Here is my code for getting all user data from 'users/show' with a newly authenticated user and returning the user full name and user icon with 1.1 - the following code is implemented in the authentication callback file:

session_start();
require ('twitteroauth/twitteroauth.php');
require ('twitteroauth/config.php');

$consumer_key = '****************';
$consumer_secret = '**********************************';

$to = new TwitterOAuth($consumer_key, $consumer_secret);

$tok = $to->getRequestToken('http://exampleredirect.com?twitoa=1');

$token = $tok['oauth_token'];
$secret = $tok['oauth_token_secret'];

//save tokens to session
$_SESSION['ttok'] = $token;
$_SESSION['tsec'] = $secret;

$request_link = $to->getAuthorizeURL($token,TRUE);

header('Location: ' . $request_link);

The following code then is in the redirect after authentication and token request

if($_REQUEST['twitoa']==1){
    require ('twitteroauth/twitteroauth.php');
    require_once('twitteroauth/config.php');
    //Twitter Creds
    $consumer_key = '*****************';
    $consumer_secret = '************************************';

    $oauth_token = $_GET['oauth_token']; //ex Request vals->http://domain.com/twitter_callback.php?oauth_token=MQZFhVRAP6jjsJdTunRYPXoPFzsXXKK0mQS3SxhNXZI&oauth_verifier=A5tYHnAsbxf3DBinZ1dZEj0hPgVdQ6vvjBJYg5UdJI

    $ttok = $_SESSION['ttok'];
    $tsec = $_SESSION['tsec'];

    $to = new TwitterOAuth($consumer_key, $consumer_secret, $ttok, $tsec);
    $tok = $to->getAccessToken();
    $btok = $tok['oauth_token'];
    $bsec = $tok['oauth_token_secret'];
    $twit_u_id = $tok['user_id'];
    $twit_screen_name = $tok['screen_name'];

    //Twitter 1.1 DEBUG
    //print_r($tok);
    //echo '<br/><br/>';
    //print_r($to);
    //echo '<br/><br/>';
    //echo $btok . '<br/><br/>';
    //echo $bsec . '<br/><br/>';
    //echo $twit_u_id . '<br/><br/>';
    //echo $twit_screen_name . '<br/><br/>';

    $twit_screen_name=urlencode($twit_screen_name);
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $btok, $bsec);
    $connection->host = "https://api.twitter.com/1.1/";
    $connection->ssl_verifypeer = TRUE;
    $connection->content_type = 'application/x-www-form-urlencoded';
    $ucontent = $connection->get('users/show', array('screen_name' => $twit_screen_name));

    //echo 'connection:<br/><br/>';
    //print_r($connection);
    //echo '<br/><br/>';
    //print_r($ucontent);

    $t_user_name = $ucontent->name;
    $t_user_icon = $ucontent->profile_image_url;

    //echo $t_user_name.'<br/><br/>';
    //echo $t_user_icon.'<br/><br/>';
}

It took me way too long to figure this one out. Hope this helps someone!!

How to left align a fixed width string?

You can prefix the size requirement with - to left-justify:

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

set the width of select2 input (through Angular-ui directive)

Easier CSS solution independent from select2

//HTML
<select id="" class="input-xlg">
</select>
<input type="text" id="" name="" value="" class="input-lg" />

//CSS
.input-xxsm {
  width: 40px!important; //for 2 digits 
}

.input-xsm {
  width: 60px!important; //for 4 digits 
}

.input-sm {
  width: 100px!important; //for short options   
}

.input-md {
  width: 160px!important; //for medium long options 
}

.input-lg {
  width: 220px!important; //for long options    
}

.input-xlg {
  width: 300px!important; //for very long options   
}

.input-xxlg {
  width: 100%!important; //100% of parent   
}

How to copy directory recursively in python and overwrite all?

My simple answer.

def get_files_tree(src="src_path"):
    req_files = []
    for r, d, files in os.walk(src):
        for file in files:
            src_file = os.path.join(r, file)
            src_file = src_file.replace('\\', '/')
            if src_file.endswith('.db'):
                continue
            req_files.append(src_file)

    return req_files
def copy_tree_force(src_path="",dest_path=""):
    """
    make sure that all the paths has correct slash characters.
    """
    for cf in get_files_tree(src=src_path):
        df= cf.replace(src_path, dest_path)
        if not os.path.exists(os.path.dirname(df)):
            os.makedirs(os.path.dirname(df))
        shutil.copy2(cf, df)

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

VS 2012: Scroll Solution Explorer to current file

There are many ways to do this:

Go to current File once:

  • Visual Studio 2013

    VS 13 has it's own shortcut to do this: Ctrl+\, S (Press Ctrl + \, Release both keys, Press the S key)

    You can edit this default shortcut, if you are searching for SolutionExplorer.SyncWithActiveDocument in your Keyboard Settings (Tools->Options->Enviornment->Keyboard)

    In addition there is also a new icon in the Solution Explorer, more about this here.

    Sync with Active Document Button in VS2013 - Solution Explorer

  • Visual Studio 2012

    If you use VS 2012, there is a great plugin to add this new functionality from VS2013 to VS2012: . The default shortcut is strg + alt + ü. I think this one is the best, as navigating to the solution explorer is mapped to strg + ü.

  • Resharper

    If you use Resharper try Shift+Alt+L

    This is a nice mapping as you can use Strg+Alt+L for navigating to the solution explorer

Track current file all the time:

  • Visual Studio >= 2012:

    If you like to track your current file in the solution explorer all the time, you can use the solution from the accepted answer (Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer), but I think this can get very annoying in large projects.

Split (explode) pandas dataframe string entry to separate rows

One-liner using split(___, expand=True) and the level and name arguments to reset_index():

>>> b = a.var1.str.split(',', expand=True).set_index(a.var2).stack().reset_index(level=0, name='var1')
>>> b
   var2 var1
0     1    a
1     1    b
2     1    c
0     2    d
1     2    e
2     2    f

If you need b to look exactly like in the question, you can additionally do:

>>> b = b.reset_index(drop=True)[['var1', 'var2']]
>>> b
  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

How to copy a string of std::string type in C++?

strcpy is only for C strings. For std::string you copy it like any C++ object.

std::string a = "text";
std::string b = a; // copy a into b

If you want to concatenate strings you can use the + operator:

std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;

You can even do many at once:

std::string c = a + " " + b + "hello";

Although "hello" + " world" doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"

Reversing an Array in Java

The following will reverse in place the array between indexes i and j (to reverse the whole array call reverse(a, 0, a.length - 1))

    public void reverse(int[] a, int i , int j) {
        int ii =  i;
        int jj = j;

        while (ii < jj) {
            swap(ii, jj);
            ++ii;
            --jj;
        }
    }

MySQL Select Date Equal to Today

Sounds like you need to add the formatting to the WHERE:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()

See SQL Fiddle with Demo

Regular Expression with wildcards to match any character

The following should work:

ABC: *\([a-zA-Z]+\) *(.+)

Explanation:

ABC:            # match literal characters 'ABC:'
 *              # zero or more spaces
\([a-zA-Z]+\)   # one or more letters inside of parentheses
 *              # zero or more spaces
(.+)            # capture one or more of any character (except newlines)

To get your desired grouping based on the comments below, you can use the following:

(ABC:) *(\([a-zA-Z]+\).+)

Parse Json string in C#

I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

Code to parse:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

Output:

AppName
Lorem ipsum dolor sit amet
1


AnotherAppName
consectetur adipisicing elit
String


ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text


Application
Ut enim ad minim veniam
100


LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.

Proper usage of .net MVC Html.CheckBoxFor

None of the above answers worked for me when binding back on POST, until I added the following in CSHTML

<div class="checkbox c-checkbox">
    <label>
        <input type="checkbox" id="xPrinting" name="xPrinting" value="true"  @Html.Raw( Model.xPrinting ? "checked" : "")>
        <span class=""></span>Printing
    </label>
</div>


// POST: Index

[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

How to save a BufferedImage as a File

You can save a BufferedImage object using write method of the javax.imageio.ImageIO class. The signature of the method is like this:

public static boolean write(RenderedImage im, String formatName, File output) throws IOException

Here im is the RenderedImage to be written, formatName is the String containing the informal name of the format (e.g. png) and output is the file object to be written to. An example usage of the method for PNG file format is shown below:

ImageIO.write(image, "png", file);