Programs & Examples On #Nsbrowser

NSBrowser is a Cocoa control that breaks down items hierarchically.

Get first 100 characters from string, respecting full words

The problem with accepted answer is that result string goes over the the limit, i.e. it can exceed 100 chars since strpos will look after the offset and so your length will always be a over your limit. If the last word is long, like squirreled then the length of your result will be 111 (to give you an idea).

A better solution is to use wordwrap function:

function truncate($str, $length = 125, $append = '...') {
    if (strlen($str) > $length) {
        $delim = "~\n~";
        $str = substr($str, 0, strpos(wordwrap($str, $length, $delim), $delim)) . $append;
    } 

    return $str;
}


echo truncate("The quick brown fox jumped over the lazy dog.", 5);

This way you can be sure the string is truncated under your limit (and never goes over)

P.S. This is particularly useful if you plan to store the truncated string in your database with a fixed-with column like VARCHAR(50), etc.

P.P.S. Note the special delimiter in wordwrap. This is to make sure that your string is truncated correctly even when it contains newlines (otherwise it will truncate at first newline which you don't want).

Angular 2: 404 error occur when I refresh through the browser

Perhaps you can do it while registering your root with RouterModule. You can pass a second object with property useHash:true like the below:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { ROUTES }   from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    RouterModule.forRoot(ROUTES ,{ useHash: true }),],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

What does template <unsigned int N> mean?

Yes, it is a non-type parameter. You can have several kinds of template parameters

  • Type Parameters.
    • Types
    • Templates (only classes and alias templates, no functions or variable templates)
  • Non-type Parameters
    • Pointers
    • References
    • Integral constant expressions

What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:

Template type parameter:

template<typename T>
struct Container {
    T t;
};

// pass type "long" as argument.
Container<long> test;

Template integer parameter:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

Template pointer parameter (passing a pointer to a function)

template<void (*F)()>
struct FunctionWrapper {
    static void call_it() { F(); }
};

// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;

Template reference parameter (passing an integer)

template<int &A>
struct SillyExample {
    static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

Template template parameter.

template<template<typename T> class AllocatePolicy>
struct Pool {
    void allocate(size_t n) {
        int *p = AllocatePolicy<int>::allocate(n);
    }
};

// pass the template "allocator" as argument. 
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:

template<unsigned int SIZE = 3>
struct Vector {
    unsigned char buffer[SIZE];
};

Vector<> test;

Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:

template<>
struct Vector<3> {
    // alternative definition for SIZE == 3
};

Firefox Add-on RESTclient - How to input POST parameters?

Request header needs to be set as per below image.add request header

request body can be passed as json string in text area. enter image description here

Restore a deleted file in the Visual Studio Code Recycle Bin

Running on Ubuntu 18.04, with VS code 1.51.0

My deleted files from VS Code are located at:

~/.local/share/Trash/files

To search for your deleted files:

find ~/.local/share/Trash/files -name your_file_name 

Hope my case helped!

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

you can use the return statement without any parameter to exit a function

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

or raise an exception if you want to be informed of the problem

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Recursively list all files in a directory including files in symlink directories

How about tree? tree -l will follow symlinks.

Disclaimer: I wrote this package.

Setting the value of checkbox to true or false with jQuery

var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );

This will set the value of the checkbox to "true" or "false" (value property is a string), depending whether it's unchecked or checked.

Works in jQuery >= 1.0

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

Variable number of arguments in C++?

As others have said, C-style varargs. But you can also do something similar with default arguments.

How to get the index of an element in an IEnumerable?

An alternative to finding the index after the fact is to wrap the Enumerable, somewhat similar to using the Linq GroupBy() method.

public static class IndexedEnumerable
{
    public static IndexedEnumerable<T> ToIndexed<T>(this IEnumerable<T> items)
    {
        return IndexedEnumerable<T>.Create(items);
    }
}

public class IndexedEnumerable<T> : IEnumerable<IndexedEnumerable<T>.IndexedItem>
{
    private readonly IEnumerable<IndexedItem> _items;

    public IndexedEnumerable(IEnumerable<IndexedItem> items)
    {
        _items = items;
    }

    public class IndexedItem
    {
        public IndexedItem(int index, T value)
        {
            Index = index;
            Value = value;
        }

        public T Value { get; private set; }
        public int Index { get; private set; }
    }

    public static IndexedEnumerable<T> Create(IEnumerable<T> items)
    {
        return new IndexedEnumerable<T>(items.Select((item, index) => new IndexedItem(index, item)));
    }

