Programs & Examples On #Data transfer

Data transmission, digital transmission, or digital communications is the physical transfer of data (a digital bit stream) over a point-to-point or point-to-multipoint communication channel.

What is a Data Transfer Object (DTO)?

A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.

DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern.

Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than 4 or 5 parameters.

When using the DTO pattern, you would also make use of DTO assemblers. The assemblers are used to create DTOs from Domain Objects, and vice versa.

The conversion from Domain Object to DTO and back again can be a costly process. If you're not creating a distributed application, you probably won't see any great benefits from the pattern, as Martin Fowler explains here

Remote Linux server to remote linux server dir copy. How?

scp will do the job, but there is one wrinkle: the connection to the second remote destination will use the configuration on the first remote destination, so if you use .ssh/config on the local environment, and you expect rsa and dsa keys to work, you have to forward your agent to the first remote host.

Sending POST data without form

You could use AJAX to send a POST request if you don't want forms.

Using jquery $.post method it is pretty simple:

$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
    alert('successfully posted key1=value1&key2=value2 to foo.php');
});

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

A solution that accept exceptions(passed by parameters):

Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);

(function($) {
    $.fn.maskOwnName = function(not_capitalize) {
            not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;

        $(this).keypress(function(e){
            if(e.altKey || e.ctrlKey)
                return;

            var new_char = String.fromCharCode(e.which).toLowerCase();

            if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
                var start = this.selectionStart,
                    end = this.selectionEnd;

                if(e.keyCode == 8){
                    if(start == end)
                        start--;

                    new_char = '';
                }

                var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
                var maxlength = this.getAttribute('maxlength');
                var words = new_value.split(' ');
                start += new_char.length;
                end = start;

                if(maxlength === null || new_value.length <= maxlength)
                    e.preventDefault();
                else
                    return;

                for (var i = 0; i < words.length; i++){
                    words[i] = words[i].toLowerCase();

                    if(not_capitalize.indexOf(words[i]) == -1)
                        words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
                }

                this.value = words.join(' ');
                this.setSelectionRange(start, end);
            }
        });
    }

    $.fn.maskLowerName = function(pos) {
        $(this).css('text-transform', 'lowercase').bind('blur change', function(){
            this.value = this.value.toLowerCase();
        });
    }

    $.fn.maskUpperName = function(pos) {
        $(this).css('text-transform', 'uppercase').bind('blur change', function(){
            this.value = this.value.toUpperCase();
        });
    }
})(jQuery);

Getting Hour and Minute in PHP

print date('H:i');
$var = date('H:i');

Should do it, for the current time. Use a lower case h for 12 hour clock instead of 24 hour.

More date time formats listed here.

A project with an Output Type of Class Library cannot be started directly

The project type set as the Start-up project in that solution is of type ClassLibrary. DUe to that, the output is a dll not an executable and so, you cannot start it.

If this is an error then you can do this:

A quick and dirty fix for this, if that is the only csproj in the solution is to open the .csproj file in a text editor and change the value of the node <ProjectGuid> to the Guid corresponding to a WinForms C# project. (That you may obtain from a google search or by creating a new project and opening the .csproj file generated by Visual Studio to find out what the GUID for that type is). (Enjoy - not many people know about this sneaky trick)

BUT: the project might be a class library rightfully and then you should reference it in another project and use it that way.

Push Notifications in Android Platform

I dont know if this is still useful. I achieved something like this with a java library at http://www.pushlets.com/

Althoug doing it in a service won't prevent android from shutting it down an killing the listener thread.

How to set a variable to be "Today's" date in Python/Pandas

You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime

>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')

This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.

Replacing today with now would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.

In pandas versions prior to 0.23.x, normalize may not have been necessary to remove the non-midnight timestamp.

Best practices for Storyboard login screen, handling clearing of data upon logout

I didn't like bhavya's answer because of using AppDelegate inside View Controllers and setting rootViewController has no animation. And Trevor's answer has issue with flashing view controller on iOS8.

UPD 07/18/2015

AppDelegate inside View Controllers:

Changing AppDelegate state (properties) inside view controller breaks encapsulation.

Very simple hierarchy of objects in every iOS project:

AppDelegate (owns window and rootViewController)

ViewController (owns view)

It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).

If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]

UPD 07/18/2015

I replicate modal controller animations using UINavigationController (tl;dr: check the project).

I'm using UINavigationController to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.

How it works:

  1. Initial view controller (or self.window.rootViewController) is UINavigationController with ProgressViewController as a rootViewController. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).

  2. AppDelegate is responsible for getting login status updates.

  3. DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).

  4. ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.

How animators logic works:

  1. AppDelegate sets itself as a delegate of self.window.rootViewController (which is UINavigationController).

  2. AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:] if necessary.

  3. Animators implement -transitionDuration: and -animateTransition: methods. -[ModalPresentAnimator animateTransition:]:

    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        [[transitionContext containerView] addSubview:toViewController.view];
        CGRect frame = toViewController.view.frame;
        CGRect toFrame = frame;
        frame.origin.y = CGRectGetHeight(frame);
        toViewController.view.frame = frame;
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                         animations:^
         {
             toViewController.view.frame = toFrame;
         } completion:^(BOOL finished)
         {
             [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
         }];
    }
    

Test project is here.

Difference between the Apache HTTP Server and Apache Tomcat?

an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.

Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].

Also you can check this link for more clarification:-

https://sites.google.com/site/sureshdevang/servlet-architecture

Also check this answer for further researching :-

https://softwareengineering.stackexchange.com/a/221092

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

How do I convert a Swift Array to a String?

If the array contains strings, you can use the String's join method:

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

In Swift 2:

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

This can be useful if you want to use a specific separator (hypen, blank, comma, etc).

Otherwise you can simply use the description property, which returns a string representation of the array:

let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"

Hint: any object implementing the Printable protocol has a description property. If you adopt that protocol in your own classes/structs, you make them print friendly as well

In Swift 3

  • join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

var array = ["1", "2", "3"]
array.joined(separator:"-")

Remove ALL white spaces from text

.replace(/\s+/, "") 

Will replace the first whitespace only, this includes spaces, tabs and new lines.

To replace all whitespace in the string you need to use global mode

.replace(/\s/g, "")

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

A colleague of mine recommended Internet Explorer Collection. It appears to work without issues, but I'm far from a power user. It also supports installing IE 1 (!!) through 8.

wp-admin shows blank page, how to fix it?

I was also facing same problem but i renamed contact-form-7 plugin from /wp-content/plugins directory to contact-form-7-rename and problem solved.

So this is due to unsupportable plugins or theme.

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

Python - Check If Word Is In A String

if 'seek' in 'those who seek shall find':
    print('Success!')

but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

Check that the application on the test device and Google Play developer console really match.

I might have a bit of a special case but it might help someone: First, I had uploaded a package to Google Play that I had created with an ant build script. Second, on the test device, I debugged the same application (or so I thought). I got the "Error while retrieving information from server. [RPC:S-7:AEC-0]", and logcat displayed:

Class not found when unmarshalling: com.google.android.finsky.billing.lightpurchase.PurchaseParams, e: java.lang.ClassNotFoundException: com.google.android.finsky.billing.lightpurchase.PurchaseParams

The problem was that in the ant script, I have aapt command for modifying the package name. However, Eclipse does not run that command, so there was a package name mismatch between the applications in Google Play and the test device.

Get PostGIS version

As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:

postgres=# select PostGIS_full_version();
postgis_full_version                                                                  
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)

You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.

Getting file names without extensions

Just for the record:

DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
string fileNames = String.Join(", ", smFiles.Select<FileInfo, string>(fi => Path.GetFileNameWithoutExtension(fi.FullName)));

This way you don't use StringBuilder but String.Join(). Also please remark that Path.GetFileNameWithoutExtension() needs a full path (fi.FullName), not fi.Name as I saw in one of the other answers.

How to get span tag inside a div in jQuery and assign a text?

$("#message > span").text("your text");

or

$("#message").find("span").text("your text");

or

$("span","#message").text("your text");

or

$("#message > a.close-notify").siblings('span').text("your text");

Private class declaration

private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.

Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Suppose you have text field and submit button,

<input type="text" id="text-field" />
<input type="submit" class="btn" value="Submit"/>

Disabling:

To disable any button, for example, submit button you just need to add disabled attribute as,

$('input[type="submit"]').attr('disabled','disabled');

After executing above line, your submit button html tag would look like this:

<input type="submit" class="btn" value="Submit" disabled/>

Notice the 'disabled' attribute has added.

Enabling:

For enabling button, such as when you have some text in text field. You will need to remove the disable attribute to enable button as,

 if ($('#text-field').val() != '') {
     $('input[type="submit"]').removeAttr('disabled');
 }

Now the above code will remove the 'disabled' attribute.

Difference between checkout and export in SVN

if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

in Windows in the search option Go to administrative tools>component services>OracleServiceXE(start this service)

Guzzle 6: no more json() method for responses

Adding ->getContents() doesn't return jSON response, instead it returns as text.

You can simply use json_decode

Load CSV file with Spark

If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.

I am also new to Pyspark and trying to read CSV file. Following code worked for me:

In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data

1. Without mentioning the schema:

from pyspark.sql import SparkSession  
scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()

Now check the columns: sdfData.columns

Output will be:

['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']

Check the datatype for each column:

sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))

This will give the data frame with all the columns with datatype as StringType

2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)

from pyspark.sql import SparkSession  
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
    schema = StructType([\
        StructField("InvoiceNo", IntegerType()),\
        StructField("StockCode", StringType()), \
        StructField("Description", StringType()),\
        StructField("Quantity", IntegerType()),\
        StructField("InvoiceDate", StringType()),\
        StructField("CustomerID", DoubleType()),\
        StructField("Country", StringType())\
    ])

scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL example: Reading CSV file with schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)

Now check the schema for datatype of each column:

sdfData.schema

StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))

Edited: We can use the following line of code as well without mentioning schema explicitly:

sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema

The output is:

StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))

The output will look like this:

sdfData.show()

+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode|         Description|Quantity|   InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
|   536365|   85123A|WHITE HANGING HEA...|       6|12/1/2010 8:26|      2.55|  17850|
|   536365|    71053| WHITE METAL LANTERN|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84406B|CREAM CUPID HEART...|       8|12/1/2010 8:26|      2.75|  17850|
|   536365|   84029G|KNITTED UNION FLA...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84029E|RED WOOLLY HOTTIE...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|    22752|SET 7 BABUSHKA NE...|       2|12/1/2010 8:26|      7.65|  17850|
|   536365|    21730|GLASS STAR FROSTE...|       6|12/1/2010 8:26|      4.25|  17850|
|   536366|    22633|HAND WARMER UNION...|       6|12/1/2010 8:28|      1.85|  17850|
|   536366|    22632|HAND WARMER RED P...|       6|12/1/2010 8:28|      1.85|  17850|
|   536367|    84879|ASSORTED COLOUR B...|      32|12/1/2010 8:34|      1.69|  13047|
|   536367|    22745|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22748|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22749|FELTCRAFT PRINCES...|       8|12/1/2010 8:34|      3.75|  13047|
|   536367|    22310|IVORY KNITTED MUG...|       6|12/1/2010 8:34|      1.65|  13047|
|   536367|    84969|BOX OF 6 ASSORTED...|       6|12/1/2010 8:34|      4.25|  13047|
|   536367|    22623|BOX OF VINTAGE JI...|       3|12/1/2010 8:34|      4.95|  13047|
|   536367|    22622|BOX OF VINTAGE AL...|       2|12/1/2010 8:34|      9.95|  13047|
|   536367|    21754|HOME BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21755|LOVE BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21777|RECIPE BOX WITH M...|       4|12/1/2010 8:34|      7.95|  13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows

What is the difference between ndarray and array in numpy?

numpy.array is just a convenience function to create an ndarray; it is not a class itself.

You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray:

Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:

https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

Convert absolute path into relative path given a current directory using Bash

I needed something like this but which resolved symbolic links too. I discovered that pwd has a -P flag for that purpose. A fragment of my script is appended. It's within a function in a shell script, hence the $1 and $2. The result value, which is the relative path from START_ABS to END_ABS, is in the UPDIRS variable. The script cd's into each parameter directory in order to execute the pwd -P and this also means that relative path parameters are handled. Cheers, Jim

SAVE_DIR="$PWD"
cd "$1"
START_ABS=`pwd -P`
cd "$SAVE_DIR"
cd "$2"
END_ABS=`pwd -P`

START_WORK="$START_ABS"
UPDIRS=""

while test -n "${START_WORK}" -a "${END_ABS/#${START_WORK}}" '==' "$END_ABS";
do
    START_WORK=`dirname "$START_WORK"`"/"
    UPDIRS=${UPDIRS}"../"
done
UPDIRS="$UPDIRS${END_ABS/#${START_WORK}}"
cd "$SAVE_DIR"

Rename all files in directory from $filename_h to $filename_half?

Try rename command:

rename 's/_h.png/_half.png/' *.png

Update:

example usage:

create some content

$ mkdir /tmp/foo
$ cd /tmp/foo
$ touch one_h.png two_h.png three_h.png
$ ls 
one_h.png  three_h.png  two_h.png

test solution:

$ rename 's/_h.png/_half.png/' *.png
$ ls
one_half.png  three_half.png  two_half.png

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

Importing a Maven project into Eclipse from Git

I would perform a git clone via the command line (outside Eclipse) then use File -> Import... -> Existing Maven Projects.

Your projects will be understood as using Git and Maven. It's the fastest and most reliable way to import IMO.

How can I get terminal output in python?

The easiest way is to use the library commands

import commands
print commands.getstatusoutput('echo "test" | wc')

Javascript to check whether a checkbox is being checked or unchecked

Also make sure you test it both in firefox and IE. There are some nasty bugs with JS manipulated checkboxes.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Loop through an array in JavaScript

If you want to use jQuery, it has a nice example in its documentation:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
 });

Can I make a <button> not submit a form?

Yes, you can make a button not submit a form by adding an attribute of type of value button: <button type="button"><button>

Only using @JsonIgnore during serialization, but not deserialization

Another easy way to handle this is to use the argument allowSetters=truein the annotation. This will allow the password to be deserialized into your dto but it will not serialize it into a response body that uses contains object.

example:

@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
    String foo;
    String bar;
}

Both foo and bar are populated in the object, but only foo is written into a response body.

Removing App ID from Developer Connection

  • As of Apr 2013, it is possible to delete App IDs.
  • As of Sep 2013, it is impossible to delete App IDs again after the big outage. I hope Apple will put it back.
  • As of mid 2014, it is possible to delete App IDs again. However, you can't delete id of apps existing in the App Store.

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

