Programs & Examples On #Opensearch

Open Search is a document description format for defining an API like interface to execute simple searches on that site. ex: http://example.com/search?q={searchTerms}

Base64 Encoding Image

$encoded_data = base64_encode(file_get_contents('path-to-your-image.jpg'));    

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Had this error when I had deleted a table from the database. Solved it by right clicking on EDMX diagram, going to Properties, selecting the table from the list in the Properties window, and deleting it (using delete key) from the diagram.

Toolbar overlapping below status bar

Remove below lines from style or style(21)

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
<item name="android:windowTranslucentStatus">false</item>

Convert Variable Name to String?

You somehow have to refer to the variable you want to print the name of. So it would look like:

print varname(something_else)

There is no such function, but if there were it would be kind of pointless. You have to type out something_else, so you can as well just type quotes to the left and right of it to print the name as a string:

print "something_else"

Getting the parent of a directory in Bash

if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd). This would give 3 parents directories up

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

Is it possible to select the last n items with nth-child?

:nth-last-child(-n+2) should do the trick

What is the symbol for whitespace in C?

There is no particular symbol for whitespace. It is actually a set of some characters which are:

' '      space 
'\t'     horizontal tab 
'\n'     newline
'\v'     vertical tab 
'\f'     feed 
'\r'     carriage return    

Use isspace standard library function from ctype.h if you want to check for any of these white-spaces.

For just a space, use ' '.

Writing JSON object to a JSON file with fs.writeFileSync

to open a local file or url with chrome, i used:

const open = require('open'); // npm i open
// open('http://google.com')
open('build_mytest/index.html', {app: "chrome.exe"})

dropping a global temporary table

yes - the engine will throw different exceptions for different conditions.

you will change this part to catch the exception and do something different

  EXCEPTION
      WHEN OTHERS THEN

here is a reference

http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/07_errs.htm

Jquery selector input[type=text]')

$('.sys').children('input[type=text], select').each(function () { ... });

EDIT: Actually this code above is equivalent to the children selector .sys > input[type=text] if you want the descendant select (.sys input[type=text]) you need to use the options given by @NiftyDude.

More information:

How to SHUTDOWN Tomcat in Ubuntu?

Try using this command : (this will stop tomcat servlet this really helps)

sudo service tomcat7 stop

or

sudo tomcat7 restart (if you need a restart)

How to create a foreign key in phpmyadmin

A simple SQL example would be like this:

ALTER TABLE `<table_name>` ADD `<column_name>` INT(11) NULL DEFAULT NULL ;

Make sure you use back ticks `` in table name and column name

A cron job for rails: best practices?

I use backgroundrb.

http://backgroundrb.rubyforge.org/

I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.

jQuery Remove string from string

I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,

  • If the username is not allowed to have spaces, then just search for everything before the first space or comma (thus finding both "u1 likes this" and "u1, u2, and u3 like this").
  • If it is allowed to have a space, it would probably be easier to wrap each username in it's own span tag server-side, before sending it to the client, and then just working with the span tags.

How do I create a copy of an object in PHP?

According to previous comment, if you have another object as a member variable, do following:

class MyClass {
  private $someObject;

  public function __construct() {
    $this->someObject = new SomeClass();
  }

  public function __clone() {
    $this->someObject = clone $this->someObject;
  }

}

Now you can do cloning:

$bar = new MyClass();
$foo = clone $bar;

How to check for null in Twig?

Without any assumptions the answer is:

{% if var is null %}

But this will be true only if var is exactly NULL, and not any other value that evaluates to false (such as zero, empty string and empty array). Besides, it will cause an error if var is not defined. A safer way would be:

{% if var is not defined or var is null %}

which can be shortened to:

{% if var|default is null %}

If you don't provide an argument to the default filter, it assumes NULL (sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):

{% if var|default is empty %}

Print very long string completely in pandas dataframe

Another easier way to print the whole string is to call values on the dataframe.

df = pd.DataFrame({'one' : ['one', 'two', 
      'This is very long string very long string very long string veryvery long string']})

print(df.values)

The Output will be

[['one']
 ['two']
 ['This is very long string very long string very long string veryvery long string']]

How can I decode HTML characters in C#?

If there is no Server context (i.e your running offline), you can use HttpUtility.HtmlDecode.

What is the difference between x86 and x64

x86 is for a 32-bit OS, and x64 is for a 64-bit OS

Intercept a form submit in JavaScript and prevent normal submission

<form onSubmit="return captureForm()"> that should do. Make sure that your captureForm() method returns false.

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

Maximum length of the textual representation of an IPv6 address?

I think @Deepak answer in this link is more close to correct answer. Max length for client ip address. So correct size is 45 not 39. Sometimes we try to scrounge in fields size but it seems to better if we prepare enough storage size.

UILabel is not auto-shrinking text to fit label size

In case you are still searching for a better solution, I think this is what you want:

A Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle (this property is effective only when the numberOfLines property is set to 1).

When setting this property, minimumScaleFactor MUST be set too (a good default is 0.5).

Swift

var adjustsFontSizeToFitWidth: Bool { get set }

Objective-C

@property(nonatomic) BOOL adjustsFontSizeToFitWidth;

A Boolean value indicating whether spacing between letters should be adjusted to fit the string within the label’s bounds rectangle.

Swift

var allowsDefaultTighteningForTruncation: Bool { get set }

Objective-C

@property(nonatomic) BOOL allowsDefaultTighteningForTruncation;

Source.

Determine if 2 lists have the same elements, regardless of order?

As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.

def sequences_contain_same_items(a, b):
    for item in a:
        try:
            i = b.index(item)
        except ValueError:
            return False
        b = b[:i] + b[i+1:]
    return not b

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

Summary

To fix this issue encountered while running local app vs remote database, use SQL Server Configuration Manager to add an alias for the remote database.

Details

I had run into this problem recently when transitioning from a Windows 7 to a Windows 10 laptop. I was running a local development and runtime environment accessing our Dev database on a remote server. We access the Dev database through a server alias setup through SQL Server Client Network Utility (cliconfg.exe). After confirming that the alias was correctly setup in both the 64 and 32 bit versions of the utility and that the database server was accessible from the new laptop via SSMS, I still got the error seen by the OP (not the OP's IP address, of course).

It was necessary to use SQL Server Configuration Manager to add an alias for the remote Dev database server. Fixed things right up.

enter image description here

iOS: Modal ViewController with transparent background

I added these three lines in the init method in the presented view controller, and works like a charm:

self.providesPresentationContextTransitionStyle = YES;
self.definesPresentationContext = YES;
[self setModalPresentationStyle:UIModalPresentationOverCurrentContext];

EDIT (working on iOS 9.3):

self.modalPresentationStyle = UIModalPresentationOverFullScreen;

As per documentation:

UIModalPresentationOverFullScreen A view presentation style in which the presented view covers the screen. The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.

Available in iOS 8.0 and later.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

Why do we use web.xml?

It says all the requests to go through WicketFilter


Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level


This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Disable Deploy on Save in the Project's Properties/Run screen. That's what worked for me finally. Why the hell NetBeans screws this up is beyond me.

Note: I was able to compile the file it was complaining about using right-click in NetBeans. Apparently it wasn't really compiling it when I used Build & Compile since that gave no errors at all. But then after that, the errors just moved to another java class file. I couldn't compile then since it was grayed out. I also tried deleting the build and dist directories in my NetBeans project files but that didn't help either.

SQL Server Escape an Underscore

Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.

For your case, the following WHERE clauses are equivalent:

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

try

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'show advanced options', 1
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

then rebuild your index

Cannot use Server.MapPath

you can try using this

    System.Web.HttpContext.Current.Server.MapPath(path);

or use HostingEnvironment.MapPath

    System.Web.Hosting.HostingEnvironment.MapPath(path);

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

AngularJS: How to run additional code after AngularJS has rendered a template?

I came with a pretty simple solution. I'm not sure whether it is the correct way to do it but it works in a practical sense. Let's directly watch what we want to be rendered. For example in a directive that includes some ng-repeats, I would watch out for the length of text (you may have other things!) of paragraphs or the whole html. The directive will be like this:

.directive('myDirective', [function () {
    'use strict';
    return {

        link: function (scope, element, attrs) {
            scope.$watch(function(){
               var whole_p_length = 0;
               var ps = element.find('p');
                for (var i=0;i<ps.length;i++){
                    if (ps[i].innerHTML == undefined){
                        continue
                    }
                    whole_p_length+= ps[i].innerHTML.length;
                }
                //it could be this too:  whole_p_length = element[0].innerHTML.length; but my test showed that the above method is a bit faster
                console.log(whole_p_length);
                return whole_p_length;
            }, function (value) {   
                //Code you want to be run after rendering changes
            });
        }
}]);

NOTE that the code actually runs after rendering changes rather complete rendering. But I guess in most cases you can handle the situations whenever rendering changes happen. Also you could think of comparing this ps length (or any other measure) with your model if you want to run your code only once after rendering completed. I appreciate any thoughts/comments on this.

How could I create a function with a completion handler in Swift?

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

Hope it helps.

SLF4J: Class path contains multiple SLF4J bindings

For me, it turned out to be an Eclipse/Maven issue after switch from log4j to logback. Take a look into your .classpath file and search for the string "log4j".

In my case I had the following there: <classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-log4j12/1.7.1/slf4j-log4j12-1.7.1.jar"/> <classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.17/log4j-1.2.17.jar" />

Removing those entries from the file (or you could regenerate it) fixed the issue.

array_push() with key value pair

You don't need to use array_push() function, you can assign new value with new key directly to the array like..

$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);


Output:

   Array(
     [color1] => red
     [color2] => blue
     [color3] => green
   )

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Try like this:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'

Could not find the main class, program will exit

The Manifest text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Delete element in a slice

In golang's wiki it show some tricks for slice, including delete an element from slice.

Link: enter link description here

For example a is the slice which you want to delete the number i element.

a = append(a[:i], a[i+1:]...)

OR

a = a[:i+copy(a[i:], a[i+1:])]

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

How to mount a host directory in a Docker container

I had the same requirement to mount host directory from container and I used volume mount command. But during testing noticed that it's creating files inside container too but after some digging found that they are just symbolic links and actual file system used form host machine.

Disposing WPF User Controls

My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).

