Programs & Examples On #Filtered index

Set min-width in HTML table's <td>

Try using an invisible element (or psuedoelement) to force the table-cell to expand.

td:before {
  content: '';
  display: block; 
  width: 5em;
}

JSFiddle: https://jsfiddle.net/cibulka/gf45uxr6/1/

java.util.Date vs java.sql.Date

tl;dr

Use neither.

Neither

java.util.Date vs java.sql.Date: when to use which and why?

Both of these classes are terrible, flawed in design and in implementation. Avoid like the Plague Coronavirus.

Instead use java.time classes, defined in in JSR 310. These classes are an industry-leading framework for working with date-time handling. These supplant entirely the bloody awful legacy classes such as Date, Calendar, SimpleDateFormat, and such.

java.util.Date

The first, java.util.Date is meant to represent a moment in UTC, meaning an offset from UTC of zero hours-minutes-seconds.

java.time.Instant

Now replaced by java.time.Instant.

Instant instant = Instant.now() ;  // Capture the current moment as seen in UTC.

java.time.OffsetDateTime

Instant is the basic building-block class of java.time. For more flexibility, use OffsetDateTime set to ZoneOffset.UTC for the same purpose: representing a moment in UTC.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

You can send this object to a database by using PreparedStatement::setObject with JDBC 4.2 or later.

myPreparedStatement.setObject( … , odt ) ;

Retrieve.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

java.sql.Date

The java.sql.Date class is also terrible and obsolete.

This class is meant to represent a date only, without a time-of-day and without a time zone. Unfortunately, in a terrible hack of a design, this class inherits from java.util.Date which represents a moment (a date with time-of-day in UTC). So this class is merely pretending to be date-only, while actually carrying a time-of-day and implicit offset of UTC. This causes so much confusion. Never use this class.

java.time.LocalDate

Instead, use java.time.LocalDate to track just a date (year, month, day-of-month) without any time-of-day nor any time zone or offset.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate ld = LocalDate.now( z ) ;    // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).

Send to the database.

myPreparedStatement.setObject( … , ld ) ;

Retrieve.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Android error: Failed to install *.apk on device *: timeout

I get this a lot. I'm on a Galaxy S too. I unplug the cable from the phone, plug it back in and try launching the app again from Eclipse, and it usually does the trick. Eclipse seems to lose the connection to the phone occasionally but this seems to kick it back to life.

Regular expression for number with length of 4, 5 or 6

If the language you use accepts {}, you can use [0-9]{4,6}.

If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?.

How to convert int[] to Integer[] in Java?

Rather than write your own code you can use an IntBuffer to wrap the existing int[] without having to copy the data into an Integer array

int[] a = {1,2,3,4};
IntBuffer b = IntBuffer.wrap(a);

IntBuffer implements comparable so you are able to use the code you already have written. Formally maps compare keys such that a.equals(b) is used to say two keys are equal, so two IntBuffers with array 1,2,3 - even if the arrays are in different memory locations - are said to be equal and so will work for your frequency code.

ArrayList<int[]> data = ... // load a dataset`

Map<IntBuffer, Double> frequencies = new HashMap<IntBuffer, Double>();

for(int[] a : data) {

    IntBuffer q = IntBuffer.wrap(a);

    if(frequencies.containsKey(q)) {
        frequencies.put(q, tfs.get(q) + p);
    } else {
        frequencies.put(q, p);
    }

}

Hope that helps

Why do abstract classes in Java have constructors?

Because another class could extend it, and the child class needs to invoke a superclass constructor.

‘ant’ is not recognized as an internal or external command

Need to see whether you got ant folder moved by mistake or unknowingly. It is set in environment variables.I resolved this once as mentioned below.

I removed ant folder by mistake and placed in another folder.I went to command prompt and typed "path". It has given me path as "F:\apache-ant-1.9.4\". So I moved the ant back to F drive and it resolved the issue.

how to implement a pop up dialog box in iOS

Yup, a UIAlertView is probably what you're looking for. Here's an example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No network connection" 
                                                message:@"You must be connected to the internet to use this app." 
                                               delegate:nil 
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];
[alert release];

If you want to do something more fancy, say display a custom UI in your UIAlertView, you can subclass UIAlertView and put in custom UI components in the init method. If you want to respond to a button press after a UIAlertView appears, you can set the delegate above and implement the - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex method.

You might also want to look at the UIActionSheet.

Composer Warning: openssl extension is missing. How to enable in WAMP

uncomment ;extension=php_openssl.dll in both

wamp\bin\php\php5.4.12\php.ini
wamp\bin\apache\Apache2.4.4\bin\php.ini

it will work

Visual Studio 2008 Product Key in Registry?

I found the product key for Visual Studio 2008 Professional under a slightly different key:

HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY

it was listed without the dashes as stated above.

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

Powershell 2 copy-item which creates a folder if doesn't exist

Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
    $filesplit = $sourceFile.split("\")
    $splitcount = $filesplit.count
    # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
    $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
    # Output List of source and dest 
    Write-Host ""
    Write-Host "===$sourceFile===" -ForegroundColor Green
    Write-Host "+++$destFile+++"
    # Create path and file, if they do not already exist
    $destPath = Split-Path $destFile
    If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
    If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}

Handling file renames in git

you have to git add css/mobile.css the new file and git rm css/iphone.css, so git knows about it. then it will show the same output in git status

you can see it clearly in the status output (the new name of the file):

# Untracked files:
#   (use "git add <file>..." to include in what will be committed)

and (the old name):

# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)

i think behind the scenes git mv is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name

Can't import database through phpmyadmin file size too large

Here is what I've done:

  1. Gone to my XAMPP installed directoy C:\xampp\php
  2. Open the "Configuration Settings" file named php.ini using your text editor, preferably you can also you Notepad for Windows machine.
  3. Somewhere nearby on line no 886, please update it to upload_max_filesize = 128M
  4. Similarly on line no 735 post_max_size = 128M
  5. On line no 442 max_execution_time = 300
  6. On line no 452 max_input_time = 60
  7. Restart your Apache from either XAMPP Control Panel or using CMD in Windows https://stackoverflow.com/a/6723485/969092

Done!

Using DataContractSerializer to serialize, but can't deserialize back

Here is how I've always done it:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

postgresql - replace all instances of a string within text field

Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -

select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;

How to force view controller orientation in iOS 8?

If you are using navigationViewController you should create your own superclass for this and override:

- (BOOL)shouldAutorotate {
  id currentViewController = self.topViewController;

  if ([currentViewController isKindOfClass:[SecondViewController class]])
    return NO;

  return YES;
}

this will disable rotation in SecondViewController but if you push your SecondViewController when your device is on portrait orientation then your SecondViewController will appear in portrait mode.

Assume that you are using storyboard. You have to create manual segue (How to) and in your "onClick" method:

- (IBAction)onPlayButtonClicked:(UIBarButtonItem *)sender {
  NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
  [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  [self performSegueWithIdentifier:@"PushPlayerViewController" sender:self];
}

This will force landscape orientation before your superclass disable autorotate feature.

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Difference between Divide and Conquer Algo and Dynamic Programming

  • Divide and Conquer
    • They broke into non-overlapping sub-problems
    • Example: factorial numbers i.e. fact(n) = n*fact(n-1)
fact(5) = 5* fact(4) = 5 * (4 * fact(3))= 5 * 4 * (3 *fact(2))= 5 * 4 * 3 * 2 * (fact(1))

As we can see above, no fact(x) is repeated so factorial has non overlapping problems.

  • Dynamic Programming
    • They Broke into overlapping sub-problems
    • Example: Fibonacci numbers i.e. fib(n) = fib(n-1) + fib(n-2)
fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1))

As we can see above, fib(4) and fib(3) both use fib(2). similarly so many fib(x) gets repeated. that's why Fibonacci has overlapping sub-problems.

  • As a result of the repetition of sub-problem in DP, we can keep such results in a table and save computation effort. this is called as memoization

How can I calculate divide and modulo for integers in C#?

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

Getting file size in Python?

Try

os.path.getsize(filename)