Most useful NLog configurations

Apparently, you can now use NLog with Growl for Windows.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <extensions>
        <add assembly="NLog.Targets.GrowlNotify" />
    </extensions>

    <targets>
        <target name="growl" type="GrowlNotify" password="" host="" port="" />
    </targets>

    <rules>
        <logger name="*" minLevel="Trace" appendTo="growl"/>
    </rules>

</nlog>

NLog with Growl for Windows NLog trace message with Growl for Windows NLog debug message with Growl for Windows NLog info message with Growl for Windows NLog warn message with Growl for Windows NLog error message with Growl for Windows NLog fatal message with Growl for Windows

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

In fact the real solution for this issue is to use the jms-api-1.1-rev-1.jar artifact available on Maven Central : http://search.maven.org/#artifactdetails%7Cjavax.jms%7Cjms-api%7C1.1-rev-1%7Cjar

Understanding inplace=True

When trying to make changes to a Pandas dataframe using a function, we use 'inplace=True' if we want to commit the changes to the dataframe. Therefore, the first line in the following code changes the name of the first column in 'df' to 'Grades'. We need to call the database if we want to see the resulting database.

df.rename(columns={0: 'Grades'}, inplace=True)
df

We use 'inplace=False' (this is also the default value) when we don't want to commit the changes but just print the resulting database. So, in effect a copy of the original database with the committed changes is printed without altering the original database.

Just to be more clear, the following codes do the same thing:

#Code 1
df.rename(columns={0: 'Grades'}, inplace=True)
#Code 2
df=df.rename(columns={0: 'Grades'}, inplace=False}

Counter increment in Bash loop not working

There were two conditions that caused the expression ((var++)) to fail for me:

  1. If I set bash to strict mode (set -euo pipefail) and if I start my increment at zero (0).

  2. Starting at one (1) is fine but zero causes the increment to return "1" when evaluating "++" which is a non-zero return code failure in strict mode.

I can either use ((var+=1)) or var=$((var+1)) to escape this behavior

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

sql primary key and index

primary keys are automatically indexed

you can create additional indices using the pk depending on your usage

  • index zip_code, id may be helpful if you often select by zip_code and id

ORA-01882: timezone region not found

I had the same problem when trying to make a connection on OBIEE to Oracle db. I changed my Windows timezone from (GMT+01:00) West Central Africa to (GMT+01:00) Brussels, Copenhagen, Madrid, Paris. Then I rebooted my computer and it worked just fine. Seems like Oracle was not able to recognize the west central Africa timezone.

String concatenation in Ruby

The + operator is the normal concatenation choice, and is probably the fastest way to concatenate strings.

The difference between + and << is that << changes the object on its left hand side, and + doesn't.

irb(main):001:0> s = 'a'
=> "a"
irb(main):002:0> s + 'b'
=> "ab"
irb(main):003:0> s
=> "a"
irb(main):004:0> s << 'b'
=> "ab"
irb(main):005:0> s
=> "ab"

Set cursor position on contentEditable <div>

Update

I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.

Previous answer

You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.

I might put something together to do this, will post back here if and when I do.

EDIT:

I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.

http://www.timdown.co.uk/code/selections/

Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.

I will write this up fully at some point soon.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

How to redirect the output of the time command to a file in Linux?

If you are using GNU time instead of the bash built-in, try

time -o outfile command

(Note: GNU time formats a little differently than the bash built-in).

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Difference between onLoad and ng-init in angular

ng-init is a directive that can be placed inside div's, span's, whatever, whereas onload is an attribute specific to the ng-include directive that functions as an ng-init. To see what I mean try something like:

<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>

You'll see that only the second one shows up.

An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.

What is "String args[]"? parameter in main method Java

args contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:

$ java MyProg -f file.txt

Then args will be an array containing the strings "-f" and "file.txt".

Android - How to get application name? (Not package name)

If you know Package name then Use following snippet

ApplicationInfo ai;
try {
    ai = pm.getApplicationInfo(packageName, 0);
} catch (final NameNotFoundException e) {
    ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");

Is there a no-duplicate List implementation out there?

I just made my own UniqueList in my own little library like this:

package com.bprog.collections;//my own little set of useful utilities and classes

import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Jonathan
*/
public class UniqueList {

private HashSet masterSet = new HashSet();
private ArrayList growableUniques;
private Object[] returnable;

public UniqueList() {
    growableUniques = new ArrayList();
}

public UniqueList(int size) {
    growableUniques = new ArrayList(size);
}

public void add(Object thing) {
    if (!masterSet.contains(thing)) {
        masterSet.add(thing);
        growableUniques.add(thing);
    }
}

/**
 * Casts to an ArrayList of unique values
 * @return 
 */
public List getList(){
    return growableUniques;
}

public Object get(int index) {
    return growableUniques.get(index);
}

public Object[] toObjectArray() {
    int size = growableUniques.size();
    returnable = new Object[size];
    for (int i = 0; i < size; i++) {
        returnable[i] = growableUniques.get(i);
    }
    return returnable;
    }
}

I have a TestCollections class that looks like this:

package com.bprog.collections;
import com.bprog.out.Out;
/**
*
* @author Jonathan
*/
public class TestCollections {
    public static void main(String[] args){
        UniqueList ul = new UniqueList();
        ul.add("Test");
        ul.add("Test");
        ul.add("Not a copy");
        ul.add("Test"); 
        //should only contain two things
        Object[] content = ul.toObjectArray();
        Out.pl("Array Content",content);
    }
}

Works fine. All it does is it adds to a set if it does not have it already and there's an Arraylist that is returnable, as well as an object array.

AttributeError: Can only use .dt accessor with datetimelike values

Your problem here is that to_datetime silently failed so the dtype remained as str/object, if you set param errors='coerce' then if the conversion fails for any particular string then those rows are set to NaT.

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')

So you need to find out what is wrong with those specific row values.

See the docs

Count Vowels in String Python

from collections import defaultdict


def count_vowels(word):
    vowels = 'aeiouAEIOU'
    count = defaultdict(int)   # init counter
    for char in word:
        if char in vowels:
            count[char] += 1
    return count

A pythonic way to count vowels in a word, not like in java or c++, actually no need to preprocess the word string, no need for str.strip() or str.lower(). But if you'd like to count vowels case-insensitively, then before go into the for-loop, use str.lower().

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Android Material Design Button Styles

If I understand you correctly, you want to do something like this:
enter image description here

In such case, it should be just enough to use:

<item name="android:colorButtonNormal">#2196f3</item>

Or for API less than 21:

<item name="colorButtonNormal">#2196f3</item>

In addition to Using Material Theme Tutorial.

Animated variant is here.

Stored procedure - return identity as output parameter or scalar

Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.

If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.

If you prefer a result set return, then again is arguable better to use the OUTPUT clause:

INSERT INTO  MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);

This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.

Overall, I can't see a single case when returning SCOPE_IDENTITY() as a result set would be a good practice.

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

In my case the select2 would open correctly if there was zero or more pills.

But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:

$("#myselect").select2({ width: '100%' });      

How do I check if a Key is pressed on C++

check if a key is pressed, if yes, then do stuff

Consider 'select()', if this (reportedly Posix) function is available on your os.

'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)


from man page:

'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"

When select is invoked:

a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.

The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).

b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.

fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.


Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...

Then I get an fd to use in 'select()' by using open:

// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY ); 

It is useful to cout this value.