I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!

Simple Android RecyclerView example

You can use abstract adapter with diff utils and filter

SimpleAbstractAdapter.kt

abstract class SimpleAbstractAdapter<T>(private var items: ArrayList<T> = arrayListOf()) : RecyclerView.Adapter<SimpleAbstractAdapter.VH>() {
   protected var listener: OnViewHolderListener<T>? = null
   private val filter = ArrayFilter()
   private val lock = Any()
   protected abstract fun getLayout(): Int
   protected abstract fun bindView(item: T, viewHolder: VH)
   protected abstract fun getDiffCallback(): DiffCallback<T>?
   private var onFilterObjectCallback: OnFilterObjectCallback? = null
   private var constraint: CharSequence? = ""

override fun onBindViewHolder(vh: VH, position: Int) {
    getItem(position)?.let { bindView(it, vh) }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
    return VH(parent, getLayout())
}

override fun getItemCount(): Int = items.size

protected abstract class DiffCallback<T> : DiffUtil.Callback() {
    private val mOldItems = ArrayList<T>()
    private val mNewItems = ArrayList<T>()

    fun setItems(oldItems: List<T>, newItems: List<T>) {
        mOldItems.clear()
        mOldItems.addAll(oldItems)
        mNewItems.clear()
        mNewItems.addAll(newItems)
    }

    override fun getOldListSize(): Int {
        return mOldItems.size
    }

    override fun getNewListSize(): Int {
        return mNewItems.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return areItemsTheSame(
                mOldItems[oldItemPosition],
                mNewItems[newItemPosition]
        )
    }

    abstract fun areItemsTheSame(oldItem: T, newItem: T): Boolean

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return areContentsTheSame(
                mOldItems[oldItemPosition],
                mNewItems[newItemPosition]
        )
    }

    abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean
}

class VH(parent: ViewGroup, @LayoutRes layout: Int) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(layout, parent, false))

interface OnViewHolderListener<T> {
    fun onItemClick(position: Int, item: T)
}

fun getItem(position: Int): T? {
    return items.getOrNull(position)
}

fun getItems(): ArrayList<T> {
    return items
}

fun setViewHolderListener(listener: OnViewHolderListener<T>) {
    this.listener = listener
}

fun addAll(list: List<T>) {
    val diffCallback = getDiffCallback()
    when {
        diffCallback != null && !items.isEmpty() -> {
            diffCallback.setItems(items, list)
            val diffResult = DiffUtil.calculateDiff(diffCallback)
            items.clear()
            items.addAll(list)
            diffResult.dispatchUpdatesTo(this)
        }
        diffCallback == null && !items.isEmpty() -> {
            items.clear()
            items.addAll(list)
            notifyDataSetChanged()
        }
        else -> {
            items.addAll(list)
            notifyDataSetChanged()
        }
    }
}

fun add(item: T) {
    items.add(item)
    notifyDataSetChanged()
}

fun add(position:Int, item: T) {
    items.add(position,item)
    notifyItemInserted(position)
}

fun remove(position: Int) {
    items.removeAt(position)
    notifyItemRemoved(position)
}

fun remove(item: T) {
    items.remove(item)
    notifyDataSetChanged()
}

fun clear(notify: Boolean=false) {
    items.clear()
    if (notify) {
        notifyDataSetChanged()
    }
}

fun setFilter(filter: SimpleAdapterFilter<T>): ArrayFilter {
    return this.filter.setFilter(filter)
}

interface SimpleAdapterFilter<T> {
    fun onFilterItem(contains: CharSequence, item: T): Boolean
}

fun convertResultToString(resultValue: Any): CharSequence {
    return filter.convertResultToString(resultValue)
}

fun filter(constraint: CharSequence) {
    this.constraint = constraint
    filter.filter(constraint)
}

fun filter(constraint: CharSequence, listener: Filter.FilterListener) {
    this.constraint = constraint
    filter.filter(constraint, listener)
}

fun getFilter(): Filter {
    return filter
}

interface OnFilterObjectCallback {
    fun handle(countFilterObject: Int)
}

fun setOnFilterObjectCallback(objectCallback: OnFilterObjectCallback) {
    onFilterObjectCallback = objectCallback
}

inner class ArrayFilter : Filter() {
    private var original: ArrayList<T> = arrayListOf()
    private var filter: SimpleAdapterFilter<T> = DefaultFilter()
    private var list: ArrayList<T> = arrayListOf()
    private var values: ArrayList<T> = arrayListOf()


    fun setFilter(filter: SimpleAdapterFilter<T>): ArrayFilter {
        original = items
        this.filter = filter
        return this
    }

    override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
        val results = Filter.FilterResults()
        if (constraint == null || constraint.isBlank()) {
            synchronized(lock) {
                list = original
            }
            results.values = list
            results.count = list.size
        } else {
            synchronized(lock) {
                values = original
            }
            val result = ArrayList<T>()
            for (value in values) {
                if (constraint!=null && constraint.trim().isNotEmpty() && value != null) {
                    if (filter.onFilterItem(constraint, value)) {
                        result.add(value)
                    }
                } else {
                    value?.let { result.add(it) }
                }
            }
            results.values = result
            results.count = result.size
        }
        return results
    }

    override fun publishResults(constraint: CharSequence, results: Filter.FilterResults) {
        items = results.values as? ArrayList<T> ?: arrayListOf()
        notifyDataSetChanged()
        onFilterObjectCallback?.handle(results.count)
    }

}

class DefaultFilter<T> : SimpleAdapterFilter<T> {
    override fun onFilterItem(contains: CharSequence, item: T): Boolean {
        val valueText = item.toString().toLowerCase()
        if (valueText.startsWith(contains.toString())) {
            return true
        } else {
            val words = valueText.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            for (word in words) {
                if (word.contains(contains)) {
                    return true
                }
            }
        }
        return false
    }
  }
}

And extend abstract adapter with implements methods

TasksAdapter.kt

import android.annotation.SuppressLint
  import kotlinx.android.synthetic.main.task_item_layout.view.*

class TasksAdapter(private val listener:TasksListener? = null) : SimpleAbstractAdapter<Task>() {
override fun getLayout(): Int {
    return R.layout.task_item_layout
}

override fun getDiffCallback(): DiffCallback<Task>? {
    return object : DiffCallback<Task>() {
        override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
            return oldItem.items == newItem.items
        }
    }
}

@SuppressLint("SetTextI18n")
override fun bindView(item: Task, viewHolder: VH) {
    viewHolder.itemView.apply {
        val position = viewHolder.adapterPosition
        val customer = item.customer
        val customerName = if (customer != null) customer.name else ""
        tvTaskCommentTitle.text = customerName + ", #" + item.id
        tvCommentContent.text = item.taskAddress
        ivCall.setOnClickListener {
            listener?.onCallClick(position, item)
        }
        setOnClickListener {
            listener?.onItemClick(position, item)
        }
    }
}

 interface TasksListener : SimpleAbstractAdapter.OnViewHolderListener<Task> {
    fun onCallClick(position: Int, item: Task)
 }
}

Init adapter

mAdapter = TasksAdapter(object : TasksAdapter.TasksListener {
            override fun onCallClick(position: Int, item:Task) {
            }

            override fun onItemClick(position: Int, item:Task) {

            }
        })
rvTasks.adapter = mAdapter

and fill

mAdapter?.addAll(tasks)

add custom filter

mAdapter?.setFilter(object : SimpleAbstractAdapter.SimpleAdapterFilter<MoveTask> {
            override fun onFilterItem(contains: CharSequence, item:Task): Boolean {
                return contains.toString().toLowerCase().contains(item.id?.toLowerCase().toString())
            }
    })

filter data

mAdapter?.filter("test")

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

Are HTTPS URLs encrypted?

Additionally, if you're building a ReSTful API, browser leakage and http referer issues are mostly mitigated as the client may not be a browser and you may not have people clicking links.

If this is the case I'd recommend oAuth2 login to obtain a bearer token. In which case the only sensitive data would be the initial credentials...which should probably be in a post request anyway

How to access to a child method from the parent in vue.js

You can use ref.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

Code of component.

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

Removing whitespace from strings in Java

Use mysz.replaceAll("\\s+","");

Concatenate two PySpark dataframes

To make it more generic of keeping both columns in df1 and df2:

import pyspark.sql.functions as F

# Keep all columns in either df1 or df2
def outter_union(df1, df2):

    # Add missing columns to df1
    left_df = df1
    for column in set(df2.columns) - set(df1.columns):
        left_df = left_df.withColumn(column, F.lit(None))

    # Add missing columns to df2
    right_df = df2
    for column in set(df1.columns) - set(df2.columns):
        right_df = right_df.withColumn(column, F.lit(None))

    # Make sure columns are ordered the same
    return left_df.union(right_df.select(left_df.columns))

How can I force WebKit to redraw/repaint to propagate style changes?

danorton solution didn't work for me. I had some really weird problems where webkit wouldn't draw some elements at all; where text in inputs wasn't updated until onblur; and changing className would not result in a redraw.

My solution, I accidentally discovered, was to add a empty style element to the body, after the script.