    public IEnumerator<IndexedItem> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Which gives a use case of:

var items = new[] {1, 2, 3};
var indexedItems = items.ToIndexed();
foreach (var item in indexedItems)
{
    Console.WriteLine("items[{0}] = {1}", item.Index, item.Value);
}

How to import a class from default package

I can give you this suggestion, As far as know from my C and C++ Programming experience, Once, when I had the same kinda problem, I solved it by changing the dll written structure in ".C" File by changing the name of the function which implemented the JNI native functionality. for example, If you would like to add your program in the package "com.mypackage", You change the prototype of the JNI implementing ".C" File's function/method to this one:

JNIEXPORT jint JNICALL
Java_com_mypackage_Calculations_Calculate(JNIEnv *env, jobject obj, jint contextId)
{
   //code goes here
}

JNIEXPORT jdouble JNICALL
Java_com_mypackage_Calculations_GetProgress(JNIEnv *env, jobject obj, jint contextId)
{
  //code goes here
}

Since I am new to delphi, I can not guarantee you but will say this finally, (I learned few things after googling about Delphi and JNI): Ask those people (If you are not the one) who provided the Delphi implementation of the native code to change the function names to something like this:

function Java_com_mypackage_Calculations_Calculate(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JInt; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
  //Some code goes here
end;



function Java_com_mypackage_Calculations_GetProgress(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JDouble; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
//Some code goes here
end;

But, A final advice: Although you (If you are the delphi programmer) or them will change the prototypes of these functions and recompile the dll file, once the dll file is compiled, you will not be able to change the package name of your "Java" file again & again. Because, this will again require you or them to change the prototypes of the functions in delphi with changed prefixes (e.g. JAVA_yourpackage_with_underscores_for_inner_packages_JavaFileName_MethodName)

I think this solves the problem. Thanks and regards, Harshal Malshe

What is referencedColumnName used for in JPA?

It is there to specify another column as the default id column of the other table, e.g. consider the following

TableA
  id int identity
  tableb_key varchar


TableB
  id int identity
  key varchar unique

// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")

How to break out of the IF statement

To answer your question:

public void Method()
{
    while(true){
        if(something)
        {
            //some code
            if(something2)
            {
                break;
            }
        return;
        }
        break;
    }
    // The code i want to go if the second if is true
}

If else embedding inside html

You will find multiple different methods that people use and they each have there own place.

<?php if($first_condition): ?>
  /*$first_condition is true*/
<?php elseif ($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
<?php else: ?>
  /*$first_condition and $second_condition are false*/
<?php endif; ?>

If in your php.ini attribute short_open_tag = true (this is normally found on line 141 of the default php.ini file) you can replace your php open tag from <?php to <?. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php. short_open_tag is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag turned off.

A quick search of short_open_tag in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag That's a lot of people having problems with something they should just not play with.

with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag set to true.

short_open_tag will be removed in PHP6 so don't use short hand tags.

all future PHP versions will be dropping short_open_tag

"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working

and

Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .

Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem

and

To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?

You may also see people use the following example:

<?php if($first_condition){ ?>
  /*$first_condition is true*/
<?php }else if ($second_condition){ ?>
  /*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
  /*$first_condition and $second_condition are false*/
<?php } ?>

This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.

The following example shows when to use the bracket method

<?php
if($first_condition){
   /*$first_condition is true*/
}else if ($second_condition){
   /*$first_condition is false and $second_condition is true*/
}else{
   /*$first_condition and $second_condition are false*/
}
?>

If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.

UPDATE

based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.

How to allow only one radio button to be checked?

They need to all have the same name.

VBA for clear value in specific range of cell and protected cell from being wash away formula

You could define a macro containing the following code:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.ClearContents
end sub

Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.

To leave your formulas intact use the following instead:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.SpecialCells(xlCellTypeConstants, 23).Select
    Selection.ClearContents
end sub

This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'

You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.

What is the use of verbose in Keras while validating the model?

The order of details provided with verbose flag are as

Less details.... More details

0 < 2 < 1

Default is 1

For production environment, 2 is recommended

Differences between Octave and MATLAB?

MATLAB is, first and foremost, a commercial offering. Therefore, everything in MATLAB pretty much works out of the box. All the core functionality is solid, and if you're working on a special project then MATLAB probably has an add-on they can sell you that adds a lot of additional domain-specific .m files for you. It ain't cheap, but it works and it will get the job done without complaint.

Octave always shows its open-source, information-wants-to-be-free roots. It's free, and it will remind you that it's free at every opportunity. It's developed by volunteers who hate Windows with a passion. Therefore Octave runs on Windows grudgingly. It's quite surprising that as many MATLAB features exist as they do.

But here's the rub. Anytime you try to do something more than trivially complex, Octave suddenly breaks in subtle and hard to understand ways. Oops -- the terminal driver had an overflow somewhere deep in the OpenGL layer. You can't print. Oops -- the figure plots do strange things with their fonts. Good luck figuring out why. Oops -- there's some hidden dependency between Octave and some other obscure bit of free software, so it won't compile. Good luck figuring out which it is.

And the Octave response is hey! It's free software! You have all the source code, you can fix all those bugs yourself! Maybe if I had infinite time and resources on my hands, I could spend all my time fixing bugs in free software, but I personally don't. If I worked in academia, I might.

So at the core, the issue of whether to choose MATLAB or Octave comes down to one question. Interestingly, that question is always the same, when choosing between commercial vs. free software variants.

And the question is:

Do you have more money than time?

SQL DELETE with JOIN another table for WHERE condition

I think, from your description, the following would suffice:

DELETE FROM guide_category 
WHERE id_guide NOT IN (SELECT id_guide FROM guide)

I assume, that there are no referential integrity constraints on the tables involved, are there?

Convert UTC datetime string to local datetime

This answer should be helpful if you don't want to use any other modules besides datetime.

datetime.utcfromtimestamp(timestamp) returns a naive datetime object (not an aware one). Aware ones are timezone aware, and naive are not. You want an aware one if you want to convert between timezones (e.g. between UTC and local time).

If you aren't the one instantiating the date to start with, but you can still create a naive datetime object in UTC time, you might want to try this Python 3.x code to convert it:

import datetime

d=datetime.datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S") #Get your naive datetime object
d=d.replace(tzinfo=datetime.timezone.utc) #Convert it to an aware datetime object in UTC time.
d=d.astimezone() #Convert it to your local timezone (still aware)
print(d.strftime("%d %b %Y (%I:%M:%S:%f %p) %Z")) #Print it with a directive of choice

Be careful not to mistakenly assume that if your timezone is currently MDT that daylight savings doesn't work with the above code since it prints MST. You'll note that if you change the month to August, it'll print MDT.

Another easy way to get an aware datetime object (also in Python 3.x) is to create it with a timezone specified to start with. Here's an example, using UTC:

import datetime, sys

aware_utc_dt_obj=datetime.datetime.now(datetime.timezone.utc) #create an aware datetime object
dt_obj_local=aware_utc_dt_obj.astimezone() #convert it to local time

#The following section is just code for a directive I made that I liked.
if sys.platform=="win32":
    directive="%#d %b %Y (%#I:%M:%S:%f %p) %Z"
else:
    directive="%-d %b %Y (%-I:%M:%S:%f %p) %Z"

print(dt_obj_local.strftime(directive))

If you use Python 2.x, you'll probably have to subclass datetime.tzinfo and use that to help you create an aware datetime object, since datetime.timezone doesn't exist in Python 2.x.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

why are there two different kinds of for loops in java?

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

Using IF ELSE statement based on Count to execute different Insert statements

IF exists

IF exists (select * from table_1 where col1 = 'value')
BEGIN
    -- one or more
    insert into table_1 (col1) values ('valueB')
END
ELSE
    -- zero
    insert into table_1 (col1) values ('value') 

How to split a delimited string into an array in awk?

I know this is kind of old question, but I thought maybe someone like my trick. Especially since this solution not limited to a specific number of items.

# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))

# Output array items
for _ITEM in "${_ITEMS[@]}"; do
  echo "Item: ${_ITEM}"
done

The output will be:

Item: 12
Item: 23
Item: 11

Accessing private member variables from prototype-defined functions

In current JavaScript, I'm fairly certain that there is one and only one way to have private state, accessible from prototype functions, without adding anything public to this. The answer is to use the "weak map" pattern.

To sum it up: The Person class has a single weak map, where the keys are the instances of Person, and the values are plain objects that are used for private storage.

Here is a fully functional example: (play at http://jsfiddle.net/ScottRippey/BLNVr/)

var Person = (function() {
    var _ = weakMap();
    // Now, _(this) returns an object, used for private storage.
    var Person = function(first, last) {
        // Assign private storage:
        _(this).firstName = first;
        _(this).lastName = last;
    }
    Person.prototype = {
        fullName: function() {
            // Retrieve private storage:
            return _(this).firstName + _(this).lastName;
        },
        firstName: function() {
            return _(this).firstName;
        },
        destroy: function() {
            // Free up the private storage:
            _(this, true);
        }
    };
    return Person;
})();

function weakMap() {
    var instances=[], values=[];
    return function(instance, destroy) {
        var index = instances.indexOf(instance);
        if (destroy) {
            // Delete the private state:
            instances.splice(index, 1);
            return values.splice(index, 1)[0];
        } else if (index === -1) {
            // Create the private state:
            instances.push(instance);
            values.push({});
            return values[values.length - 1];
        } else {
            // Return the private state:
            return values[index];
        }
    };
}

Like I said, this is really the only way to achieve all 3 parts.

There are two caveats, however. First, this costs performance -- every time you access the private data, it's an O(n) operation, where n is the number of instances. So you won't want to do this if you have a large number of instances. Second, when you're done with an instance, you must call destroy; otherwise, the instance and the data will not be garbage collected, and you'll end up with a memory leak.

And that's why my original answer, "You shouldn't", is something I'd like to stick to.

IntelliJ how to zoom in / out

Update for intellij idea 2017 3.2

Intellij idea 2017 3.2

Javascript | Set all values of an array

Actually, you can use this perfect approach:

let arr = Array.apply(null, Array(5)).map(() => 0);
// [0, 0, 0, 0, 0]

This code will create array and fill it with zeroes. Or just:

let arr = new Array(5).fill(0)

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

TypeScript: casting HTMLElement

Just to clarify, this is correct.

Cannot convert 'NodeList' to 'HTMLScriptElement[]'

as a NodeList is not an actual array (e.g. it doesn't contain .forEach, .slice, .push, etc...).

Thus if it did convert to HTMLScriptElement[] in the type system, you'd get no type errors if you tried to call Array.prototype members on it at compile time, but it would fail at run time.

JavaScript Infinitely Looping slideshow with delays?

Here's a nice, tidy solution for you: (also see the live demo ->)

window.onload = function start() {
    slide();
}

function slide() {
    var currMarg = 0,
        contStyle = document.getElementById('container').style;
    setInterval(function() {
        currMarg = currMarg == 1800 ? 0 : currMarg + 600;
        contStyle.marginLeft = '-' + currMarg + 'px';
    }, 3000);
}

Since you are trying to learn, allow me to explain how this works.

First we declare two variables: currMarg and contStyle. currMarg is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.

Next, we will use setInterval to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout, except it happens infinitely until cancelled, instead of just happening once.

We pass an anonymous function to setInterval, which will do our work for us. The first line is:

currMarg = currMarg == 1800 ? 0 : currMarg + 600;

This is a ternary operator. It will assign currMarg the value of 0 if currMarg is equal to 1800, otherwise it will increment currMarg by 600.

With the second line, we simply assign our chosen value to containers marginLeft, and we're done!

Note: For the demo, I changed the negative values to positive, so the effect would be visible.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

    D:\Java\jdk1.5.0_10\bin\keytool -import -file "D:\Certificates\SDS services\Dev\dev-sdsservices-was8.infavig.com.cer" -keystore "D:\Java\jdk1.5.0_10\jre\lib\security\cacerts" -alias "sds certificate"

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

clearing select using jquery

use .empty()

 $('select').empty().append('whatever');

you can also use .html() but note

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

alternative: --- If you want only option elements to-be-remove, use .remove()

$('select option').remove();

How to make html <select> element look like "disabled", but pass values?

Add a class .disabled and use this CSS:

?.disabled {border: 1px solid #999; color: #333; opacity: 0.5;}
.disabled option {color: #000; opacity: 1;}?

Demo: http://jsfiddle.net/ZCSRq/

Youtube API Limitations

Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.

You can read about what a unit is here: https://developers.google.com/youtube/v3/getting-started#quota

  • A simple read operation that only retrieves the ID of each returned resource has a cost of approximately 1 unit.
  • A write operation has a cost of approximately 50 units.
  • A video upload has a cost of approximately 1600 units.

If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.

Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here: https://youtube-eng.googleblog.com/2012/09/the-youtube-api-on-stack-overflow_14.html

There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...

UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.

UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.

UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.

Calculate time difference in minutes in SQL Server

Try this..

select starttime,endtime, case
  when DATEDIFF(minute,starttime,endtime) < 60  then DATEDIFF(minute,starttime,endtime) 
  when DATEDIFF(minute,starttime,endtime) >= 60
  then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416

All You need is DateDiff..

Truncating Text in PHP?

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

Creating a UICollectionView programmatically

Swift 3

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let flowLayout = UICollectionViewFlowLayout()

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan

        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.green
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

}

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

Accessing Session Using ASP.NET Web API

Why to avoid using Session in WebAPI?

Performance, performance, performance!

There's a very good, and often overlooked reason why you shouldn't be using Session in WebAPI at all.

The way ASP.NET works when Session is in use is to serialize all requests received from a single client. Now I'm not talking about object serialization - but running them in the order received and waiting for each to complete before running the next. This is to avoid nasty thread / race conditions if two requests each try to access Session simultaneously.

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

So what does this mean for Web API? If you have an application running many AJAX requests then only ONE is going to be able to run at a time. If you have a slower request then it will block all others from that client until it is complete. In some applications this could lead to very noticeably sluggish performance.

So you should probably use an MVC controller if you absolutely need something from the users session and avoid the unncesessary performance penalty of enabling it for WebApi.

You can easily test this out for yourself by just putting Thread.Sleep(5000) in a WebAPI method and enable Session. Run 5 requests to it and they will take a total of 25 seconds to complete. Without Session they'll take a total of just over 5 seconds.

(This same reasoning applies to SignalR).

What is Shelving in TFS?

One point that is missed in a lot of these discussions is how you revert back on the SAME machine on which you shelved your changes. Perhaps obvious to most, but wasn't to me. I believe you perform an Undo Pending Changes - is that right?

I understand the process to be as follows:

  1. To shelve your current pending changes, right click the project, Shelve, add a shelve name
  2. This will save (or Shelve) the changes to the server (no-one will see them)
  3. You then do Undo Pending Changes to revert your code back to the last check-in point
  4. You can then do what you need to do with the reverted code baseline
  5. You can Unshelve the changes at any time (may require some merge confliction)

So, if you want to start some work which you may need to Shelve, make sure you check-in before you start, as the check-in point is where you'll return to when doing the Undo Pending Changes step above.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

With PYTHONPATH set as in your example, you should be able to do

python -m gmbx

-m option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py, it looks for particular file and PYTHONPATH does not apply.

How to use wait and notify in Java without IllegalMonitorStateException?

Simple use if you want How to execute threads alternatively :-

public class MyThread {
    public static void main(String[] args) {
        final Object lock = new Object();
        new Thread(() -> {
            try {
                synchronized (lock) {
                    for (int i = 0; i <= 5; i++) {
                        System.out.println(Thread.currentThread().getName() + ":" + "A");
                        lock.notify();
                        lock.wait();
                    }
                }
            } catch (Exception e) {}
        }, "T1").start();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    for (int i = 0; i <= 5; i++) {
                        System.out.println(Thread.currentThread().getName() + ":" + "B");
                        lock.notify();
                        lock.wait();
                    }
                }
            } catch (Exception e) {}
        }, "T2").start();
    }
}

response :-

T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B

Differences between SP initiated SSO and IDP initiated SSO

SP Initiated SSO

Bill the user: "Hey Jimmy, show me that report"

Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."

Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."

Bill the user: "Hi I'm Bill. Here are my credentials."

Bob the IdP: "Hi Bill. Looks like you check out."

Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."

IdP Initiated SSO

Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."

Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."


I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

I'm new with Android and the project appcompat_v7 always be created when I create new Android application project makes me so uncomfortable.

This is just a walk around. Choose Project Properties -> Android then at Library box just remove appcompat_v7_x and add appcompat_v7. Now you can delete appcompat_v7_x.

Uncheck Create Activity in create project wizard doesn't work, because when creating activity by wizard the appcompat_v7_x appear again. My ADT's version is v22.6.2-1085508.
I'm sorry if my English is bad.

How to get the file-path of the currently executing javascript code

Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,

<script type=text/javascript src='/dir/jsfile.js'></script>

or

<script type=text/javascript src='../../scripts/jsfile.js'></script>

If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path

Form inline inside a form horizontal in twitter bootstrap?

Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.

<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
    <div class="form-group">
        <label class="control-label col-sm-2" for="naam">Naam:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
            <div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
        </div>
    </div>

    <div class="form-row">

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="telefoon">Telefoon:&nbsp;*</label>
            <div class="col-sm-12">
                <input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
                <div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
            </div>
        </div>

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="email">E-mail: </label>
            <div class="col-sm-12">
                <input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
                <div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
                    </div>
                </div>

        </div>

    <div class="form-group">
        <label class="control-label col-sm-2" for="titel">Titel:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
            <div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
        </div>
    </div>
<from>

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In scripts you have more options and a better shot at rational decomposition. Look into SQLCMD mode (Query Menu -> SQLCMD mode), specifically the :setvar and :r commands.

Within a stored procedure your options are very limited. You can't create define a function directly with the body of a procedure. The best you can do is something like this, with dynamic SQL:

create proc DoStuff
as begin

  declare @sql nvarchar(max)

  /*
  define function here, within a string
  note the underscore prefix, a good convention for user-defined temporary objects
  */
  set @sql = '
    create function dbo._object_name_twopart (@object_id int)
    returns nvarchar(517) as
    begin
      return 
        quotename(object_schema_name(@object_id))+N''.''+
        quotename(object_name(@object_id))
    end
  '

  /*
  create the function by executing the string, with a conditional object drop upfront
  */
  if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart
  exec (@sql)

  /*
  use the function in a query
  */
  select object_id, dbo._object_name_twopart(object_id) 
  from sys.objects
  where type = 'U'

  /*
  clean up
  */
  drop function _object_name_twopart

end
go

This approximates a global temporary function, if such a thing existed. It's still visible to other users. You could append the @@SPID of your connection to uniqueify the name, but that would then require the rest of the procedure to use dynamic SQL too.

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

how to get the base url in javascript

To get exactly the same thing as base_url of codeigniter, you can do:

var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';

this will be more useful if you work on pure Javascript file.

Good Patterns For VBA Error Handling

Error Handling in VBA


  • On Error Goto ErrorHandlerLabel
  • Resume (Next | ErrorHandlerLabel)
  • On Error Goto 0 (disables current error handler)
  • Err object

The Err object's properties are normally reset to zero or a zero-length string in the error handling routine, but it can also be done explicitly with Err.Clear.

Errors in the error handling routine are terminating.

The range 513-65535 is available for user errors. For custom class errors, you add vbObjectError to the error number. See MS documentation about Err.Raise and the list of error numbers.

For not implemented interface members in a derived class, you should use the constant E_NOTIMPL = &H80004001.


Option Explicit

Sub HandleError()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub RaiseAndHandleError()
  On Error GoTo errMyErrorHandler
    ' The range 513-65535 is available for user errors.
    ' For class errors, you add vbObjectError to the error number.
    Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
  On Error GoTo 0

  Debug.Print "This line will be executed."

Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
  Err.Clear
Resume Next
End Sub

Sub FailInErrorHandler()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  a = 7 / 0 ' <== Terminating error!
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub DontDoThis()

  ' Any error will go unnoticed!
  On Error Resume Next
  ' Some complex code that fails here.
End Sub

Sub DoThisIfYouMust()

  On Error Resume Next
  ' Some code that can fail but you don't care.
  On Error GoTo 0

  ' More code here
End Sub

Direct download from Google Drive using Google Drive API

I would consider downloading from the link, scraping the page that you get to grab the confirmation link, and then downloading that.

If you look at the "download anyway" URL it has an extra confirm query parameter with a seemingly randomly generated token. Since it's random...and you probably don't want to figure out how to generate it yourself, scraping might be the easiest way without knowing anything about how the site works.

You may need to consider various scenarios.

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

Detecting the onload event of a window opened with window.open

This did the trick for me; full example:

HTML:

<a href="/my-popup.php" class="import">Click for my popup on same domain</a>

Javascript:

(function(){
    var doc = document;

    jQuery('.import').click(function(e){
        e.preventDefault();
        window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');

        window.popup.onload = function() {
            window.popup.onbeforeunload = function(){
                doc.location.reload(true); //will refresh page after popup close
            }
        }
    });
})();

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

@synthesize vs @dynamic, what are the differences?

here is example of @dynamic

#import <Foundation/Foundation.h>

@interface Book : NSObject
{
   NSMutableDictionary *data;
}
@property (retain) NSString *title;
@property (retain) NSString *author;
@end

@implementation Book
@dynamic title, author;

- (id)init
{
    if ((self = [super init])) {
        data = [[NSMutableDictionary alloc] init];
        [data setObject:@"Tom Sawyer" forKey:@"title"];
        [data setObject:@"Mark Twain" forKey:@"author"];
    }
    return self;
}

- (void)dealloc
{
    [data release];
    [super dealloc];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    NSString *sel = NSStringFromSelector(selector);
    if ([sel rangeOfString:@"set"].location == 0) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
    } else {
        return [NSMethodSignature signatureWithObjCTypes:"@@:"];
    }
 }

- (void)forwardInvocation:(NSInvocation *)invocation
{
    NSString *key = NSStringFromSelector([invocation selector]);
    if ([key rangeOfString:@"set"].location == 0) {
        key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
        NSString *obj;
        [invocation getArgument:&obj atIndex:2];
        [data setObject:obj forKey:key];
    } else {
        NSString *obj = [data objectForKey:key];
        [invocation setReturnValue:&obj];
    }
}

@end

int main(int argc, char **argv)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Book *book = [[Book alloc] init];
    printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
    book.title = @"1984";
    book.author = @"George Orwell";
    printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);