Here is a snippet to consider (from man select):

  fd_set rfds;
  struct timeval tv;
  int retval;

  /* Watch stdin (fd 0) to see when it has input. */
  FD_ZERO(&rfds);
  FD_SET(0, &rfds);

  /* Wait up to five seconds. */
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  retval = select(1, &rfds, NULL, NULL, &tv);
  /* Don't rely on the value of tv now! */

  if (retval == -1)
      perror("select()");
  else if (retval)
      printf("Data is available now.\n");  // i.e. doStuff()
      /* FD_ISSET(0, &rfds) will be true. */
  else
      printf("No data within five seconds.\n"); // i.e. key not pressed

Open another application from your own (intent)

Open application if it is exist, or open Play Store application for install it:

private void open() {
    openApplication(getActivity(), "com.app.package.here");
}

public void openApplication(Context context, String packageN) {
    Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
    if (i != null) {
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
        }
    }
}

"SDK Platform Tools component is missing!"

The latest version of the Android SDK ships with two different applications: an SDK Manager and an AVD Manager rather than one single app that was valid when this question was originally asked.

My particular problem was unrelated to the other suggestions. I'm on a network at the moment where HTTPS traffic is mostly disallowed. In order to install the Android Platform Tools I needed to turn on the option to "Force https://... sources to be fetched using http://..." and then this allowed me to install the other tools.

HTML5 form validation pattern alphanumeric with spaces?

Use below code for HTML5 validation pattern alphanumeric without / with space :-

for HTML5 validation pattern alphanumeric without space :- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"

for HTML5 validation pattern alphanumeric with space :-

onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"

Sum values in foreach loop php

$sum = 0;
foreach($group as $key=>$value)
{
   $sum+= $value;
}
echo $sum;

Override valueof() and toString() in Java enum

You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private String value;

    RandomEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static RandomEnum getEnum(String value) {
        for(RandomEnum v : values())
            if(v.getValue().equalsIgnoreCase(value)) return v;
        throw new IllegalArgumentException();
    }
}

Strip / trim all strings of a dataframe

You can try:

df[0] = df[0].str.strip()

or more specifically for all string columns

non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())

How to check if my string is equal to null?

Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.

Every variable that you create is actually a pointer on the value in your memory. For example:

String s = new String("This is just a test");

the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory. When you call System.out.println(anyObject), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer. For example:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.

For example:

int i = 123;

i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).

Okay so lets come back to the == operator. It always compares the pointer and not the content saved at the pointer's position in the memory.

Example:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.

Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.

Greetings

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

Homebrew refusing to link OpenSSL

Just execute brew info openssland read the information where it says:

If you need to have this software first in your PATH run: echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

sorting integers in order lowest to highest java

You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

Node.js connect only works on localhost

Binding to 0.0.0.0 is half the battle. There is an ip firewall (different from the one in system preferences) that blocks TCP ports. Hence port must be unblocked there as well by doing:

sudo ipfw add <PORT NUMBER> allow tcp from any to any

LAST_INSERT_ID() MySQL

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

Make docker use IPv4 for port binding

ISSUE RESOVLED:

USE docker run -it -p 80:80 --name nginx --net=host -d nginx

that's issue we face with VM some time instead of bridge network try with host that will work for you

tcp     0    0 0.0.0.0:80            0.0.0.0:*             LISTEN      - 
tcp6    0    0 :::80                 :::*                  LISTEN      -  

Maven dependency for Servlet 3.0 API?

Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):

Repository:

<repository>
  <id>jboss-public-repository-group</id>
  <name>JBoss Public Repository Group</name>
  <url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>

Dependency:

<!-- Servlet 3.0 Api Specification -->
<dependency>
   <groupId>org.jboss.spec.javax.servlet</groupId>
   <artifactId>jboss-servlet-api_3.0_spec</artifactId>
   <version>1.0.0.Beta2</version>
   <scope>provided</scope>
</dependency>

I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.

EDIT:

Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).

<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.servlet</artifactId>
  <version>3.0</version>
  <scope>provided</scope>
</dependency>

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

How can I enable the Windows Server Task Scheduler History recording?

Step 1: Open an elevated Task Scheduler (ie. right-click on the Task Scheduler icon and choose Run as administrator)

Step 2: In the Actions pane (right pane, not the actions tab), click Enable All Tasks History

That's it. Not sure why this isn't on by default, but it isn't.

How to change color of ListView items on focus and on click

The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.

Specifically, you'd set the textColor of your textViews to an XML resource like this one:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

Initializing a list to a known number of elements in Python

You could do this:

verts = list(xrange(1000))

That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list does a __len__ first to size the new list it should be fairly efficient.

Android: how to handle button click

My sample, Tested in Android studio 2.1

Define button in xml layout

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Java pulsation detect

Button clickButton = (Button) findViewById(R.id.btn1);
if (clickButton != null) {
    clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            /***Do what you want with the click here***/
        }
    });
}

how to insert date and time in oracle?

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

How to create EditText accepts Alphabets only in android?

EditText state = (EditText) findViewById(R.id.txtState);


                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(state.getText().toString());
                boolean bs = ms.matches();
                if (bs == false) {
                    if (ErrorMessage.contains("invalid"))
                        ErrorMessage = ErrorMessage + "state,";
                    else
                        ErrorMessage = ErrorMessage + "invalid state,";

                }

Intent from Fragment to Activity

 FragmentManager fragmentManager =  getFragmentManager();
 fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();

MySchedule is the name of my java class.

How do I do a not equal in Django queryset filtering?

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)

Checking for the correct number of arguments

cat script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

execute it like below -

./script.sh directory1 directory2

Output will be like -

directory1 exit
directory2 Does not exists

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

"You tried to execute a query that does not include the specified aggregate function"

I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By clause at the end.enter image description here

Access a JavaScript variable from PHP

I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?

matplotlib error - no module named tkinter

Almost all answers I searched for this issue say that Python on Windows comes with tkinter and tcl already installed, and I had no luck trying to download or install them using pip, or actviestate.com site. I eventually found that when I was installing python using the binary installer, I had unchecked the module related to TCL and tkinter. So, I ran the binary installer again and chose to modify my python version by this time selecting this option. No need to do anything manually then. If you go to your python terminal, then the following commands should show you version of tkinter installed with your Python:

import tkinter
import _tkinter
tkinter._test()

Removing all non-numeric characters from string in Python

@Ned Batchelder and @newacct provided the right answer, but ...

Just in case if you have comma(,) decimal(.) in your string:

import re
re.sub("[^\d\.]", "", "$1,999,888.77")
'1999888.77'

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

Can I bind an array to an IN() condition?

I extended PDO to do something similar to what stefs suggests, and it was easier for me in the long run:

class Array_Capable_PDO extends PDO {
    /**
     * Both prepare a statement and bind array values to it
     * @param string $statement mysql query with colon-prefixed tokens
     * @param array $arrays associatve array with string tokens as keys and integer-indexed data arrays as values 
     * @param array $driver_options see php documention
     * @return PDOStatement with given array values already bound 
     */
    public function prepare_with_arrays($statement, array $arrays, $driver_options = array()) {

        $replace_strings = array();
        $x = 0;
        foreach($arrays as $token => $data) {
            // just for testing...
            //// tokens should be legit
            //assert('is_string($token)');
            //assert('$token !== ""');
            //// a given token shouldn't appear more than once in the query
            //assert('substr_count($statement, $token) === 1');
            //// there should be an array of values for each token
            //assert('is_array($data)');
            //// empty data arrays aren't okay, they're a SQL syntax error
            //assert('count($data) > 0');

            // replace array tokens with a list of value tokens
            $replace_string_pieces = array();
            foreach($data as $y => $value) {
                //// the data arrays have to be integer-indexed
                //assert('is_int($y)');
                $replace_string_pieces[] = ":{$x}_{$y}";
            }
            $replace_strings[] = '('.implode(', ', $replace_string_pieces).')';
            $x++;
        }
        $statement = str_replace(array_keys($arrays), $replace_strings, $statement);
        $prepared_statement = $this->prepare($statement, $driver_options);

        // bind values to the value tokens
        $x = 0;
        foreach($arrays as $token => $data) {
            foreach($data as $y => $value) {
                $prepared_statement->bindValue(":{$x}_{$y}", $value);
            }
            $x++;
        }

        return $prepared_statement;
    }
}

You can use it like this:

$db_link = new Array_Capable_PDO($dsn, $username, $password);

$query = '
    SELECT     *
    FROM       test
    WHERE      field1 IN :array1
     OR        field2 IN :array2
     OR        field3 = :value
';

$pdo_query = $db_link->prepare_with_arrays(
    $query,
    array(
        ':array1' => array(1,2,3),
        ':array2' => array(7,8,9)
    )
);

$pdo_query->bindValue(':value', '10');

$pdo_query->execute();

Angular2: Cannot read property 'name' of undefined

In Angular, there is the support elvis operator ?. to protect against a view render failure. They call it the safe navigation operator. Take the example below:

The current person name is {{nullObject?.name}}

Since it is trying to access name property of a null value, the whole view disappears and you can see the error inside the browser console. It works perfectly with long property paths such as a?.b?.c?.d. So I recommend you to use it everytime you need to access a property inside a template.

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

How to click a href link using Selenium

You can use xpath as follows, try this one :

driver.findElement(By.xpath("(.//[@href='/docs/configuration'])")).click();

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

Can a foreign key be NULL and/or duplicate?

The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null.

Class Not Found Exception when running JUnit test

I had the same problem with a Gradle project with a test SourceSet with two resource directories.

This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:

sourceSets {
    test {
        resources {
            srcDir('../other-module/src/test/resources')
        }
    }
}

Doing this I had two resource directories related to the test SourceSet of the project main-module:

../other-module/src/test/resources src/test/resources (relative to the main-module folder, automatically added by the java plugin)

I find out that if I had two files with the same name in both the source directories, something in the process resources stage went wrong. As result, no compilation started and for this reason no .class were copied in the bin directory, where JUnit was looking for the classes. The ClassNotFoundException disappeared just renaming one of the two files.

HashMap with multiple values under the same key

If you use Spring Framework. There is: org.springframework.util.MultiValueMap.

To create unmodifiable multi value map:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

Or use org.springframework.util.LinkedMultiValueMap

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

Upload artifacts to Nexus, without Maven

for those who need it in Java, using apache httpcomponents 4.0:

public class PostFile {
    protected HttpPost httppost ;
    protected MultipartEntity mpEntity; 
    protected File filePath;

    public PostFile(final String fullUrl, final String filePath){
        this.httppost = new HttpPost(fullUrl);
        this.filePath = new File(filePath);        
        this.mpEntity = new MultipartEntity();
    }

    public void authenticate(String user, String password){
        String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
        httppost.setHeader("Authorization", "Basic " + encoding);
    }
    private void addParts() throws UnsupportedEncodingException{
        mpEntity.addPart("r", new StringBody("repository id"));
        mpEntity.addPart("g", new StringBody("group id"));
        mpEntity.addPart("a", new StringBody("artifact id"));
        mpEntity.addPart("v", new StringBody("version"));
        mpEntity.addPart("p", new StringBody("packaging"));
        mpEntity.addPart("e", new StringBody("extension"));

        mpEntity.addPart("file", new FileBody(this.filePath));

    }

    public String post() throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        addParts();
        httppost.setEntity(mpEntity);
        HttpResponse response = httpclient.execute(httppost);

        System.out.println("executing request " + httppost.getRequestLine());
        System.out.println(httppost.getEntity().getContentLength());

        HttpEntity resEntity = response.getEntity();

        String statusLine = response.getStatusLine().toString();
        System.out.println(statusLine);
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return statusLine;
    }
}

Java: How to access methods from another class

You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.

1) Give Alphas a Beta in the constructor. In class Alpha write:

public class Alpha {
   private Beta beta;
   public Alpha(Beta beta) {
     this.beta = beta; 
   }

and call cAlpha = new Alpha(cBeta) from main()

2) give Alphas a mutator that gives them a beta. In class Alpha write:

public class Alpha {
   private Beta beta;
   public void setBeta (Beta newBeta) {
     this.beta = beta;
   }

and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or

3) have a beta as an argument to doSomethingAlpha. in class Alpha write:

public void DoSomethingAlpha(Beta cBeta) {
      cbeta.DoSomethingBeta()
}

Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!

Is there any way to change input type="date" format?

Since the post is active 2 Months ago. so I thought to give my input as well.

In my case i recieve date from a card reader which comes in dd/mm/yyyy format.

what i do. E.g.

_x000D_
_x000D_
var d="16/09/2019" // date received from card_x000D_
function filldate(){_x000D_
    document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");_x000D_
    }
_x000D_
<input type="date" id="cardexpirydate">_x000D_
<br /><br />_x000D_
<input type="button" value="fill the date" onclick="filldate();">
_x000D_
_x000D_
_x000D_

what the code do:

  1. it splits the date which i get as dd/mm/yyyy (using split()) on basis of "/" and makes an array,
  2. it then reverse the array (using reverse()) since the date input supports the reverse of what i get.
  3. then it joins (using join())the array to a string according the format required by the input field

All this is done in a single line.

i thought this will help some one so i wrote this.

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

How to check file MIME type with javascript before upload?

If you just want to check if the file uploaded is an image you can just try to load it into <img> tag an check for any error callback.

Example:

var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();

reader.onload = function (e) {
    imageExists(e.target.result, function(exists){
        if (exists) {

            // Do something with the image file.. 

        } else {

            // different file format

        }
    });
};

reader.readAsDataURL(input.files[0]);


function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}

How can I get the client's IP address in ASP.NET MVC?

In a class you might call it like this:

public static string GetIPAddress(HttpRequestBase request) 
{
    string ip;
    try
    {
        ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(ip))
        {
            if (ip.IndexOf(",") > 0)
            {
                string[] ipRange = ip.Split(',');
                int le = ipRange.Length - 1;
                ip = ipRange[le];
            }
        } else
        {
            ip = request.UserHostAddress;
        }
    } catch { ip = null; }

    return ip; 
}

I used this in a razor app with great results.

Restarting cron after changing crontab file?

1) If file /var/spool/cron/crontabs/root edit via SFTP client - need service cron restart. Reload service not work.

2) If edit file /var/spool/cron/crontabs/root via console linux (nano, mc) - restart NOT need.

3) If edit cron via crontab -e - restart NOT need.

Remove grid, background color, and top and right borders from ggplot2

Simplification from the above Andrew's answer leads to this key theme to generate the half border.

theme (panel.border = element_blank(),
       axis.line    = element_line(color='black'))

Selenium 2.53 not working on Firefox 47

Try using firefox 46.0.1. It best matches with Selenium 2.53