<body>
...
<script>doSomethingThatWebkitWillMessUp();</script>
<style></style>
...

That fixed it. How weird is that? Hope this is helpful for someone.

Find p-value (significance) in scikit-learn LinearRegression

You can use scipy for p-value. This code is from scipy documentation.

>>> from scipy import stats
>>> import numpy as np
>>> x = np.random.random(10)
>>> y = np.random.random(10)
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

here-document gives 'unexpected end of file' error

The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.

How to check file input size with jQuery?

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

What's the difference between a web site and a web application?

Websites are primarily informational. In this sense, http://cnn.com and http://php.net are websites, not web applications.

Web applications primarily allow the user to perform actions. Google Analytics, gmail, and jslint are web applications.

They are not entirely exclusive. A university website likely gives information such as location, tuition rates, programs available, etc; it will likely have web applications that allow teachers to manage grades and course materials, applications for students to register for and withdraw from courses, etc.

Efficiently getting all divisors of a given number

#include<bits/stdc++.h> 
using namespace std;
typedef long long int ll;
#define MOD 1000000007
#define fo(i,k,n) for(int i=k;i<=n;++i)
#define endl '\n'
ll etf[1000001];
ll spf[1000001];
void sieve(){
    ll i,j;
    for(i=0;i<=1000000;i++) {etf[i]=i;spf[i]=i;}
    for(i=2;i<=1000000;i++){
        if(etf[i]==i){
            for(j=i;j<=1000000;j+=i){
                etf[j]/=i;
                etf[j]*=(i-1);
                if(spf[j]==j)spf[j]=i;
            }
        }
    }
}
void primefacto(ll n,vector<pair<ll,ll>>& vec){
    ll lastprime = 1,k=0;
    while(n>1){
        if(lastprime!=spf[n])vec.push_back(make_pair(spf[n],0));
        vec[vec.size()-1].second++;
        lastprime=spf[n];
        n/=spf[n];
    }
}
void divisors(vector<pair<ll,ll>>& vec,ll idx,vector<ll>& divs,ll num){
    if(idx==vec.size()){
        divs.push_back(num);
        return;
    }
    for(ll i=0;i<=vec[idx].second;i++){
        divisors(vec,idx+1,divs,num*pow(vec[idx].first,i));
    }
}
void solve(){
    ll n;
    cin>>n;
    vector<pair<ll,ll>> vec;
    primefacto(n,vec);
    vector<ll> divs;
    divisors(vec,0,divs,1);
    for(auto it=divs.begin();it!=divs.end();it++){
        cout<<*it<<endl;
    }
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    sieve();
    ll t;cin>>t;
    while(t--) solve();
    return 0;
}

How can I kill a process by name instead of PID?

Kill all processes having snippet in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.

ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill

* I would preffer pgrep if available

How do I remove blank elements from an array?

Try this:

puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]

How to remove the first character of string in PHP?

Here is the code

$str = substr($str, 1); 

echo $str;

Output:

this is a applepie :)

Position one element relative to another in CSS

I would suggest using absolute positioning within the element.

I've created this to help you visualize it a bit.

_x000D_
_x000D_
#parent {_x000D_
    width:400px;_x000D_
    height:400px;_x000D_
    background-color:white;_x000D_
    border:2px solid blue;_x000D_
    position:relative;_x000D_
}_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
_x000D_
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/wUrdM/

Trim last character from a string

        string s1 = "Hello! world!";
        string s2 = s1.Trim('!');

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.

Redirect all to index.php using htaccess

Your rewrite rule looks almost ok.

First make sure that your .htaccess file is in your document root (the same place as index.php) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).

Next make a slight change to your rule so it looks something like:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

At the moment you're just matching on . which is one instance of any character, you need at least .* to match any number of instances of any character.

The $_GET['path'] variable will contain the fake directory structure, so /mvc/module/test for instance, which you can then use in index.php to determine the Controller and actions you want to perform.


If you want the whole shebang installed in a sub-directory, such as /mvc/ or /framework/ the least complicated way to do it is to change the rewrite rule slightly to take that into account.

RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]

And ensure that your index.php is in that folder whilst the .htaccess file is in the document root.


Alternative to $_GET['path'] (updated Feb '18 and Jan '19)

It's not actually necessary (nor even common now) to set the path as a $_GET variable, many frameworks will rely on $_SERVER['REQUEST_URI'] to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.

This does simplify the RewriteRule slightly as you don't need to create the path parameter (which means the OP's original RewriteRule will now work):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

However, the rule about installing in a sub-directory still applies, e.g.

RewriteRule ^.*$ /mvc/index.php [L,QSA]



The flags:

NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)

L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)

QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.

MySQL Workbench not displaying query results

The easiest fix for me to see the Result Grid again was to click on Explain Command

[enter image description here

After that Execution Plan is going to be shown and on the right side you can click on Result Grid

enter image description here

angularjs getting previous route path

Just to document:

The callback argument previousRoute is having a property called $route which is much similar to the $route service. Unfortunately currentRoute argument, is not having much information about the current route.

To overcome this i have tried some thing like this.

$routeProvider.
   when('/', {
    controller:...,
    templateUrl:'...',
    routeName:"Home"
  }).
  when('/menu', {
    controller:...,
    templateUrl:'...',
    routeName:"Site Menu"
  })

Please note that in the above routes config a custom property called routeName is added.

app.run(function($rootScope, $route){
    //Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to 
    //bind in induvidual controllers.
    $rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
        //This will give the custom property that we have defined while configuring the routes.
        console.log($route.current.routeName)
    })
})

How to get current date in jquery?

You can add an extension method to javascript.