   [book release];
   [pool release];
   return 0;
}

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

How should I call 3 functions in order to execute them one after the other?

You could also use promises in this way:

    some_3secs_function(this.some_value).then(function(){
       some_5secs_function(this.some_other_value).then(function(){
          some_8secs_function(this.some_other_other_value);
       });
    });

You would have to make some_value global in order to access it from inside the .then

Alternatively, from the outer function you could return the value the inner function would use, like so:

    one(some_value).then(function(return_of_one){
       two(return_of_one).then(function(return_of_two){
          three(return_of_two);
       });
    });

ES6 Update

Since async/await is widely available now, this is the way to accomplish the same:

async function run(){    
    await $('#art1').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art2').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art3').animate({'width':'1000px'},1000,'linear').promise()
}

Which is basically "promisifying" your functions (if they're not already asynchronous), and then awaiting them

Convert seconds to Hour:Minute:Second

function timeToSecond($time){
    $time_parts=explode(":",$time);
    $seconds= ($time_parts[0]*86400) + ($time_parts[1]*3600) + ($time_parts[2]*60) + $time_parts[3] ; 
    return $seconds;
}

function secondToTime($time){
    $seconds  = $time % 60;
    $seconds<10 ? "0".$seconds : $seconds;
    if($seconds<10) {
        $seconds="0".$seconds;
    }
    $time     = ($time - $seconds) / 60;
    $minutes  = $time % 60;
    if($minutes<10) {
        $minutes="0".$minutes;
    }
    $time     = ($time - $minutes) / 60;
    $hours    = $time % 24;
    if($hours<10) {
        $hours="0".$hours;
    }
    $days     = ($time - $hours) / 24;
    if($days<10) {
        $days="0".$days;
    }

    $time_arr = array($days,$hours,$minutes,$seconds);
    return implode(":",$time_arr);
}

Reading/parsing Excel (xls) files with Python

Python Excelerator handles this task as well. http://ghantoos.org/2007/10/25/python-pyexcelerator-small-howto/

It's also available in Debian and Ubuntu:

 sudo apt-get install python-excelerator

Using msbuild to execute a File System Publish Profile

Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.

The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:

/p:VisualStudioVersion=12.0

12.0 is for VS2013, replace with the version you use. Once I added this parameter, it just worked.

The complete command line looks like this:

MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0

I've found it here:

http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment

They state:

If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.

How to add google-services.json in Android?

The document says:

Copy the file into the app/ folder of your Android Studio project, or into the app/src/{build_type} folder if you are using multiple build types.

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

Performance differences between ArrayList and LinkedList

In a LinkedList the elements have a reference to the element before and after it. In an ArrayList the data structure is just an array.

  1. A LinkedList needs to iterate over N elements to get the Nth element. An ArrayList only needs to return element N of the backing array.

  2. The backing array needs to either be reallocated for the new size and the array copied over or every element after the deleted element needs to be moved up to fill the empty space. A LinkedList just needs to set the previous reference on the element after the removed to the one before the removed and the next reference on the element before the removed element to the element after the removed element. Longer to explain, but faster to do.

  3. Same reason as deletion here.

Is there a way to select sibling nodes?

There are a few ways to do it.

Either one of the following should do the trick.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
    siblingList = children.filter(function(val) {
        return [node].indexOf(val) != -1;
    });
    return siblingList;
}

// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
    var siblingList = [];
    for (var n = children.length - 1; n >= 0; n--) {
        if (children[n] != node) {
            siblingList.push(children[n]);
        }  
    }
    return siblingList;
}

// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
   siblingList = children;
   index = siblingList.indexOf(node);
   if(index != -1) {
       siblingList.splice(index, 1);
   }
   return siblingList;
}

FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

How to set css style to asp.net button?

If you have a button in asp.net design page like "Default.asp" and you want to create CSS file and specified attributes for a button,labels or other controller. Then first of all create a css page

  1. Right click on Project
  2. Add new item
  3. Select StyleSheet

now you have a css page now write these code in your css page(StyleSheet.css)

StyleSheet.css

.mybtnstyle
{
 border:1px solid Red;
 background-color:Red;
 border-style:groove;
 border-top:5px;
 outline-style:dotted;
}

Default.asp

{

  <head> 
  <title> testing.com </title>
 </head>
<body>
 <b>Using Razer<b/>
<form id="form1" runat="server">
 <link id="Link1" rel="stylesheet" runat="server" media="screen" href="Stylesheet1.css" />
 <asp:Button ID="mybtn" class="mybtn" runat="server" Width="339px"/>
 </form>
 </body>
</html>

}

How to enable assembly bind failure logging (Fusion) in .NET

Just in case you're wondering about the location of FusionLog.exe - You know you have it, but you cannot find it? I was looking for FUSLOVW in last few years over and over again. After move to .NET 4.5 number of version of FUSION LOG has exploded. Her are places where it can be found on your disk, depending on software which you have installed:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin

How to prevent IFRAME from redirecting top-level window

I use sandbox="..."

  • allow-forms allows form submission
  • allow-popups allows popups
  • allow-pointer-lock allows pointer lock
  • allow-same-origin allows the document to maintain its origin
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked

ex.

        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>

html vertical align the text inside input type button

I've given up trying to align my text on buttons! Now, if I need it, I'm using <a> tags, like so:

<a href="javascript:void();" style="display:block;font-size:1em;padding:5px;cursor:default;" onclick="document.getElementById('form').submit();">Submit</a>

So, if the document's font size is 12px, my "button" will have 22px height. And the text will be vertically align. That in theory, because, in some casses, an unequal padding of "6px 5px 4px 5px" will do the job done.

Although, is a hack, this technique is pretty good for solving compatibility issues in older browsers too, like IE6!

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

How to check if my string is equal to null?

Exception may also help:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

Learning to write a compiler

Not a book, but a technical paper and an enormously fun learning experience if you want to know more about compilers (and metacompilers)... This website walks you through building a completely self-contained compiler system that can compile itself and other languages:

Tutorial: Metacompilers Part 1

This is all based on an amazing little 10-page technical paper:

Val Schorre META II: A Syntax-Oriented Compiler Writing Language

from honest-to-god 1964. I learned how to build compilers from this back in 1970. There's a mind-blowing moment when you finally grok how the compiler can regenerate itself....

I know the website author from my college days, but I have nothing to do with the website.

How to Decrease Image Brightness in CSS

You can use css filters, below and example for web-kit. please look at this example: http://jsfiddle.net/m9sjdbx6/4/

    img { -webkit-filter: brightness(0.2);}

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

what is the difference between ajax and jquery and which one is better?

It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.

It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.

How can I uninstall Ruby on ubuntu?

On Lubuntu, I just tried apt-get purge ruby* and as well as removing ruby, it looks like this command tried to remove various things to do with GRUB, which is a bit worrying for next time I want to reboot my computer. I can't yet say if any damage has really been done.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value > 1 && $value < 10) || ($value > 20 && $value < 40))

Best way to check for IE less than 9 in JavaScript without library

var ie = !-[1,]; // true if IE less than 9

This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.

How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.

This is the shortest hack by now. And I am the author ;)

How to detect the OS from a Bash script?

I tend to keep my .bashrc and .bash_alias on a file share that all platforms can access. This is how I conquer the problem in my .bash_alias:

if [[ -f (name of share)/.bash_alias_$(uname) ]]; then
    . (name of share)/.bash_alias_$(uname)
fi

And I have for example a .bash_alias_Linux with:

alias ls='ls --color=auto'

This way I keep platform specific and portable code separate, you can do the same for .bashrc

Using a dispatch_once singleton model in Swift

I would suggest an enum, as you would use in Java, e.g.

enum SharedTPScopeManager: TPScopeManager {
    case Singleton
}

How can I introduce multiple conditions in LIKE operator?

Here is an alternative way:

select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';

Here is the test code to verify:

create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col      |
+----------+
| ABCDEFG  |
| XYZ      |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Blockquote

I then modified the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

Ignore the "For Unix only" comment, as this version of sendmail works for Windows.

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

http://byitcurious.blogspot.com.br/2009/04/solving-must-issue-starttls-command.html

> Blockquote

Rebuild Docker container on file changes

After some research and testing, I found that I had some misunderstandings about the lifetime of Docker containers. Simply restarting a container doesn't make Docker use a new image, when the image was rebuilt in the meantime. Instead, Docker is fetching the image only before creating the container. So the state after running a container is persistent.

Why removing is required

Therefore, rebuilding and restarting isn't enough. I thought containers works like a service: Stopping the service, do your changes, restart it and they would apply. That was my biggest mistake.

Because containers are permanent, you have to remove them using docker rm <ContainerName> first. After a container is removed, you can't simply start it by docker start. This has to be done using docker run, which itself uses the latest image for creating a new container-instance.

Containers should be as independent as possible

With this knowledge, it's comprehensible why storing data in containers is qualified as bad practice and Docker recommends data volumes/mounting host directorys instead: Since a container has to be destroyed to update applications, the stored data inside would be lost too. This cause extra work to shutdown services, backup data and so on.

So it's a smart solution to exclude those data completely from the container: We don't have to worry about our data, when its stored safely on the host and the container only holds the application itself.

Why -rf may not really help you

The docker run command, has a Clean up switch called -rf. It will stop the behavior of keeping docker containers permanently. Using -rf, Docker will destroy the container after it has been exited. But this switch has two problems:

  1. Docker also remove the volumes without a name associated with the container, which may kill your data
  2. Using this option, its not possible to run containers in the background using -d switch

While the -rf switch is a good option to save work during development for quick tests, it's less suitable in production. Especially because of the missing option to run a container in the background, which would mostly be required.

How to remove a container

We can bypass those limitations by simply removing the container:

docker rm --force <ContainerName>

The --force (or -f) switch which use SIGKILL on running containers. Instead, you could also stop the container before:

docker stop <ContainerName>
docker rm <ContainerName>

Both are equal. docker stop is also using SIGTERM. But using --force switch will shorten your script, especially when using CI servers: docker stop throws an error if the container is not running. This would cause Jenkins and many other CI servers to consider the build wrongly as failed. To fix this, you have to check first if the container is running as I did in the question (see containerRunning variable).

Full script for rebuilding a Docker container

According to this new knowledge, I fixed my script in the following way:

#!/bin/bash
imageName=xx:my-image
containerName=my-container

docker build -t $imageName -f Dockerfile  .

echo Delete old container...
docker rm -f $containerName

echo Run new container...
docker run -d -p 5000:5000 --name $containerName $imageName

This works perfectly :)

Which port we can use to run IIS other than 80?

Port 8080 might have been used by another process in your computer.

Do netstat in command prompt to find out which server/process is using it.