https://ftp.mozilla.org/pub/firefox/releases/46.0.1/win64/en-US/

How do I configure the proxy settings so that Eclipse can download new plugins?

Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=myproxy
-Dhttp.proxyPort=8080
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1

These settings require IDE restart (sometimes with -clean -refresh command line options).
https://bugs.eclipse.org/bugs/show_bug.cgi?id=281472


Java8, Eclipse Neon3, slow proxy server:

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
-Dhttp.proxyHost=<proxy>
-Dhttp.proxyPort=8080
-Dhttps.proxyHost=<proxy>
-Dhttps.proxyPort=8080
-DsocksProxyHost=
-DsocksProxyPort=
-Dhttp.proxyUser=<user>
-Dhttp.proxyPassword=<pass>
-Dhttp.nonProxyHosts=localhost|127.0.0.1
-Dorg.eclipse.equinox.p2.transport.ecf.retry=5
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.connectTimeout=15000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts=20
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.browse.connectTimeout=3000
-Dorg.eclipse.ecf.provider.filetransfer.browse.readTimeout=1000

pip install mysql-python fails with EnvironmentError: mysql_config not found

I had the same problem in the Terraform:light container. It is based on Alpine.

There you have to install mariadb-dev with:

apk add mariadb-dev

But that one is not enough because also all the other dependencies are missed:

apk add python2 py2-pip gcc python2-dev musl-dev

How to validate a form with multiple checkboxes to have atleast one checked

How about this:

$(document).ready(function() {
    $('#subscribeForm').submit(function() {
        var $fields = $(this).find('input[name="list"]:checked');
        if (!$fields.length) {
            alert('You must check at least one box!');
            return false; // The form will *not* submit
        }
    });
});

How to set time to 24 hour format in Calendar

Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23) 
            k Hour in day (1-24) 
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }        
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

Change location of log4j.properties

You can use PropertyConfigurator to load your log4j.properties wherever it is located in the disk.

Example:

Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();

try {
    p.load(new FileInputStream(log4JPropertyFile));
    PropertyConfigurator.configure(p);
    logger.info("Wow! I'm configured!");
} catch (IOException e) {
    //DAMN! I'm not....

}

If you have an XML Log4J configuration, use DOMConfigurator instead.

socket connect() vs bind()

bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)

Get timezone from DateTime

Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.

The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.

As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.

Is there any publicly accessible JSON data source to test with real world data?

The Tumbler V2 API provides a pure JSON response but requires jumping through a few hoops:

  1. Register an application
  2. Get your "OAuth Consumer Key" which you'll find when editing your application from the apps page
  3. Use any of the methods that only require an API Key for authentication as this can be passed in the URL, e.g. posts
  4. Enjoy your JSON response!

Example URL: http://api.tumblr.com/v2/blog/puppygifs.tumblr.com/posts/photo?api_key=YOUR_KEY_HERE

Result showing tree structure in Fiddler:

Screenshot

How to return a result from a VBA function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

How to find the day, month and year with moment.js

I know this has already been answered, but I stumbled across this question and went down the path of using format, which works, but it returns them as strings when I wanted integers.

I just realized that moment comes with date, month and year methods that return the actual integers for each method.

moment().date()
moment().month()  // jan=0, dec=11
moment().year()

clearing select using jquery

For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.

Example

<select id="mySelectOption">
   <option value="" selected disabled>Please select</option>
</select>

Answer

$('#mySelectOption').val('Please Select');

Setting Column width in Apache POI

Unfortunately there is only the function setColumnWidth(int columnIndex, int width) from class Sheet; in which width is a number of characters in the standard font (first font in the workbook) if your fonts are changing you cannot use it. There is explained how to calculate the width in function of a font size. The formula is:

width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

You can always use autoSizeColumn(int column, boolean useMergedCells) after inputting the data in your Sheet.

How can I trigger a JavaScript event click

UPDATE

This was an old answer. Nowadays you should just use click. For more advanced event firing, use dispatchEvent.

_x000D_
_x000D_
const body = document.body;_x000D_
_x000D_
body.addEventListener('click', e => {_x000D_
  console.log('clicked body');_x000D_
});_x000D_
_x000D_
console.log('Using click()');_x000D_
body.click();_x000D_
_x000D_
console.log('Using dispatchEvent');_x000D_
body.dispatchEvent(new Event('click'));
_x000D_
_x000D_
_x000D_

Original Answer

Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/

Updated to work with IE9+

/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9){
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

     if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;

            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;

            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
        event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else  if (node.fireEvent) {
        // IE-old school style, you can drop this if you don't need to support IE8 and lower
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};

Note that calling fireEvent(inputField, 'change'); does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since calling input.value="Something" won't trigger a change event.

Resource u'tokenizers/punkt/english.pickle' not found

Go to python console by typing

$ python

in your terminal. Then, type the following 2 commands in your python shell to install the respective packages:

>> nltk.download('punkt') >> nltk.download('averaged_perceptron_tagger')

This solved the issue for me.

How to get featured image of a product in woocommerce

get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.

Try this:

<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
    <div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
        <?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
        <?php if($featured_image) { ?>
        <img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
        <?php } ?>
        <p><?php the_title(); ?></p>
        <span class="price"><?php echo $product->get_price_html(); ?></span>
    </div>
<?php endwhile; ?>

time delayed redirect?

Edit:

The problem i face is that HTML5 is all on one index page. So i need the timer to start on click of the blog link.

Try calling the setTimeout inside a click handler on the blog link,

$('#blogLink').click (function (e) {
   e.preventDefault(); //will stop the link href to call the blog page

   setTimeout(function () {
       window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
    }, 2000); //will call the function after 2 secs.

});

Try using setTimeout function like below,

setTimeout(function () {
   window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
}, 2000); //will call the function after 2 secs.

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

Css transition from display none to display block, navigation with subnav

You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.

_x000D_
_x000D_
nav.main ul ul {_x000D_
    position: absolute;_x000D_
    list-style: none;_x000D_
    display: none;_x000D_
    opacity: 0;_x000D_
    visibility: hidden;_x000D_
    padding: 10px;_x000D_
    background-color: rgba(92, 91, 87, 0.9);_x000D_
    -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
            transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
    display: block;_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
    animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
    0% {_x000D_
        opacity: 0;_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 1;_x000D_
    }_x000D_
}
_x000D_
<nav class="main">_x000D_
    <ul>_x000D_
        <li>_x000D_
            <a href="">Lorem</a>_x000D_
            <ul>_x000D_
                <li><a href="">Ipsum</a></li>_x000D_
                <li><a href="">Dolor</a></li>_x000D_
                <li><a href="">Sit</a></li>_x000D_
                <li><a href="">Amet</a></li>_x000D_
            </ul>_x000D_
        </li>_x000D_
    </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/

What is the hamburger menu icon called and the three vertical dots icon called?

Not an official name per se, but I've heard vertical ellipsis referred to as "snowman" in SAS community.

Copy to Clipboard for all Browsers using javascript

I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:

If you want your users to be able to click on a button and copy some text, you may have to use Flash.

If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).

It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.

This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!

Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:

YUI.add('clipboard', function(Y) {


// Change this to the id of the text area you would like to always paste in to:

pasteBox = Y.one('#pasteDIV');


// Make a hidden textbox somewhere off the page.

Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');


// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:

// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
    copyData();
        //  Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
        //  alert(e.keyCode);
        //  }, 'body',  'down:', Y);
}, 'body',  'down:91,224,17', Y);

// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
    // Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
    // Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
    pasteBox.select();
}, '#copyBox',  'down:86', Y);

// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
    pasteBox.select();
}, '#copyBox',  'down:65', Y);



// What to do when keybindings are fired:

// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
    var txt = '';
    // props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
        if (window.getSelection) { txt = window.getSelection(); }
        else if (document.getSelection) { txt = document.getSelection(); }
        else if (document.selection) { txt = document.selection.createRange().text; }
        else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');

    // If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy. 
        if(txt=='') {
                copyBox.select();
        }
    // They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
        else if (txt == copyBox.get('value')) {
        alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
                copyBox.select();
        } else {
                // They also might have selected something completely different! If so, let them. It's only fair.
        }
}
});

Hope someone else finds this useful :]

How to extract text from a string using sed?

Try this instead:

echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'

But note, if there is two pattern on one line, it will prints the 2nd.

Insert line after first match using sed

I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:

insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt

In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here

Flutter does not find android sdk

For mac users,

It was working fine yesterday, now the hell broke. I was able to fix it.

My issue was with ANDROID_HOME

// This is wrong. No idea how it was working earlier.
ANDROID_HOME = Library/Android/sdk 

If you did the same, change it to:

ANDROID_HOME = /Users/rana.singh/Library/Android/sdk 

.bash_profile has

export ANDROID_HOME=/Users/rana.singh/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

How do you check what version of SQL Server for a database using TSQL?

Try this:

if (SELECT LEFT(CAST(SERVERPROPERTY('productversion') as varchar), 2)) = '10'
BEGIN

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/.

Then it will take you to inside that folder.

Get full query string in C# ASP.NET

Just use Request.QueryString.ToString() to get full query string, like this:

string URL = "http://www.example.com/rendernews.php?"+Request.Querystring.ToString();

How to have click event ONLY fire on parent DIV, not children?

$(".advanced ul li").live('click',function(e){
    if(e.target != this) return;
    //code
    // this code will execute only when you click to li and not to a child
})

SVN - Checksum mismatch while updating

I had a simllar problem. Main provider was antivirus "FortiClient" (antivirus + VPN CLient). When I disabled it - all update/checkout was made correctly

What does O(log n) mean exactly?

In information technology it means that:

  f(n)=O(g(n)) If there is suitable constant C and N0 independent on N, 
  such that
  for all N>N0  "C*g(n) > f(n) > 0" is true.

Ant it seems that this notation was mostly have taken from mathematics.

In this article there is a quote: D.E. Knuth, "BIG OMICRON AND BIG OMEGA AND BIG THETA", 1976:

On the basis of the issues discussed here, I propose that members of SIGACT, and editors of computer science and mathematics journals, adopt notations as defined above, unless a better alternative can be found reasonably soon.

Today is 2016, but we use it still today.


In mathematical analysis it means that:

  lim (f(n)/g(n))=Constant; where n goes to +infinity

But even in mathematical analysis sometimes this symbol was used in meaning "C*g(n) > f(n) > 0".

As I know from university the symbol was intoduced by German mathematician Landau (1877-1938)

Python - Get path of root project structure

I decided for myself as follows.
Need to get the path to 'MyProject/drivers' from the main file.

MyProject/
+--- RootPackge/
¦    +-- __init__.py
¦    +-- main.py
¦    +-- definitions.py
¦
+--- drivers/
¦    +-- geckodriver.exe
¦
+-- requirements.txt
+-- setup.py

definitions.py
Put not in the root of the project, but in the root of the main package

from pathlib import Path

ROOT_DIR = Path(__file__).parent.parent

Use ROOT_DIR:
main.py

# imports must be relative,
# not from the root of the project,
# but from the root of the main package.
# Not this way:
# from RootPackge.definitions import ROOT_DIR
# But like this:
from definitions import ROOT_DIR

# Here we use ROOT_DIR
# get path to MyProject/drivers
drivers_dir = ROOT_DIR / 'drivers'
# Thus, you can get the path to any directory
# or file from the project root

driver = webdriver.Firefox(drivers_dir)
driver.get('http://www.google.com')

Then PYTHON_PATH will not be used to access the 'definitions.py' file.

Works in PyCharm:
run file 'main.py' (ctrl + shift + F10 in Windows)

Works in CLI from project root:

$ py RootPackge/main.py

Works in CLI from RootPackge:

$ cd RootPackge
$ py main.py

Works from directories above project:

$ cd ../../../../
$ py MyWork/PythoProjects/MyProject/RootPackge/main.py

Works from anywhere if you give an absolute path to the main file.
Doesn't depend on venv.

How to stretch in width a WPF user control to its window?

What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

If you are on Windows and facing the same problem, have a look at this answer of @Inazense https://stackoverflow.com/a/52869803/4567504.

In Visual studio code I was not able to find “Shell Command: Install 'code' command in PATH command.” so I had to do this manually.

  1. Open Environment Variables (System > Advance system settings > Advanced tab > environment variables) on system variables click on Path and click Edit and add new Path named

"C:\Users\Your_Username\AppData\Local\Programs\Microsoft VS Code\bin"

Now you are done! restart command prompt and try again

cancelling a handler.postdelayed process

Here is a class providing a cancel method for a delayed action

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

Spring Boot - Handle to Hibernate SessionFactory

Another way similar to the yglodt's

In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And in your configuration class:

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
    return hemf.getSessionFactory();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

How to use jQuery with Angular?

When you use Angular, try not to use the jquery library. Try using the features and the libraries that are produced for angular framework. If you want to use the jquery functions like find(), html(), closest() and etc.., I suggest using the pure js. example: querySelector(), innerHTML, parentElement and etc...

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

I've discovered that if the filename has 300 in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT error.

How to add 'libs' folder in Android Studio?

The solution for me was very simple (after 10 hours of searching). Above where your folders are there is a combobox that says "android" click it and choose "Project".

enter image description here

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

Save Dataframe to csv directly to s3 Python

since you are using boto3.client(), try:

import boto3
from io import StringIO #python3 
s3 = boto3.client('s3', aws_access_key_id='key', aws_secret_access_key='secret_key')
def copy_to_s3(client, df, bucket, filepath):
    csv_buf = StringIO()
    df.to_csv(csv_buf, header=True, index=False)
    csv_buf.seek(0)
    client.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key=filepath)
    print(f'Copy {df.shape[0]} rows to S3 Bucket {bucket} at {filepath}, Done!')

copy_to_s3(client=s3, df=df_to_upload, bucket='abc', filepath='def/test.csv')

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

git stash -> merge stashed change with current changes

May be, it is not the very worst idea to merge (via difftool) from ... yes ... a branch!

> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch

Best practice to validate null and empty collection in Java

When you use spring then you can use

boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);

where obj is any [map,collection,array,aything...]

otherwise: the code is:

public static boolean isEmpty(Object[] array) {
    return (array == null || array.length == 0);
}

public static boolean isEmpty(Object obj) {
    if (obj == null) {
        return true;
    }

    if (obj.getClass().isArray()) {
        return Array.getLength(obj) == 0;
    }
    if (obj instanceof CharSequence) {
        return ((CharSequence) obj).length() == 0;
    }
    if (obj instanceof Collection) {
        return ((Collection) obj).isEmpty();
    }
    if (obj instanceof Map) {
        return ((Map) obj).isEmpty();
    }

    // else
    return false;
}