Date.prototype.today = function () {
    return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

What is the best regular expression to check if a string is a valid URL?

Mathias Bynens has a great article on the best comparison of a lot of regular expressions: In search of the perfect URL validation regex

The best one posted is a little long, but it matches just about anything you can throw at it.

JavaScript version

/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i

PHP version

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$_iuS

How to find current transaction level?

Run this:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncommitted' 
WHEN 2 THEN 'ReadCommitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL 
FROM sys.dm_exec_sessions 
where session_id = @@SPID

docs.microsoft.com reference for the constant values.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/*Maximum value that can be entered is 2,147,483,647
 * Program to convert entered number into string
 * */
import java.util.Scanner;

public class NumberToWords 
{

public static void main(String[] args) 
{
    double num;//for taking input number
    Scanner obj=new Scanner(System.in);
    do
    {
        System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
        num=obj.nextDouble();
        if(num<=2147483647)//checking if entered number exceeds maximum integer value
        {
            int number=(int)num;//type casting double number to integer number
            splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
        }
        else
            System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
    }while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{   //splitNumber array-contains the numbers in pair of 3 digits
    int splitNumber[]=new int[4],temp=number,i=0,index;
    //splitting number into pair of 3
    if(temp==0)
        System.out.println("zero");
    while(temp!=0)
    {
        splitNumber[i++]=temp%1000;
        temp/=1000;
    }
    //passing each pair of 3 digits to another function
    for(int j=i-1;j>-1;j--)
    {   //toWords function will split pair of 3 digits to separate digits
        if(splitNumber[j]!=0)
            {toWords(splitNumber[j]);
        if(j==3)//if the number contained more than 9 digits
            System.out.print("billion,");
        else if(j==2)//if the number contained more than 6 digits & less than 10 digits
            System.out.print("million,");
        else if(j==1)
            System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
            }
            }       
}
//function that splits number into individual digits
public static void toWords(int number)
    //splitSmallNumber array contains individual digits of number passed to this function
{   int splitSmallNumber[]=new int[3],i=0,j;
    int temp=number;//making temporary copy of the number
    //logic to split number into its constituent digits

    while(temp!=0)
    {
        splitSmallNumber[i++]=temp%10;
        temp/=10;
    }
    //printing words for each digit
    for(j=i-1;j>-1;j--)
      //{   if the digit is greater than zero
        if(splitSmallNumber[j]>=0)
            //if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
        {   if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
            {
                switch(splitSmallNumber[j])
                {

                    case 1:System.out.print("one ");break;
                    case 2:System.out.print("two ");break;
                    case 3:System.out.print("three ");break;
                    case 4:System.out.print("four ");break;
                    case 5:System.out.print("five ");break;
                    case 6:System.out.print("six ");break;
                    case 7:System.out.print("seven ");break;
                    case 8:System.out.print("eight ");break;
                    case 9:System.out.print("nine ");break;

            }

        }
        //if digit is at 2nd place
        if(j==1)
        {       //if digit at 2nd place is 0 or 1
                if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
                System.out.print("hundred ");
            switch(splitSmallNumber[1])
            {   case 1://if digit at 2nd place is 1 example-213
                        switch(splitSmallNumber[0])
                        {
                        case 1:System.out.print("eleven ");break;
                        case 2:System.out.print("twelve ");break;
                        case 3:System.out.print("thirteen ");break;
                        case 4:System.out.print("fourteen ");break;
                        case 5:System.out.print("fifteen ");break;
                        case 6:System.out.print("sixteen ");break;
                        case 7:System.out.print("seventeen ");break;
                        case 8:System.out.print("eighteen ");break;
                        case 9:System.out.print("nineteen ");break;
                        case 0:System.out.print("ten ");break;
                        }break;
                        //if digit at 2nd place is not 1
                    case 2:System.out.print("twenty ");break;
                    case 3:System.out.print("thirty ");break;
                    case 4:System.out.print("forty ");break;
                    case 5:System.out.print("fifty ");break;
                    case 6:System.out.print("sixty ");break;
                    case 7:System.out.print("seventy ");break;
                    case 8:System.out.print("eighty ");break;
                    case 9:System.out.print("ninety ");break;
                    //case 0:   System.out.println("hundred ");break;

            }                           
        }           
    }
  }

}

Open fancybox from function

If you'd like to simply open a fancybox when a javascript function is called. Perhaps in your code flow and not as a result of a click. Here's how you do it:

function openFancybox() {
  $.fancybox({
     'autoScale': true,
     'transitionIn': 'elastic',
     'transitionOut': 'elastic',
     'speedIn': 500,
     'speedOut': 300,
     'autoDimensions': true,
     'centerOnScroll': true,
     'href' : '#contentdiv'
  });
}

This creates the box using "contentdiv" and opens it.

Bootstrap combining rows (rowspan)

Note: This was for Bootstrap 2 (relevant when the question was asked).

You can accomplish this by using row-fluid to make a fluid (percentage) based row inside an existing block.

<div class="row">
   <div class="span5">span5</div>
   <div class="span3">span3</div>
   <div class="span2">
      <div class="row-fluid">
         <div class="span12">span2</div>
         <div class="span12">span2</div>
      </div>
   </div>
   <div class="span2">span2</div>
</div>
<div class="row">
   <div class="span6">
      <div class="row-fluid">
         <div class="span12">span6</div>
         <div class="span12">span6</div>
      </div>
   </div>
   <div class="span6">span6</div>
</div>

Here's a JSFiddle example.

I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):

.row-fluid [class*="span"] {
    margin-left: 0;
}

How can I check whether Google Maps is fully loaded?

Where the variable map is an object of type GMap2:

    GEvent.addListener(map, "tilesloaded", function() {
      console.log("Map is fully loaded");
    });

Getting a File's MD5 Checksum in Java

Use DigestUtils from Apache Commons Codec library:

try (InputStream is = Files.newInputStream(Paths.get("file.zip"))) {
    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
}

Windows- Pyinstaller Error "failed to execute script " When App Clicked

Well I guess I have found the solution for my own question, here is how I did it:

Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.

So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.

The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!

How to retrieve all keys (or values) from a std::map and put them into a vector?

With the structured binding (“destructuring”) declaration syntax of C++17,

you can do this, which is easier to understand.

// To get the keys
std::map<int, double> map;
std::vector<int> keys;
keys.reserve(map.size());
for(const auto& [key, value] : map) {
    keys.push_back(key);
}
// To get the values
std::map<int, double> map;
std::vector<double> values;
values.reserve(map.size());
for(const auto& [key, value] : map) {
    values.push_back(value);
}

A CORS POST request works from plain JavaScript, but why not with jQuery?

You are sending "params" in js: request.send(params);

but "data" in jquery". Is data defined?: data:data,

Also, you have an error in the URL:

$.ajax( {url:url,
         type:"POST",
         dataType:"json",
         data:data, 
         success:function(data, textStatus, jqXHR) {alert("success");},
         error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
});

You are mixing the syntax with the one for $.post


Update: I was googling around based on monsur answer, and I found that you need to add Access-Control-Allow-Headers: Content-Type (below is the full paragraph)

http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/

How CORS Works

CORS works very similarly to Flash's crossdomain.xml file. Basically, the browser will send a cross-domain request to a service, setting the HTTP header Origin to the requesting server. The service includes a few headers like Access-Control-Allow-Origin to indicate whether such a request is allowed.

For the BOSH connection managers, it is enough to specify that all origins are allowed, by setting the value of Access-Control-Allow-Origin to *. The Content-Type header must also be white-listed in the Access-Control-Allow-Headers header.

Finally, for certain types of requests, including BOSH connection manager requests, the permissions check will be pre-flighted. The browser will do an OPTIONS request and expect to get back some HTTP headers that indicate which origins are allowed, which methods are allowed, and how long this authorization will last. For example, here is what the Punjab and ejabberd patches I did return for OPTIONS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type 
Access-Control-Max-Age: 86400

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Select Multiple Fields from List in Linq

Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:

var cats = listObject
    .Select(i => new { i.category_id, i.category_name })
    .Distinct()
    .OrderByDescending(i => i.category_name)
    .ToArray();

Since you (apparently) need to store it for later use, you could use the GroupBy operator:

Data[] cats = listObject
    .GroupBy(i => new { i.category_id, i.category_name })
    .OrderByDescending(g => g.Key.category_name)
    .Select(g => g.First())
    .ToArray();

Is it possible to declare two variables of different types in a for loop?

Not possible, but you can do:

float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
  //...
}

Or, explicitly limit the scope of f and i using additional brackets:

{
    float f; 
    int i;
    for (i = 0,f = 0.0; i < 5; i++)
    {
       //...
    }
}

JVM heap parameters

Apart from standard Heap parameters -Xms and -Xmx it's also good to know -XX:PermSize and -XX:MaxPermSize, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

How to stop a goroutine

I know this answer has already been accepted, but I thought I'd throw my 2cents in. I like to use the tomb package. It's basically a suped up quit channel, but it does nice things like pass back any errors as well. The routine under control still has the responsibility of checking for remote kill signals. Afaik it's not possible to get an "id" of a goroutine and kill it if it's misbehaving (ie: stuck in an infinite loop).

Here's a simple example which I tested:

package main

import (
  "launchpad.net/tomb"
  "time"
  "fmt"
)

type Proc struct {
  Tomb tomb.Tomb
}

func (proc *Proc) Exec() {
  defer proc.Tomb.Done() // Must call only once
  for {
    select {
    case <-proc.Tomb.Dying():
      return
    default:
      time.Sleep(300 * time.Millisecond)
      fmt.Println("Loop the loop")
    }
  }
}

func main() {
  proc := &Proc{}
  go proc.Exec()
  time.Sleep(1 * time.Second)
  proc.Tomb.Kill(fmt.Errorf("Death from above"))
  err := proc.Tomb.Wait() // Will return the error that killed the proc
  fmt.Println(err)
}

The output should look like:

# Loop the loop
# Loop the loop
# Loop the loop
# Loop the loop
# Death from above

How to use Fiddler to monitor WCF service

So simple, all you need is to change the address in the config client: instead of 'localhost' change to the machine name or IP

How to label each equation in align environment?

Within the environment align from the package amsmath it is possible to combine the use of \label and \tag for each equation or line. For example, the code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}

produces:

screenshot of output

How to display activity indicator in middle of the iphone screen?

If you want to center the spinner using AutoLayout, do:

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[activityView startAnimating];
[self.view addSubview:activityView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterX
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterX
                                                     multiplier:1.0
                                                       constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterY
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterY
                                                     multiplier:1.0
                                                       constant:0.0]];

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

pop/remove items out of a python tuple

Maybe you want dictionaries?

d = dict( (i,value) for i,value in enumerate(tple))
while d:
    bla bla bla
    del b[x]

SQL query question: SELECT ... NOT IN

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null

Make sure your list parameter does not contain null values.

Here's an explanation:

WHERE field1 NOT IN (1, 2, 3, null)

is the same as:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • That last comparision evaluates to null.
  • That null is OR'd with the rest of the boolean expression, yielding null. (*)
  • null is negated, yielding null.
  • null is not true - the where clause only keeps true rows, so all rows are filtered.

(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.

Android - styling seek bar

You can also make it this way :

<SeekBar
    android:id="@+id/redSeekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:progressDrawable="@color/red"
    android:maxHeight="3dip"/>

Hope it will help!

Difference between a View's Padding and Margin

In simple words:
padding changes the size of the box (with something).
margin changes the space between different boxes

Export DataTable to Excel with Open Xml SDK in c#

I also wrote a C#/VB.Net "Export to Excel" library, which uses OpenXML and (more importantly) also uses OpenXmlWriter, so you won't run out of memory when writing large files.

Full source code, and a demo, can be downloaded here:

Export to Excel

It's dead easy to use. Just pass it the filename you want to write to, and a DataTable, DataSet or List<>.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

And if you're calling it from an ASP.Net application, pass it the HttpResponse to write the file out to.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

Authentication failed because remote party has closed the transport stream

If you want to use an older version of .net, create your own flag and cast it.

    //
    // Summary:
    //     Specifies the security protocols that are supported by the Schannel security
    //     package.
    [Flags]
    private enum MySecurityProtocolType
    {
        //
        // Summary:
        //     Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
        Ssl3 = 48,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.0 security protocol.
        Tls = 192,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.1 security protocol.
        Tls11 = 768,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.2 security protocol.
        Tls12 = 3072
    }
    public Session()
    {
        System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
    }

Moving average or running mean

or module for python that calculates

in my tests at Tradewave.net TA-lib always wins:

import talib as ta
import numpy as np
import pandas as pd
import scipy
from scipy import signal
import time as t

PAIR = info.primary_pair
PERIOD = 30

def initialize():
    storage.reset()
    storage.elapsed = storage.get('elapsed', [0,0,0,0,0,0])

def cumsum_sma(array, period):
    ret = np.cumsum(array, dtype=float)
    ret[period:] = ret[period:] - ret[:-period]
    return ret[period - 1:] / period

def pandas_sma(array, period):
    return pd.rolling_mean(array, period)

def api_sma(array, period):
    # this method is native to Tradewave and does NOT return an array
    return (data[PAIR].ma(PERIOD))

def talib_sma(array, period):
    return ta.MA(array, period)

def convolve_sma(array, period):
    return np.convolve(array, np.ones((period,))/period, mode='valid')

def fftconvolve_sma(array, period):    
    return scipy.signal.fftconvolve(
        array, np.ones((period,))/period, mode='valid')    

def tick():

    close = data[PAIR].warmup_period('close')

    t1 = t.time()
    sma_api = api_sma(close, PERIOD)
    t2 = t.time()
    sma_cumsum = cumsum_sma(close, PERIOD)
    t3 = t.time()
    sma_pandas = pandas_sma(close, PERIOD)
    t4 = t.time()
    sma_talib = talib_sma(close, PERIOD)
    t5 = t.time()
    sma_convolve = convolve_sma(close, PERIOD)
    t6 = t.time()
    sma_fftconvolve = fftconvolve_sma(close, PERIOD)
    t7 = t.time()

    storage.elapsed[-1] = storage.elapsed[-1] + t2-t1
    storage.elapsed[-2] = storage.elapsed[-2] + t3-t2
    storage.elapsed[-3] = storage.elapsed[-3] + t4-t3
    storage.elapsed[-4] = storage.elapsed[-4] + t5-t4
    storage.elapsed[-5] = storage.elapsed[-5] + t6-t5    
    storage.elapsed[-6] = storage.elapsed[-6] + t7-t6        

    plot('sma_api', sma_api)  
    plot('sma_cumsum', sma_cumsum[-5])
    plot('sma_pandas', sma_pandas[-10])
    plot('sma_talib', sma_talib[-15])
    plot('sma_convolve', sma_convolve[-20])    
    plot('sma_fftconvolve', sma_fftconvolve[-25])

def stop():

    log('ticks....: %s' % info.max_ticks)

    log('api......: %.5f' % storage.elapsed[-1])
    log('cumsum...: %.5f' % storage.elapsed[-2])
    log('pandas...: %.5f' % storage.elapsed[-3])
    log('talib....: %.5f' % storage.elapsed[-4])
    log('convolve.: %.5f' % storage.elapsed[-5])    
    log('fft......: %.5f' % storage.elapsed[-6])

results:

[2015-01-31 23:00:00] ticks....: 744
[2015-01-31 23:00:00] api......: 0.16445
[2015-01-31 23:00:00] cumsum...: 0.03189
[2015-01-31 23:00:00] pandas...: 0.03677
[2015-01-31 23:00:00] talib....: 0.00700  # <<< Winner!
[2015-01-31 23:00:00] convolve.: 0.04871
[2015-01-31 23:00:00] fft......: 0.22306

enter image description here

Convert time.Time to string

Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

package main


// Import Package
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}