Have a look at this page (http://en.wikipedia.org/wiki/Port_number) it gives you full explanation on how to use port number

How to run eclipse in clean mode? what happens if we do so?

Using the -clean option is the way to go, as mentioned by the other answers.

Make sure that you remove it from your .ini or shortcut after you've fixed the problem. It causes Eclipse to reevaluate all of the plugins everytime it starts and can dramatically increase startup time, depending on how many Eclipse plugins you have installed.

How to return a list of keys from a Hash Map?

map.keySet()

will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap

How to determine if a string is a number with C++?

Yet another answer, that uses stold (though you could also use stof/stod if you don't require the precision).

bool isNumeric(const std::string& string)
{
    std::size_t pos;
    long double value = 0.0;

    try
    {
        value = std::stold(string, &pos);
    }
    catch(std::invalid_argument&)
    {
        return false;
    }
    catch(std::out_of_range&)
    {
        return false;
    }

    return pos == string.size() && !std::isnan(value);
}

How to get a parent element to appear above child

style:

.parent{
  overflow:hidden;
  width:100px;
}

.child{
  width:200px;
}

body:

<div class="parent">
   <div class="child"></div>
</div>

JFrame Exit on close Java

If you're using a Frame (Class Extends Frame) you'll not get the

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

Although there are many answers already and a link to a very good article on change detection, I wanted to give my two cents here. I think the check is there for a reason so I thought about the architecture of my app and realized that the changes in the view can be dealt with by using BehaviourSubject and the correct lifecycle hook. So here's what I did for a solution.

  • I use a third-party component (fullcalendar), but I also use Angular Material, so although I made a new plugin for styling, getting the look and feel was a bit awkward because customization of the calendar header is not possible without forking the repo and rolling your own.
  • So I ended up getting the underlying JavaScript class, and need to initialize my own calendar header for the component. That requires the ViewChild to be rendered befor my parent is rendered, which is not the way Angular works. This is why I wrapped the value I need for my template in a BehaviourSubject<View>(null):

    calendarView$ = new BehaviorSubject<View>(null);
    

Next, when I can be sure the view is checked, I update that subject with the value from the @ViewChild:

  ngAfterViewInit(): void {
    // ViewChild is available here, so get the JS API
    this.calendarApi = this.calendar.getApi();
  }

  ngAfterViewChecked(): void {
    // The view has been checked and I know that the View object from
    // fullcalendar is available, so emit it.
    this.calendarView$.next(this.calendarApi.view);
  }

Then, in my template, I just use the async pipe. No hacking with change detection, no errors, works smoothly.

Please don't hesitate to ask if you need more details.

How do you remove a Cookie in a Java Servlet

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

AJAX reload page with POST

There's another way with post instead of ajax

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

Check/Uncheck a checkbox on datagridview

Below Code is working perfect

Select / Deselect a check box column on data grid by using checkbox CONTROL

    private void checkBox2_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox2.Checked == false)
        {
            foreach (DataGridViewRow row in dGV1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];

                    chk.Value = chk.TrueValue;
            }
       }
       else if(checkBox2.Checked==true)
       {
            foreach (DataGridViewRow row in dGV1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = 1;
                if (row.IsNewRow)
                {
                    chk.Value = 0;
                }
            }
        }
    }

PHP function ssh2_connect is not working

I am running CentOS 5.6 as my development environment and the following worked for me.

su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Change the location of the ~ directory in a Windows install of Git Bash

Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

PHPMailer: SMTP Error: Could not connect to SMTP host

In my case it was a lack of SSL support in PHP which gave this error.

So I enabled extension=php_openssl.dll

$mail->SMTPDebug = 1; also hinted towards this solution.

Update 2017

$mail->SMTPDebug = 2;, see: https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#enabling-debug-output

Can I have an IF block in DOS batch file?

Maybe a bit late, but hope it hellps:

@echo off 

if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (  
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause

Entity Framework Provider type could not be loaded?

Late to the party, but the top voted answers all seemed like hacks to me.

All I did was remove the following from my app.config in the test project. Worked.

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

How to insert data using wpdb

Use $wpdb->insert().

$wpdb->insert('wp_submitted_form', array(
    'name' => 'Kumkum',
    'email' => '[email protected]',
    'phone' => '3456734567', // ... and so on
));

Addition from @mastrianni:

$wpdb->insert sanitizes your data for you, unlike $wpdb->query which requires you to sanitize your query with $wpdb->prepare. The difference between the two is $wpdb->query allows you to write your own SQL statement, where $wpdb->insert accepts an array and takes care of sanitizing/sql for you.

PHP/MySQL: How to create a comment section in your website

I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.

Here are some of the db fields i'm using.

id (auto incremented)
name
email
text
datetime
approved

When does System.gc() do something?

The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc(). This is the reason of this "may or may not decide to do a GC at that point".

Now, if you look at OpenJDK source code, which is the backbone of Oracle JVM, you will see that a call to System.gc() does start a GC cycle. If you use another JVM, such as J9, you have to check their documentation to find out the answer. For instance, Azul's JVM has a garbage collector that runs continuously, so a call to System.gc() won't do anything

Some other answer mention starting a GC in JConsole or VisualVM. Basically, these tools make a remote call to System.gc().

Usually, you don't want to start a garbage collection cycle from your code, as it messes up with the semantics of your application. Your application does some business stuff, the JVM takes care of memory management. You should keep those concerns separated (don't make your application do some memory management, focus on business).

However, there are few cases where a call to System.gc() might be understandable. Consider, for example, microbenchmarks. No-one wants to have a GC cycle to happen in the middle of a microbenchmark. So you may trigger a GC cycle between each measurement to make sure every measurement starts with an empty heap.

Add floating point value to android resources/values

There is a solution:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

Format = enclosing data type:

  • float
  • boolean
  • fraction
  • integer
  • ...

and type stands for:

Type = resource type (referenced with R.XXXXX.name):

  • color
  • dimen
  • string
  • style
  • etc...

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.


Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

Get the last item in an array

This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop().

arr.pop() is exactly as efficient as arr[arr.length-1], and both are the same speed as arr.push().

Therefore, you can get away with:

---EDITED [check that thePop isn't undefined before pushing]---

let thePop = arr.pop()
thePop && arr.push(thePop)

---END EDIT---

Which can be reduced to this (same speed [EDIT: but unsafe!]):

arr.push(thePop = arr.pop())    //Unsafe if arr empty

This is twice as slow as arr[arr.length-1], but you don't have to stuff around with an index. That's worth gold on any day.

Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]:

[Method]..............[ETUs 5 elems]...[ETU 1 million elems]

arr[arr.length - 1]      ------> 1              -----> 1

let myPop = arr.pop()
arr.push(myPop)          ------> 2              -----> 2

arr.slice(-1).pop()      ------> 36             -----> 924  

arr.slice(-1)[0]         ------> 36             -----> 924  

[...arr].pop()           ------> 120            -----> ~21,000,000 :)

The last three options, ESPECIALLY [...arr].pop(), get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop() probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.

How to insert default values in SQL table?

Just don't include the columns that you want to use the default value for in your insert statement. For instance:

INSERT INTO table1 (field1, field3) VALUES (5, 10);

...will take the default values for field2 and field4, and assign 5 to field1 and 10 to field3.

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

Getting Django admin url for an object

There's another way for the later versions, for example in 1.10:

{% load admin_urls %}
<a href="{% url opts|admin_urlname:'add' %}">Add user</a>
<a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>

Where opts is something like mymodelinstance._meta or MyModelClass._meta

One gotcha is you can't access underscore attributes directly in Django templates (like {{ myinstance._meta }}) so you have to pass the opts object in from the view as template context.

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

Android Studio emulator does not come with Play Store for API 23

What you need to do is update the config.ini file for the device and re-download the system image.

Update the following values in C:\Users\USER\.android\avd\DEVICE_ID\config.ini (on Windows) or ~/.android/avd/DEVICE_ID/config.ini (on Linux)

PlayStore.enabled = true
image.sysdir.1=system-images\android-27\google_apis_playstore\x86\
tag.display=Google Play
tag.id=google_apis_playstore

Then re-download the system image for the device from Android Studio > Tools > AVD Manager

That is all. Restart your device and you'll have the Play Store installed.

This has also been answered here: How to install Google Play app in Android Studio emulator?

How to install CocoaPods?

This works for OS X El Capitan 10.11.x

sudo gem install -n /usr/local/bin cocoapods
after this you can setup the pod using pod setup cmd and then move to your project directory and install pod

Customize Bootstrap checkboxes