It should return the size of a file, reported by os.stat().

how to fix Cannot call sendRedirect() after the response has been committed?

you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

Replacing objects in array

Since you're using Lodash you could use _.map and _.find to make sure major browsers are supported.

In the end I would go with something like:

_x000D_
_x000D_
function mergeById(arr) {_x000D_
  return {_x000D_
    with: function(arr2) {_x000D_
      return _.map(arr, item => {_x000D_
        return _.find(arr2, obj => obj.id === item.id) || item_x000D_
      })_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
var result = mergeById([{id:'124',name:'qqq'}, _x000D_
           {id:'589',name:'www'}, _x000D_
           {id:'45',name:'eee'},_x000D_
           {id:'567',name:'rrr'}])_x000D_
    .with([{id:'124',name:'ttt'}, {id:'45',name:'yyy'}])_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://raw.githubusercontent.com/lodash/lodash/4.13.1/dist/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How to ignore the certificate check when ssl

Based on Adam's answer and Rob's comment I used this:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => certificate.Issuer == "CN=localhost";

which filters the "ignoring" somewhat. Other issuers can be added as required of course. This was tested in .NET 2.0 as we need to support some legacy code.

Fastest method of screen capturing on Windows

DXGI Desktop Capture

Project that captures the desktop image with DXGI duplication. Saves the captured image to the file in different image formats (*.bmp; *.jpg; *.tif).

This sample is written in C++. You also need some experience with DirectX (D3D11, D2D1).

What the Application Can Do

  • If you have more than one desktop monitor, you can choose.
  • Resize the captured desktop image.
  • Choose different scaling modes.
  • You can show or hide the mouse icon in the output image.
  • You can rotate the image for the output picture, or leave it as default.

Why does npm install say I have unmet dependencies?

The above answers didn't help me fully even after deleteting node_modules directory.

Below command helped me finally:

npm config set registry http://registry.npmjs.org/

Note that this pulls node modules over an insecure HTTP connection.

Src: https://stackoverflow.com/a/13119867/4082503

VirtualBox error "Failed to open a session for the virtual machine"

Updating VirtualBox to newest version fixed my issue.

How can I combine flexbox and vertical scroll in a full-height app?

The current spec says this regarding flex: 1 1 auto:

Sizes the item based on the width/height properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are either flex: auto, flex: initial, or flex: none, any positive free space after the items have been sized will be distributed evenly to the items with flex: auto.

http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common

It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0 (or any other smallish number).

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

How to set the From email address for mailx command?

In case you also want to include your real name in the from-field, you can use the following format

mailx -r "[email protected] (My Name)" -s "My Subject" ...

If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:

mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...

Hope this can save someone an hour of hard work/research!

make image( not background img) in div repeat?

It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.

<div id="rightflower">
<div id="divImg"></div> 
</div>

And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.

When should I create a destructor?

It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.

Clear the cache in JavaScript

You can also force the code to be reloaded every hour, like this, in PHP :

<?php
echo '<script language="JavaScript" src="js/myscript.js?token='.date('YmdH').'">';
?>

or

<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>

How can I get the nth character of a string?

Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];

...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

str = str + 1; // makes it point to 'E' now
char myChar =  *str;

I hope this helps.

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Closing Bootstrap modal onclick

Close the modal box using javascript

$('#product-options').modal('hide');

Open the modal box using javascript

$('#product-options').modal('show');

Toggle the modal box using javascript

$('#myModal').modal('toggle');

Means close the modal if it's open and vice versa.

Reading from text file until EOF repeats last line

Without to much modifications of the original code, it could become :

while (!iFile.eof())
{  
    int x;
    iFile >> x;
    if (!iFile.eof()) break;
    cerr << x << endl;
}

but I prefer the two other solutions above in general.

How can I check if a command exists in a shell script?

A function which works in both bash and zsh:

# Return the first pathname in $PATH for name in $1
function cmd_path () {
  if [[ $ZSH_VERSION ]]; then
    whence -cp "$1" 2> /dev/null
  else  # bash
     type -P "$1"  # No output if not in $PATH
  fi
}

Non-zero is returned if the command is not found in $PATH.

What determines the monitor my app runs on?

Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.

So I am not sure there is a way to tell every program where to open. Hope that helps some.

Open JQuery Datepicker by clicking on an image w/ no input field

Turns out that a simple hidden input field does the job:

<input type="hidden" id="dp" />

And then use the buttonImage attribute for your image, like normal:

    $("#dp").datepicker({
        buttonImage: '../images/icon_star.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
     });

Initially I tried a text input field and then set a display:none style on it, but that caused the calendar to emerge from the top of the browser, rather than from where the user clicked. But the hidden field works as desired.

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

How can I reorder a list?

You can provide your own sort function to list.sort():

The sort() method takes optional arguments for controlling the comparisons.

  • cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

  • key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

  • reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

My Thought,

Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.

Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.

How can I hide an HTML table row <tr> so that it takes up no space?

You can use style display:none with tr to hide and it will work with all browsers.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

A CSS selector to get last visible div

Try

div:not([style*="display: none"])

How can I add to a List's first position?

You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

Bootstrap: Open Another Modal in Modal

data-dismiss makes the current modal window force close

data-toggle opens up a new modal with the href content inside it

<a data-dismiss="modal" data-toggle="modal" href="#lost">Click</a>

or

<a data-dismiss="modal" onclick="call the new div here">Click</a>

do let us know if it works.

Why should I use the keyword "final" on a method parameter in Java?

Stop a Variable’s Reassignment

While these answers are intellectually interesting, I've not read the short simple answer:

Use the keyword final when you want the compiler to prevent a variable from being re-assigned to a different object.

Whether the variable is a static variable, member variable, local variable, or argument/parameter variable, the effect is entirely the same.

Example

Let’s see the effect in action.

Consider this simple method, where the two variables (arg and x) can both be re-assigned different objects.

// Example use of this method: 
//   this.doSomething( "tiger" );
void doSomething( String arg ) {
  String x = arg;   // Both variables now point to the same String object.
  x = "elephant";   // This variable now points to a different String object.
  arg = "giraffe";  // Ditto. Now neither variable points to the original passed String.
}

Mark the local variable as final. This results in a compiler error.

void doSomething( String arg ) {
  final String x = arg;  // Mark variable as 'final'.
  x = "elephant";  // Compiler error: The final local variable x cannot be assigned. 
  arg = "giraffe";  
}

Instead, let’s mark the parameter variable as final. This too results in a compiler error.

void doSomething( final String arg ) {  // Mark argument as 'final'.
  String x = arg;   
  x = "elephant"; 
  arg = "giraffe";  // Compiler error: The passed argument variable arg cannot be re-assigned to another object.
}

Moral of the story:

If you want to ensure a variable always points to the same object, mark the variable final.

Never Reassign Arguments

As good programming practice (in any language), you should never re-assign a parameter/argument variable to an object other than the object passed by the calling method. In the examples above, one should never write the line arg = . Since humans make mistakes, and programmers are human, let’s ask the compiler to assist us. Mark every parameter/argument variable as 'final' so that the compiler may find and flag any such re-assignments.

In Retrospect

As noted in other answers… Given Java's original design goal of helping programmers to avoid dumb mistakes such as reading past the end of an array, Java should have been designed to automatically enforce all parameter/argument variables as 'final'. In other words, Arguments should not be variables. But hindsight is 20/20 vision, and the Java designers had their hands full at the time.

So, always add final to all arguments?

Should we add final to each and every method parameter being declared?

  • In theory, yes.
  • In practice, no.
    ? Add final only when the method’s code is long or complicated, where the argument may be mistaken for a local or member variable and possibly re-assigned.

If you buy into the practice of never re-assigning an argument, you will be inclined to add a final to each. But this is tedious and makes the declaration a bit harder to read.

For short simple code where the argument is obviously an argument, and not a local variable nor a member variable, I do not bother adding the final. If the code is quite obvious, with no chance of me nor any other programmer doing maintenance or refactoring accidentally mistaking the argument variable as something other than an argument, then don’t bother. In my own work, I add final only in longer or more involved code where an argument might mistaken for a local or member variable.

#Another case added for the completeness

public class MyClass {
    private int x;
    //getters and setters
}

void doSomething( final MyClass arg ) {  // Mark argument as 'final'.
  
   arg =  new MyClass();  // Compiler error: The passed argument variable arg  cannot be re-assigned to another object.

   arg.setX(20); // allowed
  // We can re-assign properties of argument which is marked as final
 }

record

Java 16 brings the new records feature. A record is a very brief way to define a class whose central purpose is to merely carry data, immutably and transparently.

You simply declare the class name along with the names and types of its member fields. The compiler implicitly provides the constructor, getters, equals & hashCode, and toString.

The fields are read-only, with no setters. So a record is one case where there is no need to mark the arguments final. They are already effectively final. Indeed, the compiler forbids using final when declaring the fields of a record.

public record Employee( String name , LocalDate whenHired )  //  Marking `final` here is *not* allowed.
{
}

If you provide an optional constructor, there you can mark final.

public record Employee(String name , LocalDate whenHired)  //  Marking `final` here is *not* allowed.
{
    public Employee ( final String name , final LocalDate whenHired )  //  Marking `final` here *is* allowed.
    {
        this.name = name;
        whenHired = LocalDate.MIN;  //  Compiler error, because of `final`. 
        this.whenHired = whenHired;
    }
}

Python: read all text file lines in loop

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

get dictionary value by key

Why not just use key name on dictionary, C# has this:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 dict.Add("UserID", "test");
 string userIDFromDictionaryByKey = dict["UserID"];

If you look at the tip suggestion:

enter image description here

gpg: no valid OpenPGP data found

Managed to resolve it. separated the command in to two commands and used directly the file name which was downloaded example -

wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key    add -

can be separated into

  1. wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key
  2. sudo apt-key add jenkins-ci.org.key

How to type a new line character in SQL Server Management Studio

In SSMS, you can't print new line with select, just using PRINT instead

DECLARE @text NVARCHAR(100)
SET @text = concat(N'This is line 1.', CHAR(10), N'This is line 2.')
PRINT @text

Python slice first and last element in list

More General Case: Return N points from each end of list

The answers work for the specific first and last, but some, like myself, may be looking for a solution that can be applied to a more general case in which you can return the top N points from either side of the list (say you have a sorted list and only want the 5 highest or lowest), i came up with the following solution:

In [1]
def GetWings(inlist,winglen):
    if len(inlist)<=winglen*2:
        outlist=inlist
    else:
        outlist=list(inlist[:winglen])
        outlist.extend(list(inlist[-winglen:]))
    return outlist

and an example to return bottom and top 3 numbers from list 1-10:

In [2]
GetWings([1,2,3,4,5,6,7,8,9,10],3)

#Out[2]
#[1, 2, 3, 8, 9, 10]

Replacing .NET WebBrowser control with a better browser, like Chrome?

Checkout CefSharp .Net bindings, a project I started a while back that thankfully got picked up by the community and turned into something wonderful.

The project wraps the Chromium Embedded Framework and has been used in a number of major projects including Rdio's Windows client, Facebook Messenger for Windows and Github for Windows.

It features browser controls for WPF and Winforms and has tons of features and extension points. Being based on Chromium it's blisteringly fast too.

Grab it from NuGet: Install-Package CefSharp.Wpf or Install-Package CefSharp.WinForms

Check out examples and give your thoughts/feedback/pull-requests: https://github.com/cefsharp/CefSharp

BSD Licensed

Bootstrap Modal before form Submit

It is easy to solve, only create an hidden submit:

<button id="submitCadastro" type="button">ENVIAR</button>
<input type="submit" id="submitCadastroHidden" style="display: none;" >

with jQuery you click the submit:

$("#submitCadastro").click(function(){
    if($("#checkDocumentos").prop("checked") == false){
        //alert("Aceite os termos e condições primeiro!.");
        $("#modalERROR").modal("show");
    }else{
        //$("#formCadastro").submit();
        $("#submitCadastroHidden").click();                     
    }
});

What is the difference between Python and IPython?

ipython is an interactive shell built with python.

From the project website:

IPython provides a rich toolkit to help you make the most out of using Python, with:

  • Powerful Python shells (terminal and Qt-based).
  • A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media.
  • Support for interactive data visualization and use of GUI toolkits.
  • Flexible, embeddable interpreters to load into your own projects.
  • Easy to use, high performance tools for parallel computing.

Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features.

I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython.

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

ARM compilation error, VFP registers used by executable, not object file

I encountered the issue using Atollic for ARM on STM32F4 (I guess it applies to all STM32 with FPU).

Using SW floating point didn't worked well for me (thus compiling correctly).

When STM32cubeMX generates code for TrueStudio (Atollic), it doesn't set an FPU unit in C/C++ build settings (not sure about generated code for other IDEs).

Set a FPU in "Target" for (under project Properties build settings):

  • Assembler
  • C Compiler
  • C Linker

Then you have the choice to Mix HW/SW fp or use HW.

Generated command lines are added with this for the intended target:

-mfloat-abi=hard -mfpu=fpv4-sp-d16

Add 2 hours to current time in MySQL?

This will also work

SELECT NAME 
FROM GEO_LOCATION
WHERE MODIFY_ON BETWEEN SYSDATE() - INTERVAL 2 HOUR AND SYSDATE()

How do I find duplicates across multiple columns?

Using count(*) over(partition by...) provides a simple and efficient means to locate unwanted repetition, whilst also list all affected rows and all wanted columns:

SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city

While most recent RDBMS versions support count(*) over(partition by...) MySQL V 8.0 introduced "window functions", as seen below (in MySQL 8.0)

CREATE TABLE stuff(
   id   INTEGER  NOT NULL
  ,name VARCHAR(60) NOT NULL
  ,city VARCHAR(60) NOT NULL
);
INSERT INTO stuff(id,name,city) VALUES 
  (904834,'jim','London')
, (904835,'jim','London')
, (90145,'Fred','Paris')
, (90132,'Fred','Paris')
, (90133,'Fred','Paris')

, (923457,'Barney','New York') # not expected in result
;
SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city
    id | name | city   | qty
-----: | :--- | :----- | --:
 90145 | Fred | Paris  |   3
 90132 | Fred | Paris  |   3
 90133 | Fred | Paris  |   3
904834 | jim  | London |   2
904835 | jim  | London |   2

db<>fiddle here

Window functions. MySQL now supports window functions that, for each row from a query, perform a calculation using rows related to that row. These include functions such as RANK(), LAG(), and NTILE(). In addition, several existing aggregate functions now can be used as window functions; for example, SUM() and AVG(). For more information, see Section 12.21, “Window Functions”.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

The one liner to get true postives etc. out of the confusion matrix is to ravel it:

from sklearn.metrics import confusion_matrix

y_true = [1, 1, 0, 0]
y_pred = [1, 0, 1, 0]   

tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(tn, fp, fn, tp)  # 1 1 1 1

How to solve "Fatal error: Class 'MySQLi' not found"?

Some distributions (such as Gentoo) support multiple installations of PHP, and you have to make sure you're using one with mysqli installed and enabled.

On Gentoo, I had installed a new PHP (with the mysqli USE flag enabled), but I needed to activate the new version of PHP (since the old one must have been missing mysqli):

# eselect php list apache2
  [1]   php5.3 *
  [2]   php5.5
# eselect php set apache2 2
You have to run `/etc/init.d/apache2 restart' for the changes to take effect
# /etc/init.d/apache2 restart

python location on mac osx

On High Sierra

which python

shows the default python but if you downloaded and installed the latest version from python.org you can find it by:

which python3.6

which on my machine shows

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.

DELETE FROM tableA
WHERE ROWID IN 
  ( SELECT q.ROWID
    FROM tableA q
      INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
    WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
      AND (u.FldFormat = 'Date'));

Search input with an icon Bootstrap 4

Update 2019

Why not use an input-group?

<div class="input-group col-md-4">
      <input class="form-control py-2" type="search" value="search" id="example-search-input">
      <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i>
        </button>
      </span>
</div>

And, you can make it appear inside the input using the border utils...

        <div class="input-group col-md-4">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
              <button class="btn btn-outline-secondary border-left-0 border" type="button">
                    <i class="fa fa-search"></i>
              </button>
            </span>
        </div>

Or, using a input-group-text w/o the gray background so the icon appears inside the input...

        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
            </span>
        </div>

Alternately, you can use the grid (row>col-) with no gutter spacing:

<div class="row no-gutters">
     <div class="col">
          <input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
     </div>
     <div class="col-auto">
          <button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
             <i class="fa fa-search"></i>
          </button>
     </div>
</div>

Or, prepend the icon like this...

<div class="input-group">
  <span class="input-group-prepend">
    <div class="input-group-text bg-transparent border-right-0">
      <i class="fa fa-search"></i>
    </div>
  </span>
  <input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
  <span class="input-group-append">
    <button class="btn btn-outline-secondary border-left-0 border" type="button">
     Search
    </button>
  </span>
</div>

Demo of all Bootstrap 4 icon input options


enter image description here


Example with validation icons

Checking whether a String contains a number value in Java

 try{
      Integer.parseInt(string);
      return true;
}catch (Exception  e){
      return false;
}

or you can do it himself:

 for ( int i = 0; i < string.length; ++i ) {
      if ( !( string[i] >= '0' || string[i] <= '9' ) )
           return false;
 }
 return true;

Of course is also function isDigit

IE and Edge fix for object-fit: cover;

Here is the only CSS solution to fix this. Use the below css.

.row-fluid {
  display: table;
}

.row-fluid .span6 {
  display: table-cell;
  vertical-align: top;
}

.vc_single_image-wrapper {
  position: relative;
}

.vc_single_image-wrapper .image-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
}

HTML from the OP:

<div class="vc_single_image-wrapper   vc_box_border_grey">
  <div class="image-wrapper" style="background-image: url(http://i0.wp.com/www.homedecor.nl/wp-content/uploads/2016/03/Gordijnen-Home-Decor-2.jpg?fit=952%2C480;"></div>
</div>

try this, it should work. also remove float from .row-fluid .span6

Convert double to string C++?

In C++11, use std::to_string if you can accept the default format (%f).

storedCorrect[count]= "(" + std::to_string(c1) + ", " + std::to_string(c2) + ")";

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Difference between PACKETS and FRAMES

Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data, segment, packet, frame and bit. And the term PDU (Protocol Data Unit) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.

When we come to your question, we can call all of them by using the general term PDU, but if you want to call them specifically at a given layer:

  • Data: PDU of Application, Presentation and Session Layers
  • Segment: PDU of Transport Layer
  • Packet: PDU of network Layer
  • Frame: PDU of data-link Layer
  • Bit: PDU of physical Layer

Here is a diagram, since a picture is worth a thousand words: a picture is worth a thousand words

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

How do I use HTML as the view engine in Express?

I recommend using https://www.npmjs.com/package/express-es6-template-engine - extremely lightwave and blazingly fast template engine. The name is a bit misleading as it can work without expressjs too.

The basics required to integrate express-es6-template-engine in your app are pretty simple and quite straight forward to implement:

_x000D_
_x000D_
const express = require('express'),_x000D_
  es6Renderer = require('express-es6-template-engine'),_x000D_
  app = express();_x000D_
  _x000D_
app.engine('html', es6Renderer);_x000D_
app.set('views', 'views');_x000D_
app.set('view engine', 'html');_x000D_
 _x000D_
app.get('/', function(req, res) {_x000D_
  res.render('index', {locals: {title: 'Welcome!'}});_x000D_
});_x000D_
 _x000D_
app.listen(3000);
_x000D_
_x000D_
_x000D_ Here is the content of the index.html file locate inside your 'views' directory:

<!DOCTYPE html>
<html>
<body>
    <h1>${title}</h1>
</body>
</html>

jQuery: how to find first visible input/select/textarea excluding buttons?

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
    $(parent).find('input, textarea, select')
        .not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
        .filter(':enabled:visible:first')
        .focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('form#aspnetForm');

Element:

var el = $('form#aspnetForm');
focusFirst(el);

JQuery Ajax Post results in 500 Internal Server Error

Use a Try Catch block on your server side and in the catch block pass back the exception error to the client. This should give you a helpful error message.

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

Redirecting to a certain route based on condition

    $routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController}).
 .when('/login', {templateUrl: 'partials/index.html', controller: IndexController})
 .otherwise({redirectTo: '/index'});

datetimepicker is not a function jquery

For some reason this link solved my problem...I don't know why tho..

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Then this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

NOTE: I am using Bootstrap 3 and Jquery 1.11.3

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

How to close current tab in a browser window?

As for the people who are still visiting this page, you are only allowed to close a tab that is opened by a script OR by using the anchor tag of HTML with target _blank. Both those can be closed using the

<script>
    window.close();
</script>

How to check if there exists a process with a given pid in Python?

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

AngularJS: Service vs provider vs factory

My clarification on this matter:

Basically all of the mentioned types (service, factory, provider, etc.) are just creating and configuring global variables (that are of course global to the entire application), just as old fashioned global variables were.

While global variables are not recommended, the real usage of these global variables is to provide dependency injection, by passing the variable to the relevant controller.

There are many levels of complications in creating the values for the "global variables":

  1. Constant
    This defines an actual constant that should not be modified during the entire application, just like constants in other languages are (something that JavaScript lacks).
  2. Value
    This is a modifiable value or object, and it serves as some global variable, that can even be injected when creating other services or factories (see further on these). However, it must be a "literal value", which means that one has to write out the actual value, and cannot use any computation or programming logic (in other words 39 or myText or {prop: "value"} are OK, but 2 +2 is not).
  3. Factory
    A more general value, that is possible to be computed right away. It works by passing a function to AngularJS with the logic needed to compute the value and AngularJS executes it, and it saves the return value in the named variable.
    Note that it is possible to return a object (in which case it will function similar to a service) or a function (that will be saved in the variable as a callback function).
  4. Service
    A service is a more stripped-down version of factory which is valid only when the value is an object, and it allows for writing any logic directly in the function (as if it would be a constructor), as well as declaring and accessing the object properties using the this keyword.
  5. Provider
    Unlike a service which is a simplified version of factory, a provider is a more complex, but more flexible way of initializing the "global" variables, with the biggest flexibility being the option to set values from the app.config.
    It works like using a combination of service and provider, by passing to provider a function that has properties declared using the this keyword, which can be used from the app.config.
    Then it needs to have a separate $.get function which is executed by AngularJS after setting the above properties via the app.config file , and this $.get function behaves just as the factory above, in that its return value is used to initialize the "global" variables.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan

Here is an extract from it:

openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>

openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>

openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>

How to include quotes in a string

As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:

string msg = @"I want to learn ""c#""";

jQuery Ajax File Upload

Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.

    $('#UploadB1').click(function(e){        
    e.preventDefault();

    if (!fileupload.valid()) {
        return false;            
    }

    var myformData = new FormData();        
    myformData.append('file', $('#uploadFile')[0].files[0]);

    $("#UpdateMessage5").html("Uploading file ....");
    $("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");

    myformData.append('mode', 'fileUpload');
    myformData.append('myid', $('#myid').val());
    myformData.append('type', $('#fileType').val());
    //formData.append('myfile', file, file.name); 

    $.ajax({
        url: 'include/fetch.php',
        method: 'post',
        processData: false,
        contentType: false,
        cache: false,
        data: myformData,
        enctype: 'multipart/form-data',
        success: function(response){
            $("#UpdateMessage5").html(response); //.delay(2000).hide(1); 
            $("#UpdateMessage5").css("background","");

            console.log("file successfully submitted");
        },error: function(){
            console.log("not okay");
        }
    });
});

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Based on the link provided by Philip I got this to working

Worksheets("Final Analysis Sheet").Range("A4:G112").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\FTPDailycheck\TodaysImages\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

For a dataset of this format:

CONFIG000   1080.65 1080.87 1068.76 1083.52 1084.96 1080.31 1081.75 1079.98
CONFIG001   414.6   421.76  418.93  415.53  415.23  416.12  420.54  415.42
CONFIG010   1091.43 1079.2  1086.61 1086.58 1091.14 1080.58 1076.64 1083.67
CONFIG011   391.31  392.96  391.24  392.21  391.94  392.18  391.96  391.66
CONFIG100   1067.08 1062.1  1061.02 1068.24 1066.74 1052.38 1062.31 1064.28
CONFIG101   371.63  378.36  370.36  371.74  370.67  376.24  378.15  371.56
CONFIG110   1060.88 1072.13 1076.01 1069.52 1069.04 1068.72 1064.79 1066.66
CONFIG111   350.08  350.69  352.1   350.19  352.28  353.46  351.83  350.94

This code works for my application:

def ShowData(data, names):
    i = 0
    while i < data.shape[0]:
        print(names[i] + ": ")
        j = 0
        while j < data.shape[1]:
            print(data[i][j])
            j += 1
        print("")
        i += 1

def Main():
    print("The sample data is: ")
    fname = 'ANOVA.csv'
    csv = numpy.genfromtxt(fname, dtype=str, delimiter=",")
    num_rows = csv.shape[0]
    num_cols = csv.shape[1]
    names = csv[:,0]
    data = numpy.genfromtxt(fname, usecols = range(1,num_cols), delimiter=",")
    print(names)
    print(str(num_rows) + "x" + str(num_cols))
    print(data)
    ShowData(data, names)

Python-2 output:

The sample data is:
['CONFIG000' 'CONFIG001' 'CONFIG010' 'CONFIG011' 'CONFIG100' 'CONFIG101'
 'CONFIG110' 'CONFIG111']
8x9
[[ 1080.65  1080.87  1068.76  1083.52  1084.96  1080.31  1081.75  1079.98]
 [  414.6    421.76   418.93   415.53   415.23   416.12   420.54   415.42]
 [ 1091.43  1079.2   1086.61  1086.58  1091.14  1080.58  1076.64  1083.67]
 [  391.31   392.96   391.24   392.21   391.94   392.18   391.96   391.66]
 [ 1067.08  1062.1   1061.02  1068.24  1066.74  1052.38  1062.31  1064.28]
 [  371.63   378.36   370.36   371.74   370.67   376.24   378.15   371.56]
 [ 1060.88  1072.13  1076.01  1069.52  1069.04  1068.72  1064.79  1066.66]
 [  350.08   350.69   352.1    350.19   352.28   353.46   351.83   350.94]]
CONFIG000:
1080.65
1080.87
1068.76
1083.52
1084.96
1080.31
1081.75
1079.98

CONFIG001:
414.6
421.76
418.93
415.53
415.23
416.12
420.54
415.42

CONFIG010:
1091.43
1079.2
1086.61
1086.58
1091.14
1080.58
1076.64
1083.67

CONFIG011:
391.31
392.96
391.24
392.21
391.94
392.18
391.96
391.66

CONFIG100:
1067.08
1062.1
1061.02
1068.24
1066.74
1052.38
1062.31
1064.28

CONFIG101:
371.63
378.36
370.36
371.74
370.67
376.24
378.15
371.56

CONFIG110:
1060.88
1072.13
1076.01
1069.52
1069.04
1068.72
1064.79
1066.66

CONFIG111:
350.08
350.69
352.1
350.19
352.28
353.46
351.83
350.94

What is the difference between Left, Right, Outer and Inner Joins?

There are three basic types of join:

  • INNER join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.
  • CROSS join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.
  • OUTER join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
    • LEFT means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match.
    • RIGHT means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match.
    • FULL means keep all records from both tables, and insert a NULL value in either table if there is no match.

Often you see will the OUTER keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.

Here is an example of when you might want to use each type:

  • INNER: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.
  • OUTER: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.
  • CROSS: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.

What is the inclusive range of float and double in Java?

From Primitives Data Types:

  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.

UTF-8 all the way through

Data Storage:

  • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).

  • In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

Data Access:

  • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

    • If you're using the PDO abstraction layer with PHP = 5.3.6, you can specify charset in the DSN:

       $dbh = new PDO('mysql:charset=utf8mb4');
      
    • If you're using mysqli, you can call set_charset():

        $mysqli->set_charset('utf8mb4');       // object oriented style
        mysqli_set_charset($link, 'utf8mb4');  // procedural style
      
    • If you're stuck with plain mysql but happen to be running PHP = 5.2.3, you can call mysql_set_charset.

  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

  • The same consideration regarding utf8mb4/utf8 applies as above.

Output:

  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).

  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.

  • When encoding the output using json_encode(), add JSON_UNESCAPED_UNICODE as a second parameter.

Input:

  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding() does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.

  • From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:

    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.

Other Code Considerations:

  • Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.

  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring extension.

  • PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.

  • To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

How does Spring autowire by name when more than one matching bean is found?

One more solution with resolving by name:

@Resource(name="country")

It uses javax.annotation package, so it's not Spring specific, but Spring supports it.

How do I add options to a DropDownList using jQuery?

Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

Maybe your model not linked when migration process is ongoing. Try to import it in file urls.py from models import your_file

Converting a year from 4 digit to 2 digit and back again in C#

This is an old post, but I thought I'd give an example using an ExtensionMethod (since C# 3.0), since this will hide the implementation and allow for use everywhere in the project instead or recreating the code over and over or needing to be aware of some utility class.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

public static class DateTimeExtensions
    {
        public static int ToYearLastTwoDigit(this DateTime date)
        {
            var temp = date.ToString("yy");
            return int.Parse(temp);
        }
    }

You can then call this method anywhere you use a DateTime object, for example...

var dateTime = new DateTime(2015, 06, 19);
var year = cob.ToYearLastTwoDigit();

What's in an Eclipse .classpath/.project file?

.project

When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.

.classpath

Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.

Import error No module named skimage

As per the official installation page of skimage (skimage Installation) : python-skimage package depends on matplotlib, scipy, pil, numpy and six.

So install them first using

sudo apt-get install python-matplotlib python-numpy python-pil python-scipy

Apparently skimage is a part of Cython which in turn is a superset of python and hence you need to install Cython to be able to use skimage.

sudo apt-get install build-essential cython

Now install skimage package using

sudo apt-get install python-skimage

This solved the Import error for me.

Don't change link color when a link is clicked

you are looking for this:

a:visited{
  color:blue;
}

Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)

Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)

a:link{
  color:blue;
}
a:visited{
  color:purple;
}
a:hover{
  color:orange;
}
a:focus{
  color:green;
}
a:active{
  color:red;
}

If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)

If you have different types of links that you want to all have the same color when clicked, add a class to the links.

a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
  color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
  color:orange;
}

It should be noted that not all browsers respect each of these options ;-)

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

What does 'URI has an authority component' mean?

The solution was simply that the URI was malformed (because the location of my project was over a "\\" UNC path). This issue was fixed when I used a local workspace.

What are carriage return, linefeed, and form feed?

Carriage return and line feed are also references to typewriters, in that the with a small push on the handle on the left side of the carriage (the place where the paper goes), the paper would rotate a small amount around the cylinder, advancing the document one line. If you had finished typing one line, and wanted to continue on to the next, you pushed harder, both advancing a line and sliding the carriage all the way to the right, then resuming typing left to right again as the carriage traveled with each keystroke. Needless to say, word-wrap was the default setting for all word processing of the era. P:D

How to change background Opacity when bootstrap modal is open

use this code

_x000D_
_x000D_
$("#your_modal_id").on("shown.bs.modal", function(){_x000D_
      $('.modal-backdrop.in').css('opacity', '0.9');_x000D_
});
_x000D_
_x000D_
_x000D_

How to insert an object in an ArrayList at a specific position

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.

Python's most efficient way to choose longest string in list?

len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

I wrote a C++ class using timeb.

#include <sys/timeb.h>
class msTimer 
{
public:
    msTimer();
    void restart();
    float elapsedMs();
private:
    timeb t_start;
};

Member functions:

msTimer::msTimer() 
{ 
    restart(); 
}

void msTimer::restart() 
{ 
    ftime(&t_start); 
}

float msTimer::elapsedMs() 
{
    timeb t_now;
    ftime(&t_now);
    return (float)(t_now.time - t_start.time) * 1000.0f +
           (float)(t_now.millitm - t_start.millitm);
}

Example of use:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char** argv) 
{
    msTimer t;
    for (int i = 0; i < 5000000; i++)
        ;
    std::cout << t.elapsedMs() << endl;
    return 0;
}

Output on my computer is '19'. Accuracy of the msTimer class is of the order of milliseconds. In the usage example above, the total time of execution taken up by the for-loop is tracked. This time included the operating system switching in and out the execution context of main() due to multitasking.

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Convert string to binary then back again using PHP

i was looking for some string bits conversion and got here, If the next case is for you take //it so... if you want to use the bits from a string into different bits maybe this example would help

$string="1001"; //this would be 2^0*1+....0...+2^3*1=1+8=9
$bit4=$string[0];//1
$bit3=$string[1];
$bit2=$string[2];
$bit1=$string[3];//1

C++ STL Vectors: Get iterator from index?

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

EDIT
differences in usage:

std::vector<>::iterator it = ( v.begin() + index );

or

std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

How to save a new sheet in an existing excel file, using Pandas?

Can do it without using ExcelWriter, using tools in openpyxl This can make adding fonts to the new sheet much easier using openpyxl.styles

import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

#Location of original excel sheet
fileLocation =r'C:\workspace\data.xlsx'

#Location of new file which can be the same as original file
writeLocation=r'C:\workspace\dataNew.xlsx'

data = {'Name':['Tom','Paul','Jeremy'],'Age':[32,43,34],'Salary':[20000,34000,32000]}

#The dataframe you want to add
df = pd.DataFrame(data)

#Load existing sheet as it is
book = load_workbook(fileLocation)
#create a new sheet
sheet = book.create_sheet("Sheet Name")

#Load dataframe into new sheet
for row in dataframe_to_rows(df, index=False, header=True):
    sheet.append(row)

#Save the modified excel at desired location    
book.save(writeLocation)

Accessing dict keys like an attribute?

Solution is:

DICT_RESERVED_KEYS = vars(dict).keys()


class SmartDict(dict):
    """
    A Dict which is accessible via attribute dot notation
    """
    def __init__(self, *args, **kwargs):
        """
        :param args: multiple dicts ({}, {}, ..)
        :param kwargs: arbitrary keys='value'

        If ``keyerror=False`` is passed then not found attributes will
        always return None.
        """
        super(SmartDict, self).__init__()
        self['__keyerror'] = kwargs.pop('keyerror', True)
        [self.update(arg) for arg in args if isinstance(arg, dict)]
        self.update(kwargs)

    def __getattr__(self, attr):
        if attr not in DICT_RESERVED_KEYS:
            if self['__keyerror']:
                return self[attr]
            else:
                return self.get(attr)
        return getattr(self, attr)

    def __setattr__(self, key, value):
        if key in DICT_RESERVED_KEYS:
            raise AttributeError("You cannot set a reserved name as attribute")
        self.__setitem__(key, value)

    def __copy__(self):
        return self.__class__(self)

    def copy(self):
        return self.__copy__()

how to replace an entire column on Pandas.DataFrame

For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.

Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4

columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...

original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite

original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

How do I compile C++ with Clang?

Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:

To compile multiple C++ files using clang++:

$ clang++ *.cpp 
$ ./a.out 

To compile multiple C++ files using g++:

$ g++ -c *.cpp 
$ g++ -o temp.exe *.o
$ ./temp.exe

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

How should I pass multiple parameters to an ASP.Net Web API GET?

What does this record marking mean? If this is used only for logging purposes, I would use GET and disable all caching, since you want to log every query for this resources. If record marking has another purpose, POST is the way to go. User should know, that his actions effect the system and POST method is a warning.

Simple JavaScript Checkbox Validation

For now no jquery or php needed. Use just "required" HTML5 input attrbute like here

 <form>
        <p>
            <input class="form-control" type="text" name="email" />
            <input type="submit" value="ok" class="btn btn-success" name="submit" />
            <input type="hidden" name="action" value="0" />
        </p>
        <p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
 </form>

This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.

Which loop is faster, while or for?

In C#, the For loop is slightly faster.

For loop average about 2.95 to 3.02 ms.

The While loop averaged about 3.05 to 3.37 ms.

Quick little console app to prove:

 class Program
    {
        static void Main(string[] args)
        {
            int max = 1000000000;
            Stopwatch stopWatch = new Stopwatch();

            if (args.Length == 1 && args[0].ToString() == "While")
            {
                Console.WriteLine("While Loop: ");
                stopWatch.Start();
                WhileLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
            else
            {
                Console.WriteLine("For Loop: ");
                stopWatch.Start();
                ForLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
        }

        private static void WhileLoop(int max)
        {
            int i = 0;
            while (i <= max)
            {
                //Console.WriteLine(i);
                i++;
            };
        }

        private static void ForLoop(int max)
        {
            for (int i = 0; i <= max; i++)
            {
                //Console.WriteLine(i);
            }
        }

        private static void DisplayElapsedTime(TimeSpan ts)
        {
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }
    }

ExecJS and could not find a JavaScript runtime

FYI, this fixed the problem for me... it's a pathing problem: http://forums.freebsd.org/showthread.php?t=35539

JavaScript editor within Eclipse

Eclipse HTML Editor Plugin

I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days.

I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane.

However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for.

How to send a "multipart/form-data" with requests in python?

Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.

In short, the files parameter takes a dict with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

In the above, the tuple is composed as follows:

(filename, data, content_type, headers)

If the value is just a string, the filename will be the same as the key, as in the following:

>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}

Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

If the value is a tuple and the first entry is None the filename property will not be included:

>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}

Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I have used MySQL DB for Hive MetaStore. Please follow the below steps:

  • in hive-site.xml the metastore should be proper
<property>
 <name>javax.jdo.option.ConnectionURL</name> 
 <value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&amp;useSSL=false</value>
</property>
  • go to the mysql: mysql -u hduser -p
  • then run drop database metastore
  • then come out from MySQL and execute schematool -initSchema dbType mysql

Now error will go.

Finding the max/min value in an array of primitives using Java

Here's a utility class providing min/max methods for primitive types: Primitives.java

int [] numbers= {10,1,8,7,6,5,2};
    int a=Integer.MAX_VALUE;
    for(int c:numbers) {
        a=c<a?c:a;
        }
        
    System.out.println("Lowest value is"+a);

LIKE operator in LINQ

   public static class StringEx
    {
        public static bool Contains(this String str, string[] Arr, StringComparison comp)
        {
            if (Arr != null)
            {
                foreach (string s in Arr)
                {
                    if (str.IndexOf(s, comp)>=0)
                    { return true; }
                }
            }

            return false;
        }

        public static bool Contains(this String str,string[] Arr)
        {
            if (Arr != null)
            {
                foreach (string s in Arr)
                {
                    if (str.Contains(s))
                    { return true; }
                }
            }

            return false;
        }
    }


var portCode = Database.DischargePorts
                   .Single(p => p.PortName.Contains( new string[] {"BALTIMORE"},  StringComparison.CurrentCultureIgnoreCase) ))
                   .PortCode;

Dynamically update values of a chartjs chart

You just need to change the chartObject.data.datasets value and call update() like this:

chartObject.data.datasets = newData.datasets;
chartObject.data.labels = newData.labels;
chartObject.update();

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Try using the QueryDefs. Create the query with parameters. Then use something like this:

Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef

Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")

qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close

Set qdf = Nothing
Set dbs = Nothing

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Just do this

<button OnClick=" location.href='link.html' ">Visit Page Now</button>

Although, it's been a while since I've touched JavaScript - maybe location.href is outdated? Anyways, that's how I would do it.

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

Concatenate String in String Objective-c

Just do

NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"];

This gives you

@"first part of string (foo) third part of string"

Passing parameters to a JDBC PreparedStatement

Do something like this, which also prevents SQL injection attacks

statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();

Insert a row to pandas dataframe

concat() seems to be a bit faster than last row insertion and reindexing. In case someone would wonder about the speed of two top approaches:

In [x]: %%timeit
     ...: df = pd.DataFrame(columns=['a','b'])
     ...: for i in range(10000):
     ...:     df.loc[-1] = [1,2]
     ...:     df.index = df.index + 1
     ...:     df = df.sort_index()

17.1 s ± 705 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [y]: %%timeit
     ...: df = pd.DataFrame(columns=['a', 'b'])
     ...: for i in range(10000):
     ...:     df = pd.concat([pd.DataFrame([[1,2]], columns=df.columns), df])

6.53 s ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Get request URL in JSP which is forwarded by Servlet

None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.

http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).

Calculate the execution time of a method

Following this Microsoft Doc:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Output: RunTime 00:00:09.94

How to use vagrant in a proxy environment?

In PowerShell, you could set the http_proxy and https_proxy environment variables like so:

$env:http_proxy="http://proxy:3128"
$env:https_proxy="http://proxy:3128"

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Just disable scroll not hide it?

If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set

body { position: fixed; overflow-y:scroll }

you should still see the right scrollbar but the content is not scrollable. When you close the overlay just revert these properties with

body { position: static; overflow-y:auto }

I just proposed this way only because you wouldn't need to change any scroll event

Update

You could also do a slight improvement: if you get the document.documentElement.scrollTop property via javascript just before the layer opening, you could dynamically assign that value as top property of the body element: with this approach the page will stand in its place, no matter if you're on top or if you have already scrolled.

Css

.noscroll { position: fixed; overflow-y:scroll }

JS

$('body').css('top', -(document.documentElement.scrollTop) + 'px')
         .addClass('noscroll');

Set date input field's max date to today

You will need Javascript to do this:

HTML

<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>

JS

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
 if(dd<10){
        dd='0'+dd
    } 
    if(mm<10){
        mm='0'+mm
    } 

today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);

JSFiddle demo

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

In my case, I forgot to add MatDialogModule to imports in a child module.

How do I use disk caching in Picasso?

I had the same problem and used Glide library instead. Cache is out of the box there. https://github.com/bumptech/glide

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

Adding [AllowHtml] on the specific property is the recommended solution as there are plenty of blogs and comments suggesting to decrease the security level, which should be unacceptable.

By adding that, the MVC framework will allow the Controller to be hit and the code in that controller to be executed.

However, it depends on your code, filters, etc. how the response is generated and whether there is any further validation that might trigger another similar error.

In any case, adding [AllowHtml] attribute is the right answer, as it allows html to be deserialized in the controller. Example in your viewmodel:

[AllowHtml]
public string MessageWithHtml {get; set;}

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

How to find the operating system version using JavaScript?

platform.js seems like a good one file library to do this.

Usage example:

// on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition
platform.name; // 'IE'
platform.version; // '10.0'
platform.layout; // 'Trident'
platform.os; // 'Windows Server 2008 R2 / 7 x64'
platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64'

// or on an iPad
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
platform.os; // 'iOS 5.0'
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'

// or parsing a given UA string
var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52');
info.name; // 'Opera'
info.version; // '11.52'
info.layout; // 'Presto'
info.os; // 'Mac OS X 10.7.2'
info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2'

Check if value exists in Postgres array

When looking for the existence of a element in an array, proper casting is required to pass the SQL parser of postgres. Here is one example query using array contains operator in the join clause:

For simplicity I only list the relevant part:

table1 other_name text[]; -- is an array of text

The join part of SQL shown

from table1 t1 join table2 t2 on t1.other_name::text[] @> ARRAY[t2.panel::text]

The following also works

on t2.panel = ANY(t1.other_name)

I am just guessing that the extra casting is required because the parse does not have to fetch the table definition to figure the exact type of the column. Others please comment on this.

How do I best silence a warning about unused variables?

C++17 now provides the [[maybe_unused]] attribute.

http://en.cppreference.com/w/cpp/language/attributes

Quite nice and standard.

How to configure socket connect timeout

Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.

The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:

I created another method wich actually connected the socket ... had the main thread sleep for 2 seconds and then check on the connecting method (wich is run in a separate thread) if the socket was connected good otherwise throw an exception "Timed out " and that;s all. Thanks again for the repleies.

What are you trying to do, and why can't it wait for 15-30 seconds before timing out?

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

In my case everything said above was OK, but I still have been receiving ORA-12545: Network Transport: Unable to resolve connect hostname

I tried to ping the Oracle machine and found out I cannot see it and added it to the hosts file. Then I received another error message ORA-12541: TNS:no listener. After investigation I realized that pinging the same hostname from different machines getting different IP addresses(I don't know why) and I changed the IP address in my host file, which resolved the problem on 100%.

I'm bothering to write my experience as it seems obvious, but although I was sure the problem is in the above settings I totally forgot to check if I really can see the remote DB machine out there. Keep it in mind when you are out of ideas what is going on.....

These links helped me a lot:

http://www.moreajays.com/2013/03/ora-12545-connect-failed-because-target.html http://www.orafaq.com/wiki/ORA-12541

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

How to change the output color of echo in Linux

I've written swag to achieve just that.

You can just do

pip install swag

Now you can install all the escape commands as txt files to a given destination via:

swag install -d <colorsdir>

Or even easier via:

swag install

Which will install the colors to ~/.colors.

Either you use them like this:

echo $(cat ~/.colors/blue.txt) This will be blue

Or this way, which I find actually more interesting:

swag print -c red -t underline "I will turn red and be underlined"

Check it out on asciinema!

How to vertically align text in input type="text"?

I found this question while looking for a solution to my own problem. The previous answers rely on padding to make the text appear at the top or bottom of the input or use a combination of height and line-height to align the text to the vertical middle.

Here is an alternative solution to making the text appear in the middle using a div and positioning. Check out the jsfiddle.

<style type="text/css">
    div {
        display: inline-block;
        height: 300px;
        position: relative;
        width: 500px;
    }

    input {
        height: 100%;
        position: absolute;
        text-align: center; /* Optional */
        width: 100%;
    }
</style>

<div>
    <input type="text" value="Hello world!" />
</div>

Using R to list all files with a specified extension

Gives you the list of files with full path:

  Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory

Getting full JS autocompletion under Sublime Text

As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How to get div height to auto-adjust to background size?

You can do something like that

<div style="background-image: url(http://your-image.jpg); position:relative;">
 <img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>

Where am I? - Get country

Use this link http://ip-api.com/json ,this will provide all the information as json. From this json you can get the country easily. This site works using your current IP,it automatically detects the IP and sendback details.

Docs http://ip-api.com/docs/api:json Hope it helps.

Example json

{
  "status": "success",
  "country": "United States",
  "countryCode": "US",
  "region": "CA",
  "regionName": "California",
  "city": "San Francisco",
  "zip": "94105",
  "lat": "37.7898",
  "lon": "-122.3942",
  "timezone": "America/Los_Angeles",
  "isp": "Wikimedia Foundation",
  "org": "Wikimedia Foundation",
  "as": "AS14907 Wikimedia US network",
  "query": "208.80.152.201"
}

note : As this is a 3rd party solution, only use if others didn't work.

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Regular cast vs. static_cast vs. dynamic_cast

FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.

Barne Stroustrup's C++ style FAQ

Take that advice for what you will. I'm far from being a C++ guru.

How can I check file size in Python?

Using pathlib (added in Python 3.4 or a backport available on PyPI):

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

This is really only an interface around os.stat, but using pathlib provides an easy way to access other file related operations.

Regular Expression Validation For Indian Phone Number and Mobile number

Use the following regex

^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$

This will support the following formats:

  1. 8880344456
  2. +918880344456
  3. +91 8880344456
  4. +91-8880344456
  5. 08880344456
  6. 918880344456

Getting attributes of a class

Try the inspect module. getmembers and the various tests should be helpful.

EDIT:

For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

Is there a Social Security Number reserved for testing/examples?

Please look at this document

http://www.socialsecurity.gov/employer/randomization.html

The SSA is instituting a new policy the where all previously unused sequences are will be available for use.

Goes into affect June 25, 2011.

Taken from the new FAQ:

What changes will result from randomization?

The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top

Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?

SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.

Can one class extend two classes?

No you cannot make a class extend to two classes.

A possible solution is to make it extend from another class, and make that class extend from another again.

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

SQL Developer is returning only the date, not the time. How do I fix this?

Date format can also be set by using below query :-

alter SESSION set NLS_DATE_FORMAT = 'date_format'

e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

Command line to remove an environment variable from the OS level configuration

The command in DougWare's answer did not work, but this did:

reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v FOOBAR /f

The shortcut HKLM can be used for HKEY_LOCAL_MACHINE.

Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
    dictionary.setdefault(realName, {})[falseName] = position

dictionary now equals:

{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

How to save a list as numpy array in python?

import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

Converting PKCS#12 certificate into PEM using OpenSSL

There is a free and open-source GUI tool KeyStore Explorer to work with crypto key containers. Using it you can export a certificate or private key into separate files or convert the container into another format (jks, pem, p12, pkcs12, etc)

enter image description here

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

Pass command parameter to method in ViewModel in WPF?

Try this:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }

            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }

            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}

  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

And in xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>

Generics/templates in python?

Since python is dynamically typed, this is super easy. In fact, you'd have to do extra work for your BinaryTree class not to work with any data type.

For example, if you want the key values which are used to place the object in the tree available within the object from a method like key() you just call key() on the objects. For example:

class BinaryTree(object):

    def insert(self, object_to_insert):
        key = object_to_insert.key()

Note that you never need to define what kind of class object_to_insert is. So long as it has a key() method, it will work.

The exception is if you want it to work with basic data types like strings or integers. You'll have to wrap them in a class to get them to work with your generic BinaryTree. If that sounds too heavy weight and you want the extra efficiency of actually just storing strings, sorry, that's not what Python is good at.

What does '&' do in a C++ declaration?

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

This is invalid code on several counts. Running it through g++ gives:

crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’

A valid version of the code reads:

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            p=p+100;
            return p;
}

What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:

int add(int *p)
{
      *p=*p+100;
      return *p;
}

However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:

int add(int &p)
{
            *p=*p+100;
            return p;
}

is invalid.

If you must use a pointer to a reference, that has to be done explicitly:

int add(int &p)
{
                    int* i = &p;
            i=i+100L;
            return *i;
}

Which on a test run gives (as expected) junk output:

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792

Downloading an entire S3 bucket?

The answer by @Layke is good, but if you have a ton of data and don't want to wait forever, you should read "AWS CLI S3 Configuration".

The following commands will tell the AWS CLI to use 1,000 threads to execute jobs (each a small file or one part of a multipart copy) and look ahead 100,000 jobs:

aws configure set default.s3.max_concurrent_requests 1000
aws configure set default.s3.max_queue_size 100000

After running these, you can use the simple sync command:

aws s3 sync s3://source-bucket/source-path s3://destination-bucket/destination-path

or

aws s3 sync s3://source-bucket/source-path c:\my\local\data\path

On a system with CPU 4 cores and 16GB RAM, for cases like mine (3-50GB files) the sync/copy speed went from about 9.5MiB/s to 700+MiB/s, a speed increase of 70x over the default configuration.

How to get the selected radio button value using js

Use the element.checked property.

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

Global environment variables in a shell script

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

How to draw text using only OpenGL methods?

Theory

Why it is hard

Popular font formats like TrueType and OpenType are vector outline formats: they use Bezier curves to define the boundary of the letter.

Image source.

Transforming those formats into arrays of pixels (rasterization) is too specific and out of OpenGL's scope, specially because OpenGl does not have non-straight primitives (e.g. see Why is there no circle or ellipse primitive in OpenGL?)

The easiest approach is to first raster fonts ourselves on the CPU, and then give the array of pixels to OpenGL as a texture.

OpenGL then knows how to deal with arrays of pixels through textures very well.

Texture atlas

We could raster characters for every frame and re-create the textures, but that is not very efficient, specially if characters have a fixed size.

The more efficient approach is to raster all characters you plan on using and cram them on a single texture.

And then transfer that to the GPU once, and use it texture with custom uv coordinates to choose the right character.

This approach is called a texture atlas and it can be used not only for textures but also other repeatedly used textures, like tiles in a 2D game or web UI icons.

The Wikipedia picture of the full texture, which is itself taken from freetype-gl, illustrates this well:

I suspect that optimizing character placement to the smallest texture problem is an NP-hard problem, see: What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?

The same technique is used in web development to transmit several small images (like icons) at once, but there it is called "CSS Sprites": https://css-tricks.com/css-sprites/ and are used to hide the latency of the network instead of that of the CPU / GPU communication.

Non-CPU raster methods

There also exist methods which don't use the CPU raster to textures.

CPU rastering is simple because it uses the GPU as little as possible, but we also start thinking if it would be possible to use the GPU efficiency further.

This FOSDEM 2014 video explains other existing techniques:

Fonts inside of the 3D geometry with perspective

Rendering fonts inside of the 3D geometry with perspective (compared to an orthogonal HUD) is much more complicated, because perspective could make one part of the character much closer to the screen and larger than the other, making an uniform CPU discretization (e.g. raster, tesselation) look bad on the close part. This is actually an active research topic:

enter image description here

Distance fields are one of the popular techniques now.

Implementations

The examples that follow were all tested on Ubuntu 15.10.

Because this is a complex problem as discussed previously, most examples are large, and would blow up the 30k char limit of this answer, so just clone the respective Git repositories to compile.

They are all fully open source however, so you can just RTFS.

FreeType solutions

FreeType looks like the dominant open source font rasterization library, so it would allow us to use TrueType and OpenType fonts, making it the most elegant solution.

Examples / tutorials:

Other font rasterizers

Those seem less good than FreeType, but may be more lightweight:

Anton's OpenGL 4 Tutorials example 26 "Bitmap fonts"

The font was created by the author manually and stored in a single .png file. Letters are stored in an array form inside the image.

This method is of course not very general, and you would have difficulties with internationalization.

Build with:

make -f Makefile.linux64

Output preview:

enter image description here

opengl-tutorial chapter 11 "2D fonts"

Textures are generated from DDS files.

The tutorial explains how the DDS files were created, using CBFG and Paint.Net.

Output preview:

enter image description here

For some reason Suzanne is missing for me, but the time counter works fine: https://github.com/opengl-tutorials/ogl/issues/15

FreeGLUT

GLUT has glutStrokeCharacter and FreeGLUT is open source... https://github.com/dcnieho/FreeGLUT/blob/FG_3_0_0/src/fg_font.c#L255

OpenGLText

https://github.com/tlorach/OpenGLText

TrueType raster. By NVIDIA employee. Aims for reusability. Haven't tried it yet.

ARM Mali GLES SDK Sample

http://malideveloper.arm.com/resources/sample-code/simple-text-rendering/ seems to encode all characters on a PNG, and cut them from there.

SDL_ttf

enter image description here

Source: https://github.com/cirosantilli/cpp-cheat/blob/d36527fe4977bb9ef4b885b1ec92bd0cd3444a98/sdl/ttf.c

Lives in a separate tree to SDL, and integrates easily.

Does not provide a texture atlas implementation however, so performance will be limited: How to render fonts and text with SDL2 efficiently?

Related threads

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

Get GMT Time in Java

I wonder why no one does this:

Calendar time = Calendar.getInstance();
time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));
Date date = time.getTime();

Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity

Clear image on picturebox

I used this method to clear the image from picturebox. It may help some one

private void btnClear1_Click(object sender, EventArgs e)
        {

            img1.ImageLocation = null;
        }

The project type is not supported by this installation

You could also try to run the following command:

devenv /ResetSkipPkgs

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.