How to get multiple select box values using jQuery?

Just use this

$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();  
});

Converting from hex to string

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

Under which circumstances textAlign property works in Flutter?

Set alignment: Alignment.centerRight in Container:

Container(
    alignment: Alignment.centerRight,
    child:Text(
       "Hello",
    ),
)

How to dynamically insert a <script> tag via jQuery after page load?

If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.

If the script is static, then Rocket's getScript-suggestion is the way to go.

dropping infinite values from dataframes in pandas?

The above solution will modify the infs that are not in the target columns. To remedy that,

lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)

C - Convert an uppercase letter to lowercase

I believe you want <= 90

lower(a) 
int a; 
{
    if ((a >= 65) && (a <= 90))
        a = a + 32; 
    return a;  
}

Although tolower would probably just save you the hassle unless you wanted to do this yourself. http://www.cplusplus.com/reference/cctype/tolower/

How to reverse an animation on mouse out after hover

creating a reversed animation is kinda an overkill to a simple problem, what u need is

animation-direction: reverse

however this wont work on its own because animation spec is so dump that they forgot to add a way to restart the animation so here is how you do it with the help of js

_x000D_
_x000D_
let item = document.querySelector('.item')_x000D_
_x000D_
// play normal_x000D_
item.addEventListener('mouseover', () => {_x000D_
  item.classList.add('active')_x000D_
})_x000D_
_x000D_
// play in reverse_x000D_
item.addEventListener('mouseout', () => {_x000D_
  item.style.opacity = 0 // avoid showing the init style while switching the 'active' class_x000D_
_x000D_
  item.classList.add('in-active')_x000D_
  item.classList.remove('active')_x000D_
_x000D_
  // force dom update_x000D_
  setTimeout(() => {_x000D_
    item.classList.add('active')_x000D_
    item.style.opacity = ''_x000D_
  }, 5)_x000D_
_x000D_
  item.addEventListener('animationend', onanimationend)_x000D_
})_x000D_
_x000D_
function onanimationend() {_x000D_
  item.classList.remove('active', 'in-active')_x000D_
  item.removeEventListener('animationend', onanimationend)_x000D_
}
_x000D_
@keyframes spin {_x000D_
  0% {_x000D_
    transform: rotateY(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotateY(180deg);_x000D_
  }_x000D_
}_x000D_
_x000D_
div {_x000D_
  background: black;_x000D_
  padding: 1rem;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  /* because span cant be animated */_x000D_
  display: block;_x000D_
  color: yellow;_x000D_
  font-size: 2rem;_x000D_
}_x000D_
_x000D_
.item.active {_x000D_
  animation: spin 1s forwards;_x000D_
  animation-timing-function: ease-in-out;_x000D_
}_x000D_
_x000D_
.item.in-active {_x000D_
  animation-direction: reverse;_x000D_
}
_x000D_
<div>_x000D_
  <span class="item">ABC</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between Promises and Observables?

Overview:

  • Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.
  • A Promise can only handle one event, Observables are for streams of events over time
  • Promises can't be cancelled once they are pending
  • Data Observables emit can be transformed using operators

You can always use an observable for dealing with asynchronous behaviour since an observable has the all functionality which a promise offers (+ extra). However, sometimes this extra functionality that Observables offer is not needed. Then it would be extra overhead to import a library for it to use them.

When to use Promises:

Use promises when you have a single async operation of which you want to process the result. For example:

var promise = new Promise((resolve, reject) => {
  // do something once, possibly async
  // code inside the Promise constructor callback is getting executed synchronously

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//after the promise is resolved or rejected we can call .then or .catch method on it

promise.then((val) => console.log(val))      // logs the resolve argument
       .catch((val) => console.log(val));    // logs the reject argument

So a promise executes some code where it either resolves or rejects. If either resolve or reject is called the promise goes from a pending state to either a resolved or rejected state. When the promise state is resolved the then() method is called. When the promise state is rejected, the catch() method is called.

When to use Observables:

Use Observables when there is a stream (of data) over time which you need to be handled. A stream is a sequence of data elements which are being made available over time. Examples of streams are:

  1. User events, e.g. click, or keyup events. The user generates events (data) over time.
  2. Websockets, after the client makes a WebSocket connection to the server it pushes data over time.

In the Observable itself is specified when the next event happened, when an error occurs, or when the Observable is completed. Then we can subscribe to this observable, which activates it and in this subscription, we can pass in 3 callbacks (don't always have to pass in all). One callback to be executed for success, one callback for error, and one callback for completion. For example:

const observable = Rx.Observable.create(observer => {
  // create a single value and complete
  observer.onNext(1);
  observer.onCompleted();
});

source.subscribe(
  x => console.log('onNext: %s', x),   //  success callback
  e => console.log('onError: %s', e),  //  error callback
  () => console.log('onCompleted')     //  completion callback
 );

// first we log: onNext: 1
//  then we log: onCompleted

When creating an observable it requires a callback function which supplies an observer as an argument. On this observer, you then can call onNext, onCompleted, onError. Then when the Observable is subscribed to it will call the corresponding callbacks passed into the subscription.

Android checkbox style

In the previous answer also in the section <selector>...</selector> you may need:

<item android:state_pressed="true" android:drawable="@drawable/checkbox_pressed" ></item>

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

How to compare oldValues and newValues on React Hooks useEffect?

Using Ref will introduce a new kind of bug into the app.

Let's see this case using usePrevious that someone commented before:

  1. prop.minTime: 5 ==> ref.current = 5 | set ref.current
  2. prop.minTime: 5 ==> ref.current = 5 | new value is equal to ref.current
  3. prop.minTime: 8 ==> ref.current = 5 | new value is NOT equal to ref.current
  4. prop.minTime: 5 ==> ref.current = 5 | new value is equal to ref.current

As we can see here, we are not updating the internal ref because we are using useEffect

getting error while updating Composer

Problem :

Problem 1
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework (locked at v5.8.38, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.38].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Solution :

if you using xampp just remove ' ; ' from

;extension=mbstring

in php.ini , save it, done!

C++ getters/setters coding style

Collected ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:

class Canvas { public:
    void resize() {
        cout << "resize to " << width << " " << height << endl;
    }

    Canvas(int w, int h) : width(*this), height(*this) {
        cout << "new canvas " << w << " " << h << endl;
        width.value = w;
        height.value = h;
    }

    class Width { public:
        Canvas& canvas;
        int value;
        Width(Canvas& canvas): canvas(canvas) {}
        int & operator = (const int &i) {
            value = i;
            canvas.resize();
            return value;
        }
        operator int () const {
            return value;
        }
    } width;

    class Height { public:
        Canvas& canvas;
        int value;
        Height(Canvas& canvas): canvas(canvas) {}
        int & operator = (const int &i) {
            value = i;
            canvas.resize();
            return value;
        }
        operator int () const {
            return value;
        }
    } height;
};

int main() {
    Canvas canvas(256, 256);
    canvas.width = 128;
    canvas.height = 64;
}

Output:

new canvas 256 256
resize to 128 256
resize to 128 64

You can test it online here: http://codepad.org/zosxqjTX

PS: FO Yvette <3

How to disable RecyclerView scrolling?

Override onTouchEvent() and onInterceptTouchEvent() and return false if you don't need OnItemTouchListener at all. This does not disable OnClickListeners of ViewHolders.

public class ScrollDisabledRecyclerView extends RecyclerView {
    public ScrollDisabledRecyclerView(Context context) {
        super(context);
    }

    public ScrollDisabledRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollDisabledRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return false;
    }
}

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How to use Monitor (DDMS) tool to debug application

I think things (location) have changed little bit. For: Android Studio 1.2.1.1 Build @AI-141.1903250 - built on May 5, 2015

Franco Rondinis answer should be

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. Select your device from the dropdown list.
  4. Select your app by its package name from the list of running apps.
  5. On the Android DDMS tool window, select Memory tab.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking (same icon)

how to start allocation tracking in android studio 1.2.1.1

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I have tried methods mentioned above, restarting the AS didn't work for me, and rebuilding didn't work either. Finally I found the problem was with the .9.png files, I deleted them and rebuilt the project, and it worked fine! Try it.

How to use glyphicons in bootstrap 3.0

Download all files from bootstrap and then include this css

<style type="text/css">
        @font-face {
            font-family: 'Glyphicons Halflings';
            src: url('/fonts/glyphicons-halflings-regular.eot');
        }
 </style>

Can I fade in a background image (CSS: background-image) with jQuery?

You can give opacity value as

div {opacity: 0.4;}

For IE, you can specify as

div { filter:alpha(opacity=10));}

Lower the value - Higher the transparency.

No connection could be made because the target machine actively refused it?

I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx

I implemented this function almost exactly as written, but what happened is I got this error:

2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080

This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)

private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        // Get host related information.
        hostEntry = Dns.GetHostEntry(server);

        // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
        // an exception that occurs when the host IP Address is not compatible with the address family
        // (typical in the IPv6 case).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!

    private Socket ConnectSocket(string server, int port)
    {
        Socket s = null;

        try
        {
            // Get host related information.
            IPAddress[] ips;
            ips = Dns.GetHostAddresses(server);

            Socket tempSocket = null;
            IPEndPoint ipe = null;

            ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
            tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
            tempSocket.Connect(ipe);

            if (tempSocket.Connected)
            {
                s = tempSocket;
                s.SendTimeout = Coordinate.HL7SendTimeout;
                s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
            }
            else
            {
                return null;
            }

            return s;
        }
        catch (Exception e)
        {
            Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
            Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
            if (g_NoOutputForThreading == false)
                rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
            return null;
        }
    }

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Hash table in JavaScript

Using the function above, you would do:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

Of course, the following would also work:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object) would also get you all its functions, etc., but that might be enough depending on your needs.