Here you have an example styling checkboxes and radios using Font Awesome 5 free[

_x000D_
_x000D_
  /*General style*/_x000D_
  .custom-checkbox label, .custom-radio label {_x000D_
    position: relative;_x000D_
    cursor: pointer;_x000D_
    color: #666;_x000D_
    font-size: 30px;_x000D_
  }_x000D_
 .custom-checkbox input[type="checkbox"] ,.custom-radio input[type="radio"] {_x000D_
    position: absolute;_x000D_
    right: 9000px;_x000D_
  }_x000D_
   /*Custom checkboxes style*/_x000D_
  .custom-checkbox input[type="checkbox"]+.label-text:before {_x000D_
    content: "\f0c8";_x000D_
    font-family: "Font Awesome 5 Pro";_x000D_
    speak: none;_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    font-variant: normal;_x000D_
    text-transform: none;_x000D_
    line-height: 1;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    width: 1em;_x000D_
    display: inline-block;_x000D_
    margin-right: 5px;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:checked+.label-text:before {_x000D_
    content: "\f14a";_x000D_
    color: #2980b9;_x000D_
    animation: effect 250ms ease-in;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:disabled+.label-text {_x000D_
    color: #aaa;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:disabled+.label-text:before {_x000D_
    content: "\f0c8";_x000D_
    color: #ccc;_x000D_
  }_x000D_
_x000D_
   /*Custom checkboxes style*/_x000D_
  .custom-radio input[type="radio"]+.label-text:before {_x000D_
    content: "\f111";_x000D_
    font-family: "Font Awesome 5 Pro";_x000D_
    speak: none;_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    font-variant: normal;_x000D_
    text-transform: none;_x000D_
    line-height: 1;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    width: 1em;_x000D_
    display: inline-block;_x000D_
    margin-right: 5px;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:checked+.label-text:before {_x000D_
    content: "\f192";_x000D_
    color: #8e44ad;_x000D_
    animation: effect 250ms ease-in;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:disabled+.label-text {_x000D_
    color: #aaa;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:disabled+.label-text:before {_x000D_
    content: "\f111";_x000D_
    color: #ccc;_x000D_
  }_x000D_
_x000D_
  @keyframes effect {_x000D_
    0% {_x000D_
      transform: scale(0);_x000D_
    }_x000D_
    25% {_x000D_
      transform: scale(1.3);_x000D_
    }_x000D_
    75% {_x000D_
      transform: scale(1.4);_x000D_
    }_x000D_
    100% {_x000D_
      transform: scale(1);_x000D_
    }_x000D_
  }
_x000D_
<script src="https://kit.fontawesome.com/2a10ab39d6.js"></script>_x000D_
<div class="col-md-4">_x000D_
  <form>_x000D_
    <h2>1. Customs Checkboxes</h2>_x000D_
    <div class="custom-checkbox">_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check" checked> <span class="label-text">Option 01</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check"> <span class="label-text">Option 02</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check"> <span class="label-text">Option 03</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check" disabled> <span class="label-text">Option 04</span>_x000D_
                </label>_x000D_
      </div>_x000D_
    </div>_x000D_
  </form>_x000D_
</div>_x000D_
<div class="col-md-4">_x000D_
  <form>_x000D_
    <h2>2. Customs Radios</h2>_x000D_
    <div class="custom-radio">_x000D_
_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio" checked> <span class="label-text">Option 01</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio"> <span class="label-text">Option 02</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio"> <span class="label-text">Option 03</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio" disabled> <span class="label-text">Option 04</span>_x000D_
                </label>_x000D_
      </div>_x000D_
    </div>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I send JSON response in symfony2 controller

If your data is already serialized:

a) send a JSON response

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

c) send a JSON response

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

Create groups inside your Entities

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;

How to find list intersection?

This is an example when you need Each element in the result should appear as many times as it shows in both arrays.

def intersection(nums1, nums2):
    #example:
    #nums1 = [1,2,2,1]
    #nums2 = [2,2]
    #output = [2,2]
    #find first 2 and remove from target, continue iterating

    target, iterate = [nums1, nums2] if len(nums2) >= len(nums1) else [nums2, nums1] #iterate will look into target

    if len(target) == 0:
            return []

    i = 0
    store = []
    while i < len(iterate):

         element = iterate[i]

         if element in target:
               store.append(element)
               target.remove(element)

         i += 1


    return store

Add a month to a Date

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29

Unsupported major.minor version 52.0 when rendering in Android Studio

1?make sure Gradle Gradle JVM Version enter image description here

2?make sure ProjectSettings SDKs Veriosn enter image description here

Remove pandas rows with duplicate indices

Oh my. This is actually so simple!

grouped = df3.groupby(level=0)
df4 = grouped.last()
df4
                      A   B  rownum

2001-01-01 00:00:00   0   0       6
2001-01-01 01:00:00   1   1       7
2001-01-01 02:00:00   2   2       8
2001-01-01 03:00:00   3   3       3
2001-01-01 04:00:00   4   4       4
2001-01-01 05:00:00   5   5       5

Follow up edit 2013-10-29 In the case where I have a fairly complex MultiIndex, I think I prefer the groupby approach. Here's simple example for posterity:

import numpy as np
import pandas

# fake index
idx = pandas.MultiIndex.from_tuples([('a', letter) for letter in list('abcde')])

# random data + naming the index levels
df1 = pandas.DataFrame(np.random.normal(size=(5,2)), index=idx, columns=['colA', 'colB'])
df1.index.names = ['iA', 'iB']

# artificially append some duplicate data
df1 = df1.append(df1.select(lambda idx: idx[1] in ['c', 'e']))
df1
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233
#   c   0.275806 -0.078871  # <--- dup 1
#   e  -0.066680  0.607233  # <--- dup 2

and here's the important part

# group the data, using df1.index.names tells pandas to look at the entire index
groups = df1.groupby(level=df1.index.names)  
groups.last() # or .first()
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233

jQuery: Setting select list 'selected' based on text, failing strangely

setSelectedByText:function(eID,text) {
    var ele=document.getElementById(eID);
    for(var ii=0; ii<ele.length; ii++)
        if(ele.options[ii].text==text) { //Found!
            ele.options[ii].selected=true;
            return true;
        }
    return false;
},

Keytool is not recognized as an internal or external command

You are getting that error because the keytool executable is under the bin directory, not the lib directory in your example. And you will need to add the location of your keystore as well in the command line. There is a pretty good reference to all of this here - Jrun Help / Import certificates | Certificate stores | ColdFusion

The default truststore is the JRE's cacerts file. This file is typically located in the following places:

  • Server Configuration:

    cf_root/runtime/jre/lib/security/cacerts

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/lib/security/cacerts

  • Sun JDK installation:

    jdk_root/jre/lib/security/cacerts

  • Consult documentation for other J2EE application servers and JVMs


The keytool is part of the Java SDK and can be found in the following places:

  • Server Configuration:

    cf_root/runtime/bin/keytool

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/bin/keytool

  • Sun JDK installation:

    jdk_root/bin/keytool

  • Consult documentation for other J2EE application servers and JVMs

So if you navigate to the directory where the keytool executable is located your command line would look something like this:

keytool -list -v -keystore JAVA_HOME\jre\lib\security\cacert -storepass changeit

You will need to supply pathing information depending on where you run the keytool command from and where your certificate file resides.

Also, be sure you are updating the correct cacerts file that ColdFusion is using. In case you have more than one JRE installed on that server. You can verify the JRE ColdFusion is using from the administrator under the 'System Information'. Look for the Java Home line.

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Background thread with QThread in PyQt

PySide2 Solution:

Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.

In order to match PyQt5's behavior, you have to create the started signal yourself.

Here is an easy solution:

# Use this class instead of QThread
class QThread2(QThread):
    # Use this signal instead of "started"
    started2 = Signal()

    def __init__(self):
        QThread.__init__(self)
        self.started.connect(self.onStarted)

    def onStarted(self):
        self.started2.emit()

how to customize `show processlist` in mysql?

You can just capture the output and pass it through a filter, something like:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | sort -n -k12

The two greps strip out the header and trailer lines (others may be needed if there are other lines not containing useful information) and the sort is done based on the numeric field number 12 (I think that's right).

This one works for your immediate output:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | grep -v  '^[0-9][0-9]* rows in set '
    | grep -v '^ '
    | sort -n -k12

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

jQuery duplicate DIV into another DIV

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

Opacity CSS not working in IE8

None of the answers above worked for me, so I just gave my DIV tag a transparent background image instead, that worked perfectly for all browsers.

How to call an action after click() in Jquery?

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

How to read a local text file?

Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    <html>
    <head>
    <script>
      var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
          node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>

React JS Error: is not defined react/jsx-no-undef

You have to tell it which component you want to import by explicitly giving the class name..in your case it's Map

import Map from './Map';

class App extends Component{
    /*your code here...*/
}

Send JSON data from Javascript to PHP?

You can easily convert object into urlencoded string:

function objToUrlEncode(obj, keys) {
    let str = "";
    keys = keys || [];
    for (let key in obj) {
        keys.push(key);
        if (typeof (obj[key]) === 'object') {
            str += objToUrlEncode(obj[key], keys);
        } else {
            for (let i in keys) {
                if (i == 0) str += keys[0];
                else str += `[${keys[i]}]`
            }
            str += `=${obj[key]}&`;
            keys.pop();
        }
    }
    return str;
}

console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));

// key=value&obj[obj_key]=obj_value&

MVC pattern on Android

The actions, views and activities on Android are the baked-in way of working with the Android UI and are an implementation of the model–view–viewmodel (MVVM) pattern, which is structurally similar (in the same family as) model–view–controller.

To the best of my knowledge, there is no way to break out of this model. It can probably be done, but you would likely lose all the benefit that the existing model has and have to rewrite your own UI layer to make it work.

Input type=password, don't let browser remember the password

You can use JQuery, select the item by id:

$("input#Password").attr("autocomplete","off");

Or select the item by type:

$("input[type='password']").attr("autocomplete","off");

Or also:

You can use pure Javascript:

document.getElementById('Password').autocomplete = 'off';

sort csv by column

The reader acts like a generator. On a file with some fake data:

>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Using operator.itemgetter as Ignacio suggests:

>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]

Changing .gitconfig location on Windows

I'm no Git master, but from searching around the solution that worked easiest for me was to just go to C:\Program Files (x86)\Git\etc and open profile in a text editor.

There's an if statement on line 37 # Set up USER's home directory. I took out the if statement and put in the local directory that I wanted the gitconfig to be, then I just copied my existing gitconfig file (was on a network drive) to that location.

How to create a signed APK file using Cordova command line interface?

Step 1:

D:\projects\Phonegap\Example> cordova plugin rm org.apache.cordova.console --save

add the --save so that it removes the plugin from the config.xml file.

Step 2:

To generate a release build for Android, we first need to make a small change to the AndroidManifest.xml file found in platforms/android. Edit the file and change the line:

<application android:debuggable="true" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">

and change android:debuggable to false:

<application android:debuggable="false" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">

As of cordova 6.2.0 remove the android:debuggable tag completely. Here is the explanation from cordova:

Explanation for issues of type "HardcodedDebugMode": It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false.

If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

Step 3:

Now we can tell cordova to generate our release build:

D:\projects\Phonegap\Example> cordova build --release android

Then, we can find our unsigned APK file in platforms/android/ant-build. In our example, the file was platforms/android/ant-build/Example-release-unsigned.apk

Step 4:

Note : We have our keystore keystoreNAME-mobileapps.keystore in this Git Repo, if you want to create another, please proceed with the following steps.

Key Generation:

Syntax:

keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>

Egs:

keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000


keystore password? : xxxxxxx
What is your first and last name? :  xxxxxx
What is the name of your organizational unit? :  xxxxxxxx
What is the name of your organization? :  xxxxxxxxx
What is the name of your City or Locality? :  xxxxxxx
What is the name of your State or Province? :  xxxxx
What is the two-letter country code for this unit? :  xxx

Then the Key store has been generated with name as NAME-mobileapps.keystore

Step 5:

Place the generated keystore in

old version cordova

D:\projects\Phonegap\Example\platforms\android\ant-build

New version cordova

D:\projects\Phonegap\Example\platforms\android\build\outputs\apk

To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:

Syntax:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename> <Unsigned APK file> <Keystore Alias name>

Egs:

D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps

OR

D:\projects\Phonegap\Example\platforms\android\build\outputs\apk> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps

Enter KeyPhrase as 'xxxxxxxx'

This signs the apk in place.

Step 6:

Finally, we need to run the zip align tool to optimize the APK:

D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk 

OR

D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk

OR

D:\projects\Phonegap\Example\platforms\android\build\outputs\apk> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk

Now we have our final release binary called example.apk and we can release this on the Google Play Store.

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

How to create a new object instance from a Type

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

The Activator class has a generic variant that makes this a bit easier:

ObjectType instance = Activator.CreateInstance<ObjectType>();

How to get bean using application context in spring boot

You can use ApplicationContextAware.

ApplicationContextAware:

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.

There are a few methods for obtaining a reference to the application context. You can implement ApplicationContextAware as in the following example:

package hello;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    } 

 public ApplicationContext getContext() {
        return applicationContext;
    }
    
}