for String best is:

boolean isNullOrEmpty = (str==null || str.trim().isEmpty());

Django MEDIA_URL and MEDIA_ROOT

This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

Foreign Key naming scheme

Based on the answers and comments here, a naming convention which includes the FK table, FK field, and PK table (FK_FKTbl_FKCol_PKTbl) should avoid FK constraint name collisions.

So, for the given tables here:

fk_task_userid_user
fk_note_userid_user

So, if you add a column to track who last modified a task or a note...

fk_task_modifiedby_user
fk_note_modifiedby_user

JQuery Number Formatting

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

Android XML Percent Symbol

A tricky method: using small percent sign as below

 <string name="zone_50">Fat Burning (50&#65130; to 60&#65130;)</string> 

Percent Sign on Wikipedia

How to check if a MySQL query using the legacy API was successful?

mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function For e.g

$result=mysql_query($sql)

or

die(mysql_error());

In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Programmatically navigate using React router

with React-Router v4 on the horizon, there is now a new way of doing this.

import { MemoryRouter, BrowserRouter } from 'react-router';

const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;

<Router location="/page-to-go-to"/>

react-lego is an example app that shows how to use/update react-router and it includes example functional tests which navigate the app.

Subtracting time.Duration from time in Go

There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

E.g. when you need to substract an hour and a half, you can do that like so:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo

multiple plot in one figure in Python

This is very simple to do:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plot as many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

How does `scp` differ from `rsync`?

One major feature of rsync over scp (beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.

Centos manpages mention this the end of the --checksum option description:

Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

Replace Default Null Values Returned From Left Outer Join

MySQL

COALESCE(field, 'default')

For example:

  SELECT
    t.id,
    COALESCE(d.field, 'default')
  FROM
     test t
  LEFT JOIN
     detail d ON t.id = d.item

Also, you can use multiple columns to check their NULL by COALESCE function. For example:

mysql> SELECT COALESCE(NULL, 1, NULL);
        -> 1
mysql> SELECT COALESCE(0, 1, NULL);
        -> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
        -> NULL

How can I select an element by name with jQuery?

Performance

Today (2020.06.16) I perform tests for chosen solutions on MacOs High Sierra on Chrome 83.0, Safari 13.1.1 and Firefox 77.0.

Conclusions

Get elements by name

  • getElementByName (C) is fastest solution for all browsers for big and small arrays - however I is probably some kind of lazy-loading solution or It use some internal browser hash-cache with name-element pairs
  • mixed js-jquery solution (B) is faster than querySelectorAll (D) solution
  • pure jquery solution (A) is slowest

Get rows by name and hide them (we exclude precalculated native solution (I) - theoretically fastest) from comparison - it is used as reference)

  • surprisingly the mixed js-jquery solution (F) is fastest on all browsers
  • surprisingly the precalculated solution (I) is slower than jquery (E,F) solutions for big tables (!!!) - I check that .hide() jQuery method set style "default:none" on hidden elements - but it looks that they find faster way of do it than element.style.display='none'
  • jquery (E) solution is quite-fast on big tables
  • jquery (E) and querySelectorAll (H) solutions are slowest for small tables
  • getElementByName (G) and querySelectorAll (H) solutions are quite slow for big tables

enter image description here

Details

I perform two tests for read elements by name (A,B,C,D) and hide that elements (E,F,G,H,I)

  • small table - 3 rows - you can run test HERE
  • big table - 1000 rows - you can run test HERE

Snippet below presents used codes

_x000D_
_x000D_
//https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery#

// https://jsbench.me/o6kbhyyvib/1
// https://jsbench.me/2fkbi9rirv/1

function A() {
  return $('[name=tcol1]');
}

function B() {
  return $(document.getElementsByName("tcol1"))
}

function C() {
  return document.getElementsByName("tcol1")
}

function D() {
  return document.querySelectorAll('[name=tcol1]')
}

function E() {
  $('[name=tcol1]').hide();
}

function F() {
  $(document.getElementsByName("tcol1")).hide();
}

function G() {
  document.getElementsByName("tcol1").forEach(e=>e.style.display='none'); 
}

function H() {
  document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none'); 
}

function I() {
  let elArr = [...document.getElementsByName("tcol1")];
  let length = elArr.length
  for(let i=0; i<length; i++) elArr[i].style.display='none';
}




// -----------
// TEST
// -----------

function reset() { $('td[name=tcol1]').show(); } 

[A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`)) ;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>This snippet only presents used codes</div>
<table>
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>  
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>
</table>

<button onclick="E()">E: hide</button>
<button onclick="F()">F: hide</button>
<button onclick="G()">G: hide</button>
<button onclick="H()">H: hide</button>
<button onclick="I()">I: hide</button><br>
<button onclick="reset()">reset</button>
_x000D_
_x000D_
_x000D_

Example results on Chrome

enter image description here

How to unstage large number of files without deleting the content

Use git reset HEAD to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file to do so.)

The pipe operator, in a shell, takes the stdout of the process on the left and passes it as stdin to the process on the right. It's essentially the equivalent of:

$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out

but instead it's $ proc1 | proc2, the second process can start getting data before the first is done outputting it, and there's no actual file involved.

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

Simple (non-secure) hash function for JavaScript?

// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
    if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
    var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
    for (i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);
        bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
    }
    var chunk_len = Math.ceil(bytes.length / 32);   
    for (i=0; i<bytes.length; i++) {
        j += bytes[i];
        k++;
        if ((k == chunk_len) || (i == bytes.length-1)) {
            a = Math.floor( j / k );
            if (a < 32)
                hash += '0';
            else if (a > 126)
                hash += 'z';
            else
                hash += dict[  Math.floor( (a-32) / 2.76) ];
            j = k = 0;
        }
    }
    return hash;
}

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

PHP date add 5 year to current date

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

How to overwrite existing files in batch?

Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.

echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y

The "/Y" parameter at the end overwrites the destination file, if it exists.

See last changes in svn

svn log -r {2009-09-17}:HEAD

where 2009-09-17 is the date you went on holiday. To see the changed files as well as the summary, add a -v option:

svn log -r {2009-09-17}:HEAD -v

I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.

Change old commit message on Git

FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!

How to get current available GPUs in tensorflow?

Use this way and check all parts :

from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds


version = tf.__version__
executing_eagerly = tf.executing_eagerly()
hub_version = hub.__version__
available = tf.config.experimental.list_physical_devices("GPU")

print("Version: ", version)
print("Eager mode: ", executing_eagerly)
print("Hub Version: ", h_version)
print("GPU is", "available" if avai else "NOT AVAILABLE")

Python: Removing spaces from list objects

result = map(str.strip, hello)

Update rows in one table with data from another table based on one column in each being equal

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

How to initialize weights in PyTorch?

    import torch.nn as nn        

    # a simple network
    rand_net = nn.Sequential(nn.Linear(in_features, h_size),
                             nn.BatchNorm1d(h_size),
                             nn.ReLU(),
                             nn.Linear(h_size, h_size),
                             nn.BatchNorm1d(h_size),
                             nn.ReLU(),
                             nn.Linear(h_size, 1),
                             nn.ReLU())

    # initialization function, first checks the module type,
    # then applies the desired changes to the weights
    def init_normal(m):
        if type(m) == nn.Linear:
            nn.init.uniform_(m.weight)

    # use the modules apply function to recursively apply the initialization
    rand_net.apply(init_normal)