Export table data from one SQL Server to another

Try this:

  1. create your table on the target server using your scripts from the Script Table As / Create Script step

  2. on the target server, you can then issue a T-SQL statement:

    INSERT INTO dbo.YourTableNameHere
       SELECT *
       FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere
    

This should work just fine.

How to set margin of ImageView using code, not xml

For me this worked:

int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());

MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);

Prevent text selection after double click

To prevent IE 8 CTRL and SHIFT click text selection on individual element

var obj = document.createElement("DIV");
obj.onselectstart = function(){
  return false;
}

To prevent text selection on document

window.onload = function(){
  document.onselectstart = function(){
    return false;
  }
}

Why is it important to override GetHashCode when Equals method is overridden?

Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

The GetHashCode() method should reflect the Equals logic; the rules are:

  • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
  • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

In this case, it looks like "return FooId;" is a suitable GetHashCode() implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5) has a different hash-code to new Foo(5,3)):

unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
    int hash = 13;
    hash = (hash * 7) + field1.GetHashCode();
    hash = (hash * 7) + field2.GetHashCode();
    ...
    return hash;
}

Oh - for convenience, you might also consider providing == and != operators when overriding Equals and GetHashCode.


A demonstration of what happens when you get this wrong is here.

Hiding button using jQuery

You can use the .hide() function bound to a click handler:

$('#Comanda').click(function() {
    $(this).hide();
});

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

*ngIf else if in template

To avoid nesting and ngSwitch, there is also this possibility, which leverages the way logical operators work in Javascript:

<ng-container *ngIf="foo === 1; then first; else (foo === 2 && second) || (foo === 3 && third)"></ng-container>
  <ng-template #first>First</ng-template>
  <ng-template #second>Second</ng-template>
  <ng-template #third>Third</ng-template>

Remove scrollbar from iframe

Add this in your css to hide both scroll bar

iframe 
{
  overflow-x:hidden;
  overflow-Y:hidden;
}

function to remove duplicate characters in a string

public class StringRedundantChars {
    /**
     * @param args
     */
    public static void main(String[] args) {

        //initializing the string to be sorted
        String sent = "I love painting and badminton";

        //Translating the sentence into an array of characters
        char[] chars = sent.toCharArray();

        System.out.println("Before Sorting");
        showLetters(chars);

        //Sorting the characters based on the ASCI character code. 
        java.util.Arrays.sort(chars);

        System.out.println("Post Sorting");
        showLetters(chars);

        System.out.println("Removing Duplicates");
        stripDuplicateLetters(chars);

        System.out.println("Post Removing Duplicates");
        //Sorting to collect all unique characters 
        java.util.Arrays.sort(chars);
        showLetters(chars);

    }

    /**
     * This function prints all valid characters in a given array, except empty values
     * 
     * @param chars Input set of characters to be displayed
     */
    private static void showLetters(char[] chars) {

        int i = 0;
        //The following loop is to ignore all white spaces
        while ('\0' == chars[i]) {
            i++;
        }
        for (; i < chars.length; i++) {
            System.out.print(" " + chars[i]);
        }
        System.out.println();
    }

    private static char[] stripDuplicateLetters(char[] chars) {

        // Basic cursor that is used to traverse through the unique-characters
        int cursor = 0;
        // Probe which is used to traverse the string for redundant characters
        int probe = 1;

        for (; cursor < chars.length - 1;) {

            // Checking if the cursor and probe indices contain the same
            // characters
            if (chars[cursor] == chars[probe]) {
                System.out.println("Removing char : " + chars[probe]);
                // Please feel free to replace the redundant character with
                // character. I have used '\0'
                chars[probe] = '\0';
                // Pushing the probe to the next character
                probe++;
            } else {
                // Since the probe has traversed the chars from cursor it means
                // that there were no unique characters till probe.
                // Hence set cursor to the probe value
                cursor = probe;
                // Push the probe to refer to the next character
                probe++;
            }
        }
        System.out.println();

        return chars;
    }
}

Regex for parsing directory and filename

What about this?

[/]{0,1}([^/]+[/])*([^/]*)

Deterministic :

((/)|())([^/]+/)*([^/]*)

Strict :

^[/]{0,1}([^/]+[/])*([^/]*)$
^((/)|())([^/]+/)*([^/]*)$

Can't get Gulp to run: cannot find module 'gulp-util'

Any answer didn't help in my case. What eventually helped was removing bower and gulp (I use both of them in my project):

npm remove -g bower
npm remove -g gulp

After that I installed them again:

npm install -g bower
npm install -g gulp

Now it works just fine.

Converting between datetime, Timestamp and datetime64

To convert numpy.datetime64 to datetime object that represents time in UTC on numpy-1.8:

>>> from datetime import datetime
>>> import numpy as np
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> dt64 = np.datetime64(dt)
>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
>>> ts
1354650685.3624549
>>> datetime.utcfromtimestamp(ts)
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> np.__version__
'1.8.0.dev-7b75899'

The above example assumes that a naive datetime object is interpreted by np.datetime64 as time in UTC.


To convert datetime to np.datetime64 and back (numpy-1.6):

>>> np.datetime64(datetime.utcnow()).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)

It works both on a single np.datetime64 object and a numpy array of np.datetime64.

Think of np.datetime64 the same way you would about np.int8, np.int16, etc and apply the same methods to convert beetween Python objects such as int, datetime and corresponding numpy objects.

Your "nasty example" works correctly:

>>> from datetime import datetime
>>> import numpy 
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__
'1.6.2' # current version available via pip install numpy

I can reproduce the long value on numpy-1.8.0 installed as:

pip install git+https://github.com/numpy/numpy.git#egg=numpy-dev

The same example:

>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
1025222400000000000L
>>> numpy.__version__
'1.8.0.dev-7b75899'

It returns long because for numpy.datetime64 type .astype(datetime) is equivalent to .astype(object) that returns Python integer (long) on numpy-1.8.

To get datetime object you could:

>>> dt64.dtype
dtype('<M8[ns]')
>>> ns = 1e-9 # number of seconds in a nanosecond
>>> datetime.utcfromtimestamp(dt64.astype(int) * ns)
datetime.datetime(2002, 6, 28, 0, 0)

To get datetime64 that uses seconds directly:

>>> dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
>>> dt64.dtype
dtype('<M8[s]')
>>> datetime.utcfromtimestamp(dt64.astype(int))
datetime.datetime(2002, 6, 28, 0, 0)

The numpy docs say that the datetime API is experimental and may change in future numpy versions.

Write single CSV file using spark-csv

There is one more way to use Java

import java.io._

def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) 
  {
     val p = new java.io.PrintWriter(f);  
     try { op(p) } 
     finally { p.close() }
  } 

printToFile(new File("C:/TEMP/df.csv")) { p => df.collect().foreach(p.println)}

What does href expression <a href="javascript:;"></a> do?

An <a> element is invalid HTML unless it has either an href or name attribute.

If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.

Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.

He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.

Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).

There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.

phonegap open link in browser

As answered in other posts, you have two different options for different platforms. What I do is:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

    // Mock device.platform property if not available
    if (!window.device) {
        window.device = { platform: 'Browser' };
    }

    handleExternalURLs();
}

function handleExternalURLs() {
    // Handle click events for all external URLs
    if (device.platform.toUpperCase() === 'ANDROID') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            navigator.app.loadUrl(url, { openExternal: true });
            e.preventDefault();
        });
    }
    else if (device.platform.toUpperCase() === 'IOS') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            window.open(url, '_system');
            e.preventDefault();
        });
    }
    else {
        // Leave standard behaviour
    }
}