Update:

When Spring instantiates beans, it looks for ApplicationContextAware implementations, If they are found, the setApplicationContext() methods will be invoked.

In this way, Spring is setting current applicationcontext.

Code snippet from Spring's source code:

private void invokeAwareInterfaces(Object bean) {
        .....
        .....
 if (bean instanceof ApplicationContextAware) {                
  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
   }
}

Once you get the reference to Application context, you get fetch the bean whichever you want by using getBean().

MS Access - execute a saved query by name in VBA

You should investigate why VBA can't find queryname.

I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.

CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.

Edit: You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.

Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

what's the correct way to send a file from REST web service to client?

Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.

Client to call REST webservice:

package in.india.client.downloadfiledemo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;

public class DownloadFileClient {

    private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";

    public DownloadFileClient() {

        try {
            Client client = Client.create();
            WebResource objWebResource = client.resource(BASE_URI);
            ClientResponse response = objWebResource.path("/")
                    .type(MediaType.TEXT_HTML).get(ClientResponse.class);

            System.out.println("response : " + response);
            if (response.getStatus() == Status.OK.getStatusCode()
                    && response.hasEntity()) {
                MultiPart objMultiPart = response.getEntity(MultiPart.class);
                java.util.List<BodyPart> listBodyPart = objMultiPart
                        .getBodyParts();
                BodyPart filenameBodyPart = listBodyPart.get(0);
                BodyPart fileLengthBodyPart = listBodyPart.get(1);
                BodyPart fileBodyPart = listBodyPart.get(2);

                String filename = filenameBodyPart.getEntityAs(String.class);
                String fileLength = fileLengthBodyPart
                        .getEntityAs(String.class);
                File streamedFile = fileBodyPart.getEntityAs(File.class);

                BufferedInputStream objBufferedInputStream = new BufferedInputStream(
                        new FileInputStream(streamedFile));

                byte[] bytes = new byte[objBufferedInputStream.available()];

                objBufferedInputStream.read(bytes);

                String outFileName = "D:/"
                        + filename;
                System.out.println("File name is : " + filename
                        + " and length is : " + fileLength);
                FileOutputStream objFileOutputStream = new FileOutputStream(
                        outFileName);
                objFileOutputStream.write(bytes);
                objFileOutputStream.close();
                objBufferedInputStream.close();
                File receivedFile = new File(outFileName);
                System.out.print("Is the file size is same? :\t");
                System.out.println(Long.parseLong(fileLength) == receivedFile
                        .length());
            }
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new DownloadFileClient();
    }
}

Service to response client:

package in.india.service.downloadfiledemo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.multipart.MultiPart;

@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {

    @GET
    public Response getFile() {

        java.io.File objFile = new java.io.File(
                "D:/DanGilbert_2004-480p-en.mp4");
        MultiPart objMultiPart = new MultiPart();
        objMultiPart.type(new MediaType("multipart", "mixed"));
        objMultiPart
                .bodyPart(objFile.getName(), new MediaType("text", "plain"));
        objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
                "plain"));
        objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));

        return Response.ok(objMultiPart).build();

    }
}

JAR needed:

jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DownloadFileDemo</display-name>
    <servlet>
        <display-name>JAX-RS REST Servlet</display-name>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name> 
             <param-value>in.india.service.downloadfiledemo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

I faced the same problem in eclipse with tomcat7 with the error javax.servlet cannot be resolved. If I select the server in targeted runtime mode and build project again, the error get's resolved.

SPA best practices for authentication and session management

You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.

The Basic Auth / Session ID can be stolen via:

  • MITM attack (Man-In-The-Middle) - without SSL/HTTPS
  • An intruder gaining access to a user's computer
  • XSS

By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.

The new (more secure) flow would be:

Login

  • User logs in and sends login credentials to API (over SSL/HTTPS)
  • API receives login credentials
  • If valid:
    • Register a new session in the database Read update
    • Encrypt User ID, Session ID, IP address, timestamp, etc. in a JWT with a private key.
  • API sends the JWT token back to the client (over SSL/HTTPS)
  • Client receives the JWT token and stores in localStorage/cookie

Every request to API

  • User sends a HTTP request to API (over SSL/HTTPS) with the stored JWT token in the HTTP header
  • API reads HTTP header and decrypts JWT token with its private key
  • API validates the JWT token, matches the IP address from the HTTP request with the one in the JWT token and checks if session has expired
  • If valid:
    • Return response with requested content
  • If invalid:
    • Throw exception (403 / 401)
    • Flag intrusion in the system
    • Send a warning email to the user.

Updated 30.07.15:

JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).

I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).

Updated 17.07.16:

JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

How to implement my very own URI scheme on Android

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

How to create exe of a console application

Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.

Laravel Blade html image

If you use bootstrap, you might use this -

 <img src="{{URL::asset('/image/propic.png')}}" alt="profile Pic" height="200" width="200">

note: inside public folder create a new folder named image then put your images there. Using URL::asset() you can directly access to the public folder.

Why is vertical-align:text-top; not working in CSS

You can use margin-top: -50% to move the text all the way to the top of the div.

margin-top: -50%;

Is it a bad practice to use an if-statement without curly braces?

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

add string to String array

First, this code here,

string [] scripts = new String [] ("test3","test4","test5");

should be

String[] scripts = new String [] {"test3","test4","test5"};

Please read this tutorial on Arrays

Second,

Arrays are fixed size, so you can't add new Strings to above array. You may override existing values

scripts[0] = string1;

(or)

Create array with size then keep on adding elements till it is full.

If you want resizable arrays, consider using ArrayList.

JUnit test for System.out.println()

Instead of redirecting System.out, I would refactor the class that uses System.out.println() by passing a PrintStream as a collaborator and then using System.out in production and a Test Spy in the test. That is, use Dependency Injection to eliminate the direct use of the standard output stream.

In Production

ConsoleWriter writer = new ConsoleWriter(System.out));

In the Test

ByteArrayOutputStream outSpy = new ByteArrayOutputStream();
ConsoleWriter writer = new ConsoleWriter(new PrintStream(outSpy));
writer.printSomething();
assertThat(outSpy.toString(), is("expected output"));

Discussion

This way the class under test becomes testable by a simple refactoring, without having the need for indirect redirection of the standard output or obscure interception with a system rule.

select2 changing items dynamically

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

Commit only part of a file in Git

Tried out git add -p filename.x, but on a mac, I found gitx (http://gitx.frim.nl/ or https://github.com/pieter/gitx) to be much easier to commit exactly the lines I wanted to.

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

How to change JAVA.HOME for Eclipse/ANT

In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable. Instead it is set to the home directory of the project's JRE.

To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.

To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab. Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.

If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

Diagrams are back as of the June 11 2019 release

Download latest

as stated:

Yes, we’ve heard the feedback; Database Diagrams is back.

SQL Server Management Studio (SSMS) 18.1 is now generally available


?? Latest Version Does Not Included It ??

Sadly, the last version of SSMS to have database diagrams as a feature was version v17.9.

Since that version, the newer preview versions starting at v18.* have, in their words "...feature has been deprecated".

Hope is not lost though, for one can still download and use v17.9 to use database diagrams which as an aside for this question is technically not a ER diagramming tool.


As of this writing it is unclear if the release version of 18 will have the feature, I hope so because it is a feature I use extensively.

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

try this

provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);

Bye.

How to open the command prompt and insert commands using Java?

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

jQuery processes the data attribute and converts the values into strings.

Adding processData: false to your options object fixes the error, but I'm not sure if it fixes the problem.

Demo: http://jsfiddle.net/eHmSr/1/

How can I disable mod_security in .htaccess file?

With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess. The only option is to contact tech support and ask them to alter the configuration for you.

Reset the database (purge all), then seed a database

If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all (or delete_all) in the seed.db file to clean out a table before your MyModel.create!(...) statements load the data. Then, you can redo the db:seed operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)

There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...

AutoComplete TextBox in WPF

You can find one in the WPF Toolkit, which is also available via NuGet.

This article demos how to create a textbox which can auto-suggest items at runtime based on input, in this case, disk drive folders. WPF AutoComplete Folder TextBox

Also take a look at this nice Reusable WPF Autocomplete TextBox, it was for me very usable.

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

  • Remove all code references to System.Net.*

  • in the package window,

    Install-Package Microsoft.AspNet.WebApi.Client

  • Clean and rebuild your project

Maximum call stack size exceeded on npm install

In my case, update to the newest version:

npm install -g npm

What is Activity.finish() method doing exactly?

Also notice if you call finish() after an intent you can't go back to the previous activity with the "back" button

startActivity(intent);
finish();

Browser detection in JavaScript?

I found something interesting and quicker way. IE supports navigator.systemLanguage which returns "en-US" where other browsers return undefined.

<script>
    var lang = navigator.systemLanguage;
    if (lang!='en-US'){document.write("Well, this is not internet explorer");}
    else{document.write("This is internet explorer");}
</script>

How to move a marker in Google Maps API