So as you can see I am checking the device platform and depending on that I am using a different method. In case of a standard browser, I leave standard behaviour. From now on the solution will work fine on Android, iOS and in a browser, while HTML page won't be changed, so that it can have URLs represented as standard anchor

<a href="http://stackoverflow.com">

The solution requires InAppBrowser and Device plugins

What determines the monitor my app runs on?

Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.

Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.

To figure out how big the display really is, check out GetSystemMetrics.

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

Only numbers. Input number in React

Maybe, it will be helpful for someone
Recently I used this solution for my App
I am not sure that is a correct solution but it works fine.

this.state = {
    inputValue: "",
    isInputNotValid: false
}

handleInputValue = (evt) => {
    this.validationField(evt, "isInputNotValid", "inputValue");
}

validationField = (evt, isFieldNotValid, fieldValue ) => {
   if (evt.target.value && !isNaN(evt.target.value)) {
        this.setState({ 
            [isFieldNotValid]: false,
            [fieldValue]: evt.target.value,
        });
    } else {
        this.setState({ 
            [isFieldNotValid]: true,
            [fieldValue]: "",
        });
    }
}

<input className={this.state.isInputNotValid ? "error" : null} type="text" onChange="this.handleInputValue" />

The main idea, that state won't update till the condition isn't true and value will be empty.
Don't need to use onKeyPress, Down etc.,
also if you use these methods they aren't working on touch devices

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Error during SSL Handshake with remote server

I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.

So, I had to generate the SSL certificate again and it started working...

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

Laravel Eloquent inner join with multiple conditions

return $query->join('kg_shops', function($join)
 {
   $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');

 })
 ->select('required column names') 
 ->where('kg_shops.active', 1)
 ->get();

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

# -*- coding: utf-8 -*-
print( bytes('ò') )

This is the way of Python 2.7 when dealing with unicode chars.

This won't work with Python 3.6, since bytes require an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'

In my case I had to use iso_8859_1 when encoding bytes in order to solve the issue.

Hope this helps someone.

How to increase request timeout in IIS?

In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

Function is not defined - uncaught referenceerror

Clearing Cache solved the issue for me or you can open it in another browser

index.js

function myFun() {
    $('h2').html("H999999");
}

index.jsp

<html>
<head>
    <title>Reader</title>
</head>
<body>
<h2>${message}</h2>
<button id="hi" onclick="myFun();" type="submit">Hi</button>
</body>
</html>

Make a nav bar stick

/* Add css in your style */


.sticky-header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    border-top: 0;
    transition: 0.3s;
}


/* and use this javascript code: */

$(document).ready(function() {

  $(window).scroll(function () {
    if ($(window).scrollTop() > ) {
      $('.headercss').addClass('sticky-header');
    } else{
      $('.headercss').removeClass('sticky-header');
    }
  });
});

Multi-key dictionary in c#?

Could you use a Dictionary<TKey1,Dictionary<TKey2,TValue>>?

You could even subclass this:

public class DualKeyDictionary<TKey1,TKey2,TValue> : Dictionary<TKey1,Dictionary<TKey2,TValue>>

EDIT: This is now a duplicate answer. It also is limited in its practicality. While it does "work" and provide ability to code dict[key1][key2], there are lots of "workarounds" to get it to "just work".

HOWEVER: Just for kicks, one could implement Dictionary nonetheless, but at this point it gets a little verbose:

public class DualKeyDictionary<TKey1, TKey2, TValue> : Dictionary<TKey1, Dictionary<TKey2, TValue>> , IDictionary< object[], TValue >
{
    #region IDictionary<object[],TValue> Members

    void IDictionary<object[], TValue>.Add( object[] key, TValue value )
    {
        if ( key == null || key.Length != 2 )
            throw new ArgumentException( "Invalid Key" );

        TKey1 key1 = key[0] as TKey1;
        TKey2 key2 = key[1] as TKey2;

        if ( !ContainsKey( key1 ) )
            Add( key1, new Dictionary<TKey2, TValue>() );

        this[key1][key2] = value;
    }

    bool IDictionary<object[], TValue>.ContainsKey( object[] key )
    {
        if ( key == null || key.Length != 2 )
            throw new ArgumentException( "Invalid Key" );

        TKey1 key1 = key[0] as TKey1;
        TKey2 key2 = key[1] as TKey2;

        if ( !ContainsKey( key1 ) )
            return false;

        if ( !this[key1].ContainsKey( key2 ) )
            return false;

        return true;
    }

Capturing window.onbeforeunload

Yes what everybody says above.

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.

Retrieving Dictionary Value Best Practices

Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

Edit:

Ok, I understand your confusion so let me elaborate:

Case 1:

if (myDict.Contains(someKey))
     someVal = myDict[someKey];

In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it

Case 2:

myDict.TryGetValue(somekey, out someVal)

In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.

Save string to the NSUserDefaults?

In Swift5 and Xcode 10.2

//Save
UserDefaults.standard.set(true, forKey: "Key1") //Bool
UserDefaults.standard.set(1, forKey: "Key2")  //Integer
UserDefaults.standard.set("This is my string", forKey: "Key3") //String
UserDefaults.standard.synchronize()

//Retrive
UserDefaults.standard.bool(forKey: "Key1")
UserDefaults.standard.integer(forKey: "Key2")
UserDefaults.standard.string(forKey: "Key3")

//Remove
UserDefaults.standard.removeObject(forKey: "Key3")

Note: Save text data(means String, Array, Dictionary etc.) in UserDefaults. Don't save images in UserDefaults, it's not recommended(Save images in local directory).

Removing page title and date when printing web page (with CSS?)

There's a facility to have a separate style sheet for print, using

 <link type="text/css" rel="stylesheet" media="print" href="print.css">

I don't know if it does what you want though.

How to group an array of objects by key

With lodash/fp you can create a function with _.flow() that 1st groups by a key, and then map each group, and omits a key from each item:

_x000D_
_x000D_
const { flow, groupBy, mapValues, map, omit } = _;_x000D_
_x000D_
const groupAndOmitBy = key => flow(_x000D_
  groupBy(key),_x000D_
  mapValues(map(omit(key)))_x000D_
);_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
const groupAndOmitMake = groupAndOmitBy('make');_x000D_
_x000D_
const result = groupAndOmitMake(cars);_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
_x000D_
_x000D_
_x000D_

How do I simulate a low bandwidth, high latency environment?

Take a look at the NE-ONE Network Emulator which allows you to configure bandwidth, latency, packet loss, packet reordering, packet duplication, packet fragmentation, network congestion and many more impairments so that you can create real-world network conditions in the lab. Different impairments can be configured for the up and downlink so you could have a really good uplink but a really bad downlink experience, great for seeing how the app handles TCP queuing because the acks don't come back in a timely manner and the overall latency therefore increases!

There's an overview video here http://www.youtube.com/watch?v=DwtqlE7LcrQ specifically aimed at game developers, but it shows what it's about. NE-ONE is configured using a web browser so it's really easy to get installed and configured - you don't need to be a network guru :-)

There's a hardware version - http://www.itrinegy.com/index.php/products/network-emulators/ne-one - or you can download a Virtual Appliance (software) version that runs under VMware ESXi Server. The Virtual Appliance can be download from VMware's Solution Exchange - solutionexchange.vmware.com/store/products/ne-one-flex-network-emulator

Jackson serialization: ignore empty values (or null)

Or you can use GSON [https://code.google.com/p/google-gson/], where these null fields will be automatically removed.

SampleDTO.java

public class SampleDTO {

    String username;
    String email;
    String password;
    String birthday;
    String coinsPackage;
    String coins;
    String transactionId;
    boolean isLoggedIn;

    // getters/setters
}

Test.java

import com.google.gson.Gson;

public class Test {

    public static void main(String[] args) {
        SampleDTO objSampleDTO = new SampleDTO();
        Gson objGson = new Gson();
        System.out.println(objGson.toJson(objSampleDTO));
    }
}

OUTPUT:

{"isLoggedIn":false}

I used gson-2.2.4

Regular Expression to select everything before and up to a particular text

Up to and including txt you would need to change your regex like so:

^(.*?\\.txt)

How to dispatch a Redux action with a timeout?

You can do this with redux-thunk. There is a guide in redux document for async actions like setTimeout.

How do I install a NuGet package .nupkg file locally?

If you have a .nupkg file and just need the .dll file all you have to do is change the extension to .zip and find the lib directory.

Python: CSV write by column rather than row

Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237

How to parse this string in Java?

String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.

Should I test private methods or only public ones?

If your private method is not tested by calling your public methods then what is it doing? I'm talking private not protected or friend.

How to get row count using ResultSet in Java?

From http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSetMetaData.html

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 int numberOfColumns = rsmd.getColumnCount();

A ResultSet contains metadata which gives the number of rows.

How to run Tensorflow on CPU

You could use tf.config.set_visible_devices. One possible function that allows you to set if and which GPUs to use is:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

Suppose you are on a system with 4 GPUs and you want to use only two GPUs, the one with id = 0 and the one with id = 2, then the first command of your code, immediately after importing the libraries, would be:

set_gpu([0, 2])

In your case, to use only the CPU, you can invoke the function with an empty list:

set_gpu([])

For completeness, if you want to avoid that the runtime initialization will allocate all memory on the device, you can use tf.config.experimental.set_memory_growth. Finally, the function to manage which devices to use, occupying the GPUs memory dynamically, becomes:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            for gpu in gpus_used:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

How to convert all text to lowercase in Vim

use ggguG

gg: goes to the first line.

gu: change to lowercase.

G: goes to the last line.

Detecting touch screen devices with Javascript

Google Chrome seems to return false positives on this one:

var isTouch = 'ontouchstart' in document.documentElement;

I suppose it has something to do with its ability to "emulate touch events" (F12 -> settings at lower right corner -> "overrides" tab -> last checkbox). I know it's turned off by default but that's what I connect the change in results with (the "in" method used to work in Chrome). However, this seems to be working, as far as I have tested:

var isTouch = !!("undefined" != typeof document.documentElement.ontouchstart);

All browsers I've run that code on state the typeof is "object" but I feel more certain knowing that it's whatever but undefined :-)

Tested on IE7, IE8, IE9, IE10, Chrome 23.0.1271.64, Chrome for iPad 21.0.1180.80 and iPad Safari. It would be cool if someone made some more tests and shared the results.

Getting values from query string in an url using AngularJS $location

$location.search() returns an object, consisting of the keys as variables and the values as its value. So: if you write your query string like this:

?user=test_user_bLzgB

You could easily get the text like so:

$location.search().user

If you wish not to use a key, value like ?foo=bar, I suggest using a hash #test_user_bLzgB ,

and calling

$location.hash()

would return 'test_user_bLzgB' which is the data you wish to retrieve.

Additional info:

If you used the query string method and you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy instead of the html5 one... To get it working, add this config to your module

yourModule.config(['$locationProvider', function($locationProvider){
    $locationProvider.html5Mode(true);    
}]);

How to Clone Objects

I use AutoMapper for this. It works like this:

Mapper.CreateMap(typeof(Person), typeof(Person));
Mapper.Map(a, b);

Now person a has all the properties of person b.

As an aside, AutoMapper works for differing objects as well. For more information, check it out at http://automapper.org

Update: I use this syntax now (simplistically - really the CreateMaps are in AutoMapper profiles):

Mapper.CreateMap<Person, Person>;
Mapper.Map(a, b);

Note that you don't have to do a CreateMap to map one object of the same type to another, but if you don't, AutoMapper will create a shallow copy, meaning to the lay man that if you change one object, the other changes also.

Stop Excel from automatically converting certain text values to dates

In my case, "Sept8" in a csv file generated using R was converted into "8-Sept" by Excel 2013. The problem was solved by using write.xlsx2() function in the xlsx package to generate the output file in xlsx format, which can be loaded by Excel without unwanted conversion. So, if you are given a csv file, you can try loading it into R and converting it into xlsx using the write.xlsx2() function.

List append() in for loop

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

Escaping ampersand in URL

They need to be percent-encoded:

> encodeURIComponent('&')
"%26"

So in your case, the URL would look like:

http://www.mysite.com?candy_name=M%26M

What is Common Gateway Interface (CGI)?

CGI is a mechanism whereby an external program is called by the web server in order to handle a request, with environment variables and standard input being used to feed the request data to the program. The exact language the external program is written in does not matter, although it is easier to write CGI programs in some languages versus others.

Since CGI scripts need execute permissions, httpd by default only allows CGI programs in the cgi-bin directory to be run for (possibly now misguided) security purposes.

Most PHP scripts run in the web server process via mod_php. This is not CGI.

CGI is slow since the program (and related interpreter) must be started up per request. Modern alternatives are embedded execution, used by mod_php, and long-running processes, used by FastCGI. A given language may have its own way of implementing those mechanisms, so be sure to ask around before resorting to CGI.

How to install plugin for Eclipse from .zip

Seen here. You can unzip and

enter image description here enter image description here

Clicking Local will prefix your location fith file:/C:/etc/folder

You can Click archive instead and select your zip, as suggested in the second popular question. It will prefix with jar://path.zip but it is not accepted by Eclipse itself. So, I used the plain folder solution.

Tar archiving that takes input from a list of files

Assuming GNU tar (as this is Linux), the -T or --files-from option is what you want.

jQuery click event not working after adding class

Based on @Arun P Johny this is how you do it for an input:

<input type="button" class="btEdit" id="myButton1">

This is how I got it in jQuery:

$(document).on('click', "input.btEdit", function () {
    var id = this.id;
    console.log(id);
});

This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

UPDATE

Though it would be better to say:

$(document).on('click', "input.btEdit", function () {
    var id = $(this).id;
    console.log(id);
});

Since this is JQuery's syntax, even though both will work.

Java Try Catch Finally blocks without Catch

Java versions before version 7 allow for these three combinations of try-catch-finally...

try - catch
try - catch - finally
try - finally

finally block will be always executed no matter of what's going on in the try or/and catch block. so if there is no catch block, the exception won't be handled here.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

  • Java try block must be followed by either catch or finally block.
  • For each try block there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

How do I print a datetime in the local timezone?

I wrote something like this the other day:

import time, datetime
def nowString():
    # we want something like '2007-10-18 14:00+0100'
    mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
    dt  = datetime.datetime.now()
    dts = dt.strftime('%Y-%m-%d %H:%M')  # %Z (timezone) would be empty
    nowstring="%s%s" % (dts,mytz)
    return nowstring

So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.

Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with time.timezone.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Get the row(s) which have the max value in groups using groupby

df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))

Simple jQuery, PHP and JSONP example?

Simple jQuery, PHP and JSONP example is below:

_x000D_
_x000D_
window.onload = function(){_x000D_
 $.ajax({_x000D_
  cache: false,_x000D_
  url: "https://jsonplaceholder.typicode.com/users/2",_x000D_
  dataType: 'jsonp',_x000D_
  type: 'GET',_x000D_
  success: function(data){_x000D_
   console.log('data', data)_x000D_
  },_x000D_
  error: function(data){_x000D_
   console.log(data);_x000D_
  }_x000D_
 });_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Detecting a mobile browser

//true / false
function isMobile()
{
   return (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ); 
}

also you can follow this tutorial to detect a specific mobile. Click here.

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Java program to get the current date without timestamp

You could use

// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;

Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

Have a look at the Formatter API documentation.

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

Java division by zero doesnt throw an ArithmeticException - why?

There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.

If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.

What's the difference between unit, functional, acceptance, and integration tests?

The important thing is that you know what those terms mean to your colleagues. Different groups will have slightly varying definitions of what they mean when they say "full end-to-end" tests, for instance.

I came across Google's naming system for their tests recently, and I rather like it - they bypass the arguments by just using Small, Medium, and Large. For deciding which category a test fits into, they look at a few factors - how long does it take to run, does it access the network, database, filesystem, external systems and so on.

http://googletesting.blogspot.com/2010/12/test-sizes.html

I'd imagine the difference between Small, Medium, and Large for your current workplace might vary from Google's.

However, it's not just about scope, but about purpose. Mark's point about differing perspectives for tests, e.g. programmer vs customer/end user, is really important.

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Practical uses of git reset --soft?

One possible usage would be when you want to continue your work on a different machine. It would work like this:

  1. Checkout a new branch with a stash-like name,

    git checkout -b <branchname>_stash
    
  2. Push your stash branch up,

    git push -u origin <branchname>_stash
    
  3. Switch to your other machine.

  4. Pull down both your stash and existing branches,

    git checkout <branchname>_stash; git checkout <branchname>
    
  5. You should be on your existing branch now. Merge in the changes from the stash branch,

    git merge <branchname>_stash
    
  6. Soft reset your existing branch to 1 before your merge,

    git reset --soft HEAD^
    
  7. Remove your stash branch,

    git branch -d <branchname>_stash
    
  8. Also remove your stash branch from origin,

    git push origin :<branchname>_stash
    
  9. Continue working with your changes as if you had stashed them normally.

I think, in the future, GitHub and co. should offer this "remote stash" functionality in fewer steps.

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

jquery if div id has children

The jQuery way

In jQuery, you can use $('#id').children().length > 0 to test if an element has children.

Demo

_x000D_
_x000D_
var test1 = $('#test');_x000D_
var test2 = $('#test2');_x000D_
_x000D_
if(test1.children().length > 0) {_x000D_
    test1.addClass('success');_x000D_
} else {_x000D_
    test1.addClass('failure');_x000D_
}_x000D_
_x000D_
if(test2.children().length > 0) {_x000D_
    test2.addClass('success');_x000D_
} else {_x000D_
    test2.addClass('failure');_x000D_
}
_x000D_
.success {_x000D_
    background: #9f9;_x000D_
}_x000D_
_x000D_
.failure {_x000D_
    background: #f99;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>_x000D_
<div id="test">_x000D_
   <span>Children</span>_x000D_
</div>_x000D_
<div id="test2">_x000D_
   No children_x000D_
</div>
_x000D_
_x000D_
_x000D_


The vanilla JS way

If you don't want to use jQuery, you can use document.getElementById('id').children.length > 0 to test if an element has children.

Demo

_x000D_
_x000D_
var test1 = document.getElementById('test');_x000D_
var test2 = document.getElementById('test2');_x000D_
_x000D_
if(test1.children.length > 0) {_x000D_
    test1.classList.add('success');_x000D_
} else {_x000D_
    test1.classList.add('failure');_x000D_
}_x000D_
_x000D_
if(test2.children.length > 0) {_x000D_
    test2.classList.add('success');_x000D_
} else {_x000D_
    test2.classList.add('failure');_x000D_
}
_x000D_
.success {_x000D_
    background: #9f9;_x000D_
}_x000D_
_x000D_
.failure {_x000D_
    background: #f99;_x000D_
}
_x000D_
<div id="test">_x000D_
   <span>Children</span>_x000D_
</div>_x000D_
<div id="test2">_x000D_
   No children_x000D_
</div>
_x000D_
_x000D_
_x000D_