Here is the full code with no errors

        <!DOCTYPE html>
        <html>
        <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }

          #map-canvas 
        { 
        height: 400px; 
        width: 500px;
        }
        </style>

   </script>
        <script type="text/javascript">
        function initialize() {

            var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
                myOptions = {
                    zoom: 5,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                    },
                map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
                marker = new google.maps.Marker( {icon: {
                    url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
                    // This marker is 20 pixels wide by 32 pixels high.
                    size: new google.maps.Size(20, 32),
                    // The origin for this image is (0, 0).
                    origin: new google.maps.Point(0, 0),
                    // The anchor for this image is the base of the flagpole at (0, 32).
                    anchor: new google.maps.Point(0, 32)
                }, position: myLatLng, map: map} );

            marker.setMap( map );
            moveBus( map, marker );

        }



        function moveBus( map, marker ) {
            setTimeout(() => {
                marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
                map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
            }, 1000)


        };



        </script>
        </head>

        <body onload="initialize()">
        <script type="text/javascript">
        //moveBus();
        </script>

        <script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
        <div id="map-canvas" style="height: 500px; width: 500px;"></div>



        </body>
        </html>

Convert Base64 string to an image file?

An easy way I'm using:

file_put_contents($output_file, file_get_contents($base64_string));

This works well because file_get_contents can read data from a URI, including a data:// URI.

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

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

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

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

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

Visual Studio Error: (407: Proxy Authentication Required)

This helped in my case :

  1. close VS instance
  2. open Control Panel\User Accounts\Credential Manager
  3. Remove TFS related credentials from vault

This is just a hack. You need to do it regulary ... :-(

Best regards,

Alexander

Selenium WebDriver How to Resolve Stale Element Reference Exception?

After deep investigation of the problem I found that error occurs selecting DIV elements that were added for Bootstrap only. Chrome browser removes such DIVS and the error occurs. It is enough to step down and select real element for fixing an error. For example, my modal dialog has structure:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

Selecting div class="modal-body" generates an error, selecting form ... works as it would.

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

To remove the blue overlay on mobiles, you can use one of the following:

-webkit-tap-highlight-color: transparent; /* transparent with keyword */
-webkit-tap-highlight-color: rgba(0,0,0,0); /* transparent with rgba */
-webkit-tap-highlight-color: hsla(0,0,0,0); /* transparent with hsla */
-webkit-tap-highlight-color: #00000000; /* transparent with hex with alpha */
-webkit-tap-highlight-color: #0000; /* transparent with short hex with alpha */

However, unlike other properties, you can't use

-webkit-tap-highlight-color: none; /* none keyword */

In DevTools, this will show up as an 'invalid property value' or something.


To remove the blue/black/orange outline when focused, use this:

:focus {
    outline: none; /* no outline - for most browsers */
    box-shadow: none; /* no box shadow - for some browsers or if you are using Bootstrap */
}

The reason why I removed the box-shadow is because Bootsrap (and some browsers) sometimes add it to focused elements, so you can remove it using this.

But if anyone is navigating with a keyboard, they will get very confused indeed, because they rely on this outline to navigate. So you can replace it instead

:focus {
    outline: 100px dotted #f0f; /* 100px dotted pink outline */
}

You can target taps on mobile using :hover or :active, so you could use those to help, possibly. Or it could get confusing.


Full code:

element {
    -webkit-tap-highlight-color: transparent; /* remove tap highlight */
}
element:focus {
    outline: none; /* remove outline */
    box-shadow: none; /* remove box shadow */
}

Other information:

  • If you would like to customise the -webkit-tap-highlight-color then you should set it to a semi-transparent color so the element underneath doesn't get hidden when tapped
  • Please don't remove the outline from focused elements, or add some more styles for them.
  • -webkit-tap-highlight-color has not got great browser support and is not standard. You can still use it, but watch out!

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

What is the difference between the kernel space and the user space?

Kernel Space and User Space are logical spaces.

Most of the modern processors are designed to run in different privileged mode. x86 machines can run in 4 different privileged modes. enter image description here

And a particular machine instruction can be executed when in/above particular privileged mode.

Because of this design you are giving a system protection or sand-boxing the execution environment.

Kernel is a piece of code, which manages your hardware and provide system abstraction. So it needs to have access for all the machine instruction. And it is most trusted piece of software. So i should be executed with the highest privilege. And Ring level 0 is the most privileged mode. So Ring Level 0 is also called as Kernel Mode.

User Application are piece of software which comes from any third party vendor, and you can't completely trust them. Someone with malicious intent can write a code to crash your system if he had complete access to all the machine instruction. So application should be provided with access to limited set of instructions. And Ring Level 3 is the least privileged mode. So all your application run in that mode. Hence that Ring Level 3 is also called User Mode.

Note: I am not getting Ring Levels 1 and 2. They are basically modes with intermediate privilege. So may be device driver code are executed with this privilege. AFAIK, linux uses only Ring Level 0 and 3 for kernel code execution and user application respectively.

So any operation happening in kernel mode can be considered as kernel space. And any operation happening in user mode can be considered as user space.

SSH configuration: override the default username

man ssh_config says

User

Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.

How to manually set REFERER header in Javascript?

You can change the value of the referrer in the HTTP header using the Web Request API.

It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.

Your code will be something like this :

    chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
    var newRef = "http://new-referer/path";
    var hasRef = false;
    for(var n in details.requestHeaders){
        hasRef = details.requestHeaders[n].name == "Referer";
        if(hasRef){
            details.requestHeaders[n].value = newRef;
         break;
        }
    }
    if(!hasRef){
        details.requestHeaders.push({name:"Referer",value:newRef});
    }
    return {requestHeaders:details.requestHeaders};
},
{
    urls:["http://target/*"]
},
[
    "requestHeaders",
    "blocking"
]);

urls : It acts as a request filter, and invokes the listener only for certain requests.

For more info: https://developer.chrome.com/extensions/webRequest

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars.

There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take [] as an example. Whenever there is an [ there must be a matching ], which is simple enough for a regex "\[.*\]".

What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets.

This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count.


I ended up writing "Regular Expression Limitations" about this.

What is the $? (dollar question mark) variable in shell scripting?

$? is used to find the return value of the last executed command. Try the following in the shell:

ls somefile
echo $?

If somefile exists (regardless whether it is a file or directory), you will get the return value thrown by the ls command, which should be 0 (default "success" return value). If it doesn't exist, you should get a number other then 0. The exact number depends on the program.

For many programs you can find the numbers and their meaning in the corresponding man page. These will usually be described as "exit status" and may have their own section.

How to Scroll Down - JQuery

Try This:

window.scrollBy(0,180); // horizontal and vertical scroll increments

Determine what attributes were changed in Rails after_save callback?

To anyone seeing this later on, as it currently (Aug. 2017) tops google: It is worth mentioning, that this behavior will be altered in Rails 5.2, and has deprecation warnings as of Rails 5.1, as ActiveModel::Dirty changed a bit.

What do I change?

If you're using attribute_changed? method in the after_*-callbacks, you'll see a warning like:

DEPRECATION WARNING: The behavior of attribute_changed? inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute? instead. (called from some_callback at /PATH_TO/app/models/user.rb:15)

As it mentions, you could fix this easily by replacing the function with saved_change_to_attribute?. So for example, name_changed? becomes saved_change_to_name?.

Likewise, if you're using the attribute_change to get the before-after values, this changes as well and throws the following:

DEPRECATION WARNING: The behavior of attribute_change inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute instead. (called from some_callback at /PATH_TO/app/models/user.rb:20)

Again, as it mentions, the method changes name to saved_change_to_attribute which returns ["old", "new"]. or use saved_changes, which returns all the changes, and these can be accessed as saved_changes['attribute'].

Spring Boot: How can I set the logging level with application.properties?

If you are on Spring Boot then you can directly add following properties in application.properties file to set logging level, customize logging pattern and to store logs in the external file.

These are different logging levels and its order from minimum << maximum.

OFF << FATAL << ERROR << WARN << INFO << DEBUG << TRACE << ALL

# To set logs level as per your need.
logging.level.org.springframework = debug
logging.level.tech.hardik = trace

# To store logs to external file
# Here use strictly forward "/" slash for both Windows, Linux or any other os, otherwise, its won't work.      
logging.file=D:/spring_app_log_file.log

# To customize logging pattern.
logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"

Please pass through this link to customize your log more vividly.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Difference between "and" and && in Ruby?

The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo

The same thing works for || and or.

Reading column names alone in a csv file

here is the code to print only the headers or columns of the csv file.

import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)

Another method with pandas

import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

How to send email from Terminal?

If all you need is a subject line (as in an alert message) simply do:

mailx -s "This is all she wrote" < /dev/null "myself@myaddress"

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I just renamed the package and it worked for me.

Or if you are using Ionic, you could delete the application and try again, this happens when ionic detects that the app you are deploying is not coming from the same build. It often happen when you change from pc.

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

PHP - Insert date into mysql

How to debug SQL queries when you stuck

Print you query and run it directly in mysql or phpMyAdmin

$date = "2012-08-06";
$query= "INSERT INTO data_table (title, date_of_event) 
             VALUES('". $_POST['post_title'] ."',
                    '". $date ."')";
echo $query;
mysql_query($query) or die(mysql_error()); 

that way you can make sure that the problem is not in your PHP-script, but in your SQL-query

How to submit questions on SQ-queries

Make sure that you provided enough closure

  • Table schema
  • Query
  • Error message is any

PHP split alternative?

Had the same issue, but my code must work on both PHP 5 & PHP 7..

Here is my piece of code, which solved this.. Input a date in dmY format with one of delimiters "/ . -"

<?php
function DateToEN($date){
  if ($date!=""){
    list($d, $m, $y) = function_exists("split") ?  split("[/.-]", $date) : preg_split("/[\/\.\-]+/", $date);
    return $y."-".$m."-".$d;
  }else{
    return false;
  }
}
?>