Programs & Examples On #Intermediate language

An intermediate language, in compiler design, is a low-level language that typically resembles an idealized assembly language, often a textual representation of bytecode for a virtual machine. For .NET's CIL, use the [cil] tag.

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

How do I find the current directory of a batch file, and then use it for the path?

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

How do I reference a cell within excel named range?

I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read. I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row()) but I found it a bit too long for my tastes.

However, in this particular case, I found that using Sales alone works just as well - Excel (2010 here) just gets the corresponding row automatically.

It appears to work with other ranges too; for example let's say I have values in A2:A11 which I name Sales, I can just use =Sales*0.21 in B2:11 and it will use the same row value, giving out ten different results.


I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)

erlative named range

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

The String[] args parameter is an array of Strings passed as parameters when you are running your application through command line in the OS.

So, imagine you have compiled and packaged a myApp.jar Java application. You can run your app by double clicking it in the OS, of course, but you could also run it using command line way, like (in Linux, for example):

user@computer:~$ java -jar myApp.jar

When you call your application passing some parameters, like:

user@computer:~$ java -jar myApp.jar update notify

The java -jar command will pass your Strings update and notify to your public static void main() method.

You can then do something like:

System.out.println(args[0]); //Which will print 'update'
System.out.println(args[1]); //Which will print 'notify'

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

Efficient way to remove ALL whitespace from String?

This is fastest way I know of, even though you said you didn't want to use regular expressions:

Regex.Replace(XML, @"\s+", "")

pros and cons between os.path.exists vs os.path.isdir

Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases.

How to "crop" a rectangular image into a square with CSS?

Using background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).

If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.

I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.

It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:

1) You can change the recursion limit with sys.setrecursionlimit(n) until the maximum allowed for your platform:

sys.setrecursionlimit(limit):

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.

Find nginx version?

Try running command 'whereis nginx'. It will give you the correct path of the nginx installation, in my case nginx is installed in '/usr/local/sbin', so I need to check if this path exists in output of command 'echo $PATH'. If you don't find the path in the output of this command, then you can add this.

Suppose the output of my 'echo $PATH' command is this:

  ~$ echo $PATH
/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin

Then I can append the path '/usr/local/sbin' in $PATH by following command:

~$ echo 'export PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin"' >> $HOME/.bashrc

Please check your nginx installation path may differ from mine, but the steps for adding them are same.

"Repository does not have a release file" error

In my case the cause was Ubuntu version no longer supported by Canonical. I was able to upgrade to still supported LTS with 2 steps:

1) Manually update repo links from "in.ubuntu" to "old-releases.ubuntu". 1.1) Installed all outstanding updates 2) do-release-upgrade was able to take from this point and do actual upgrade

IMHO, this is safer method then just updating repositories to next supported ubuntu, since do-release-upgrade have chance to prevent upgrade that could fail, and may be able to diagnose a problem for you.

How can I get Apache gzip compression to work?

In my case i have used following code for enabling gzip compression in apache web server.

  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

Cannot delete or update a parent row: a foreign key constraint fails

If there are more than one job having the same advertiser_id, then your foreign key should be:

ALTER TABLE `jobs`
ADD CONSTRAINT `advertisers_ibfk_1` 
FOREIGN KEY (`advertiser_id`) 
REFERENCES `advertisers` (`advertiser_id`);

Otherwise (if its the other way round in your case), if you want the rows in advertiser to be automatically deleted if the row in job is deleted add the 'ON DELETE CASCADE' option to the end of your foreign key:

ALTER TABLE `advertisers`
ADD CONSTRAINT `advertisers_ibfk_1` 
FOREIGN KEY (`advertiser_id`) 
REFERENCES `jobs` (`advertiser_id`)
ON DELETE CASCADE;

Check out Foreign Key constraints

C# declare empty string array

Arrays' constructors are different. Here are some ways to make an empty string array:

var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()

(sorry, on mobile)

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

An unsigned 1 byte number can contain the range [0-255] inclusive. So when you see 255, it is mostly because programmers think in base 10 (get the joke?) :)

Actually, for a while, 255 was the largest size you could give a VARCHAR in MySQL, and there are advantages to using VARCHAR over TEXT with indexing and other issues.

OAuth: how to test with local URLs?

Taking Google OAuth as reference

  • In your OAuth client Tab

    1. Add your App URI example(http://localhost:3000) to Authorized JavaScript origins URIs
  • In your OAuth consent screen

    1. Add mywebsite.com to Authorized domains
  • Edit the hosts file on windows or linux Windows C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts to add 127.0.0.1 mywebsite.com (N.B. Comment out any if there is any other 127.0.0.1)

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

Windows Batch Files: if else

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

Generating a UUID in Postgres for Insert statement?

The answer by Craig Ringer is correct. Here's a little more info for Postgres 9.1 and later…

Is Extension Available?

You can only install an extension if it has already been built for your Postgres installation (your cluster in Postgres lingo). For example, I found the uuid-ossp extension included as part of the installer for Mac OS X kindly provided by EnterpriseDB.com. Any of a few dozen extensions may be available.

To see if the uuid-ossp extension is available in your Postgres cluster, run this SQL to query the pg_available_extensions system catalog:

SELECT * FROM pg_available_extensions;

Install Extension

To install that UUID-related extension, use the CREATE EXTENSION command as seen in this this SQL:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Beware: I found the QUOTATION MARK characters around extension name to be required, despite documentation to the contrary.

The SQL standards committee or Postgres team chose an odd name for that command. To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION".

Verify Installation

You can verify the extension was successfully installed in the desired database by running this SQL to query the pg_extension system catalog:

SELECT * FROM pg_extension;

UUID as default value

For more info, see the Question: Default value for UUID column in Postgres

The Old Way

The information above uses the new Extensions feature added to Postgres 9.1. In previous versions, we had to find and run a script in a .sql file. The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extension for less work on the part of the user/consumer of the extension. See my blog post for more discussion.

Types of UUIDs

By the way, the code in the Question calls the function uuid_generate_v4(). This generates a type known as Version 4 where nearly all of the 128 bits are randomly generated. While this is fine for limited use on smaller set of rows, if you want to virtually eliminate any possibility of collision, use another "version" of UUID.

For example, the original Version 1 combines the MAC address of the host computer with the current date-time and an arbitrary number, the chance of collisions is practically nil.

For more discussion, see my Answer on related Question.

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

Permutation of array

Here is how you can print all permutations in 10 lines of code:

public class Permute{
    static void permute(java.util.List<Integer> arr, int k){
        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            permute(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            System.out.println(java.util.Arrays.toString(arr.toArray()));
        }
    }
    public static void main(String[] args){
        Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
    }
}

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element. The tricky part is that after recursive call you must swap i-th element with first element back, otherwise you could get repeated values at the first spot. By swapping it back we restore order of elements (basically you do backtracking).

Iterators and Extension to the case of repeated values

The drawback of previous algorithm is that it is recursive, and does not play nicely with iterators. Another issue is that if you allow repeated elements in your input, then it won't work as is.

For example, given input [3,3,4,4] all possible permutations (without repetitions) are

[3, 3, 4, 4]
[3, 4, 3, 4]
[3, 4, 4, 3]
[4, 3, 3, 4]
[4, 3, 4, 3]
[4, 4, 3, 3]

(if you simply apply permute function from above you will get [3,3,4,4] four times, and this is not what you naturally want to see in this case; and the number of such permutations is 4!/(2!*2!)=6)

It is possible to modify the above algorithm to handle this case, but it won't look nice. Luckily, there is a better algorithm (I found it here) which handles repeated values and is not recursive.

First note, that permutation of array of any objects can be reduced to permutations of integers by enumerating them in any order.

To get permutations of an integer array, you start with an array sorted in ascending order. You 'goal' is to make it descending. To generate next permutation you are trying to find the first index from the bottom where sequence fails to be descending, and improves value in that index while switching order of the rest of the tail from descending to ascending in this case.

Here is the core of the algorithm:

//ind is an array of integers
for(int tail = ind.length - 1;tail > 0;tail--){
    if (ind[tail - 1] < ind[tail]){//still increasing

        //find last element which does not exceed ind[tail-1]
        int s = ind.length - 1;
        while(ind[tail-1] >= ind[s])
            s--;

        swap(ind, tail-1, s);

        //reverse order of elements in the tail
        for(int i = tail, j = ind.length - 1; i < j; i++, j--){
            swap(ind, i, j);
        }
        break;
    }
}

Here is the full code of iterator. Constructor accepts an array of objects, and maps them into an array of integers using HashMap.

import java.lang.reflect.Array;
import java.util.*;
class Permutations<E> implements  Iterator<E[]>{

    private E[] arr;
    private int[] ind;
    private boolean has_next;

    public E[] output;//next() returns this array, make it public

    Permutations(E[] arr){
        this.arr = arr.clone();
        ind = new int[arr.length];
        //convert an array of any elements into array of integers - first occurrence is used to enumerate
        Map<E, Integer> hm = new HashMap<E, Integer>();
        for(int i = 0; i < arr.length; i++){
            Integer n = hm.get(arr[i]);
            if (n == null){
                hm.put(arr[i], i);
                n = i;
            }
            ind[i] = n.intValue();
        }
        Arrays.sort(ind);//start with ascending sequence of integers


        //output = new E[arr.length]; <-- cannot do in Java with generics, so use reflection
        output = (E[]) Array.newInstance(arr.getClass().getComponentType(), arr.length);
        has_next = true;
    }

    public boolean hasNext() {
        return has_next;
    }

    /**
     * Computes next permutations. Same array instance is returned every time!
     * @return
     */
    public E[] next() {
        if (!has_next)
            throw new NoSuchElementException();

        for(int i = 0; i < ind.length; i++){
            output[i] = arr[ind[i]];
        }


        //get next permutation
        has_next = false;
        for(int tail = ind.length - 1;tail > 0;tail--){
            if (ind[tail - 1] < ind[tail]){//still increasing

                //find last element which does not exceed ind[tail-1]
                int s = ind.length - 1;
                while(ind[tail-1] >= ind[s])
                    s--;

                swap(ind, tail-1, s);

                //reverse order of elements in the tail
                for(int i = tail, j = ind.length - 1; i < j; i++, j--){
                    swap(ind, i, j);
                }
                has_next = true;
                break;
            }

        }
        return output;
    }

    private void swap(int[] arr, int i, int j){
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public void remove() {

    }
}

Usage/test:

    TCMath.Permutations<Integer> perm = new TCMath.Permutations<Integer>(new Integer[]{3,3,4,4,4,5,5});
    int count = 0;
    while(perm.hasNext()){
        System.out.println(Arrays.toString(perm.next()));
        count++;
    }
    System.out.println("total: " + count);

Prints out all 7!/(2!*3!*2!)=210 permutations.

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

MySQL TEXT vs BLOB vs CLOB

It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.

http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

Data Type   Date Type   Storage Required
(CLOB)      (BLOB)

TINYTEXT    TINYBLOB    L + 1 bytes, where L < 2**8  (255)
TEXT        BLOB        L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT  MEDIUMBLOB  L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT    LONGBLOB    L + 4 bytes, where L < 2**32 (4 GB)

where L stands for the byte length of a string

File count from a folder

System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;

how to Call super constructor in Lombok

If child class has more members, than parent, it could be done not very clean, but short way:

@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
    private @NonNull String fullName;
    private @NonNull String email;
    ... 

    public User(Integer id, String fullName, String email, ....) {
        this(fullName, email, ....);
        this.id = id;
    }
}

@Data
@AllArgsConstructor
abstract public class BaseEntity {
   protected Integer id;

   public boolean isNew() {
      return id == null;
   }
}

How to add icon to mat-icon-button

All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.

You'll need to import MatButtonModule and MatIconModule in your app module file.

From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.

<button mat-icon-button>
  <mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>

In your case, use

<mat-icon>thumb_up</mat-icon>

As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Or import it in your global styles.scss.

@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

As it mentions, any icon font can be used with the mat-icon component.

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

Check if a variable is a string in JavaScript

Just to expand on @DRAX's answer, I'd do this:

function isWhitespaceEmptyString(str)
{
    //RETURN:
    //      = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
    return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
}

It will account also for nulls and undefined types, and it will take care of non-string types, such as 0.

How to query first 10 rows and next time query other 10 rows from table

You can use postgresql Cursors

BEGIN;
DECLARE C CURSOR FOR where * FROM msgtable where cdate='18/07/2012';

Then use

FETCH 10 FROM C;

to fetch 10 rows.

Finnish with

COMMIT;

to close the cursor.

But if you need to make a query in different processes, LIMIT and OFFSET as suggested by @Praveen Kumar is better

"ImportError: no module named 'requests'" after installing with pip

One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.

Type python in the prompt, and press the tab key to see what versions of Python in your environment.

How to get the value of an input field using ReactJS?

your error is because of you use class and when use class we need to bind the functions with This in order to work well. anyway there are a lot of tutorial why we should "this" and what is "this" do in javascript.

if you correct your submit button it should be work:

<button type="button" onClick={this.onSubmit.bind(this)} className="btn">Save</button>

and also if you want to show value of that input in console you should use var title = this.title.value;

Correct way to convert size in bytes to KB, MB, GB in JavaScript

According to Aliceljm's answer, I removed 0 after decimal:

function formatBytes(bytes, decimals) {
    if(bytes== 0)
    {
        return "0 Byte";
    }
    var k = 1024; //Or 1 kilo = 1000
    var sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i];
}

Which passwordchar shows a black dot (•) in a winforms textbox?

Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:

this.txtPassword.UseSystemPasswordChar = true;

CSS transition when class removed

The @jfriend00's answer helps me to understand the technique to animate only remove class (not add).

A "base" class should have transition property (like transition: 2s linear all;). This enables animations when any other class is added or removed on this element. But to disable animation when other class is added (and only animate class removing) we need to add transition: none; to the second class.

Example

CSS:

.issue {
  background-color: lightblue;
  transition: 2s linear all;
}

.recently-updated {
  background-color: yellow;
  transition: none;
}

HTML:

<div class="issue" onclick="addClass()">click me</div>

JS (only needed to add class):

var timeout = null;

function addClass() {
  $('.issue').addClass('recently-updated');
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  timeout = setTimeout(function () {
    $('.issue').removeClass('recently-updated');
  }, 1000);
}

plunker of this example.

With this code only removing of recently-updated class will be animated.

How to convert / cast long to String?

Just do this:

String strLong = Long.toString(longNumber);

Using success/error/finally/catch with Promises in AngularJS

What type of granularity are you looking for? You can typically get by with:

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);

I've found that "finally" and "catch" are better off when chaining multiple promises.

Counting number of occurrences in column?

Just adding some extra sorting if needed

=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)

enter image description here

HTML Table width in percentage, table rows separated equally

Use the property table-layout:fixed; on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.

<table style='table-layout:fixed;'>
    <tbody>
        <tr>
            <td>gobble de gook</td>
            <td>mibs</td>
        </tr>
    </tbody>
</table>

Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.

angular-cli server - how to specify default port

For @angular/cli v6.2.1

The project configuration file angular.json is able to handle multiple projects (workspaces) which can be individually served.

ng config projects.my-test-project.targets.serve.options.port 4201

Where the my-test-project part is the project name what you set with the ng new command just like here:

$ ng new my-test-project
$ cd my-test-project
$ ng config projects.my-test-project.targets.serve.options.port 4201
$ ng serve
** Angular Live Development Server is listening on localhost:4201, open your browser on http://localhost:4201/ **

Legacy:

I usually use the ng set command to change the Angular CLI settings for project level.

ng set defaults.serve.port=4201

It changes change your .angular.cli.json and adds the port settings as it mentioned earlier.

After this change you can use simply ng serve and it going to use the prefered port without the need of specifying it every time.

How to get root view controller?

Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

CSS: Creating textured backgrounds

If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('') section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.

Example link: http://www.base64-image.de/

When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:

url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')

With your texture images, you'll want to employ a similar process.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Add:

fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

Or:

fprintf($file, "\xEF\xBB\xBF");

Before writing any content to CSV file.

Example:

<?php
$file = fopen( "file.csv", "w");
fprintf( $file, "\xEF\xBB\xBF");
fputcsv( $file, ["english", 122, "?????"]);
fclose($file);

use localStorage across subdomains

This is how:

[November 2020 Update: This solution relies on being able to set document.domain. The ability to do that has now been deprecated, unfortunately.]

For sharing between subdomains of a given superdomain (e.g. example.com), there's a technique you can use in that situation. It can be applied to localStorage, IndexedDB, SharedWorker, BroadcastChannel, etc, all of which offer shared functionality between same-origin pages, but for some reason don't respect any modification to document.domain that would let them use the superdomain as their origin directly.

(1) Pick one "main" domain to for the data to belong to: i.e. either https://example.com or https://www.example.com will hold your localStorage data. Let's say you pick https://example.com.

(2) Use localStorage normally for that chosen domain's pages.

(3) On all https://www.example.com pages (the other domain), use javascript to set document.domain = "example.com";. Then also create a hidden <iframe>, and navigate it to some page on the chosen https://example.com domain (It doesn't matter what page, as long as you can insert a very little snippet of javascript on there. If you're creating the site, just make an empty page specifically for this purpose. If you're writing an extension or a Greasemonkey-style userscript and so don't have any control over pages on the example.com server, just pick the most lightweight page you can find and insert your script into it. Some kind of "not found" page would probably be fine).

(4) The script on the hidden iframe page need only (a) set document.domain = "example.com";, and (b) notify the parent window when this is done. After that, the parent window can access the iframe window and all its objects without restriction! So the minimal iframe page is something like:

<!doctype html>
<html>
<head>
  <script>
    document.domain = "example.com";
    window.parent.iframeReady();  // function defined & called on parent window
  </script>
</head>
<body></body>
</html>

If writing a userscript, you might not want to add externally-accessible functions such as iframeReady() to your unsafeWindow, so instead a better way to notify the main window userscript might be to use a custom event:

    window.parent.dispatchEvent(new CustomEvent("iframeReady"));

Which you'd detect by adding a listener for the custom "iframeReady" event to your main page's window.

(NOTE: You need to set document.domain = "example.com" even if the iframe's domain is already example.com: Assigning a value to document.domain implicitly sets the origin's port to null, and both ports must match for the iframe and its parent to be considered same-origin. See the note here: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Changing_origin)

(5) Once the hidden iframe has informed its parent window that it's ready, script in the parent window can just use iframe.contentWindow.localStorage, iframe.contentWindow.indexedDB, iframe.contentWindow.BroadcastChannel, iframe.contentWindow.SharedWorker instead of window.localStorage, window.indexedDB, etc. ...and all these objects will be scoped to the chosen https://example.com origin - so they'll have the this same shared origin for all of your pages!

The most awkward part of this technique is that you have to wait for the iframe to load before proceeding. So you can't just blithely start using localStorage in your DOMContentLoaded handler, for example. Also you might want to add some error handling to detect if the hidden iframe fails to load correctly.

Obviously, you should also make sure the hidden iframe is not removed or navigated during the lifetime of your page... OTOH I don't know what the result of that would be, but very likely bad things would happen.

And, a caveat: setting/changing document.domain can be blocked using the Feature-Policy header, in which case this technique will not be usable as described.


However, there is a significantly more-complicated generalization of this technique, that can't be blocked by Feature-Policy, and that also allows entirely unrelated domains to share data, communications, and shared workers (i.e. not just subdomains off a common superdomain). @Mayank Jain already described it in their answer, namely:

The general idea is that, just as above, you create a hidden iframe to provide the correct origin for access; but instead of then just grabbing the iframe window's properties directly, you use script inside the iframe to do all of the work, and you communicate between the iframe and your main window only using postMessage() and addEventListener("message",...).

This works because postMessage() can be used even between different-origin windows. But it's also significantly more complicated because you have to pass everything through some kind of messaging infrastructure that you create between the iframe and the main window, rather than just using the localStorage, IndexedDB, etc. APIs directly in your main window's code.

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

How to make phpstorm display line numbers by default?

All the guys are right. I am just bringing the the current soultion with the images.

  1. Go to File-> Settings

enter image description here

  1. In the box in the top right corner type in line numbers, just below that choose Editor->Appearance, from the right checkboxes, find Show line numbers and check it.

  2. After that hit Apply and OK

enter image description here

That should do the trick.

My version of PhpStorm is 6.0.3

Android Facebook integration with invalid key hash

I experienced the same problem. I made a short research on the possible reasons for this strange behavior and I found the following:

  • During the first execution of a new Facebook app, it will allow connection/login even if you don't specify any key hashes.

  • For me, the tutorial which Facebook provided didn't generate the correct key hash, because it was giving the wrong configuration. When executing:

    keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
    base64
    

make sure you check all properties - the HOMEPATH, the existence of the keystore, etc. Maybe you also have to provide password.

  • What generated the proper configuration was the solution suggested by @Mahendran.

  • Also, if you see the error originally posted (http://i.stack.imgur.com/58q3v.png), most probably the key hash you see on the screen is your real one. If nothing else works, try inputting it in Facebook.

I got all those results with: Windows 7 64-bit edition, Android Studio 1.2.2, JDK 7.

How to force JS to do math instead of putting two strings together

its really simple just

var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)

this forces javascript to multiply because there is no confusion for * sign in javascript.

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

Dynamically changing font size of UILabel

Swift 2.0 Version:

private func adapteSizeLabel(label: UILabel, sizeMax: CGFloat) {
     label.numberOfLines = 0
     label.lineBreakMode = NSLineBreakMode.ByWordWrapping
     let maximumLabelSize = CGSizeMake(label.frame.size.width, sizeMax);
     let expectSize = label.sizeThatFits(maximumLabelSize)
     label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, expectSize.width, expectSize.height)
}

Search for all files in project containing the text 'querystring' in Eclipse

Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.

More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

alt text
(source: avajava.com)

Where is the WPF Numeric UpDown control?

Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro. Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

<mah:NumericUpDown x:Name="NumericUpDown" ... /> 

Enjoy the full extensibility of the object (Bindings, triggers and so on...).

How to get Django and ReactJS to work together?

The first approach is building separate Django and React apps. Django will be responsible for serving the API built using Django REST framework and React will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for React (to serve static files).

The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the React frontend and to expose the REST API. So you'll need to integrate React and Webpack with Django, these are the steps that you can follow to do that

First generate your Django project then inside this project directory generate your React application using the React CLI

For Django project install django-webpack-loader with pip:

pip install django-webpack-loader

Next add the app to installed apps and configure it in settings.py by adding the following object

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': '',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Then add a Django template that will be used to mount the React application and will be served by Django

{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React </title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

Then add an URL in urls.py to serve this template

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [

    url(r'^', TemplateView.as_view(template_name="main.html")),

]

If you start both the Django and React servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your React application able to generate the stats file.

Go ahead and navigate inside your React app then install webpack-bundle-tracker

npm install webpack-bundle-tracker --save

Then eject your Webpack configuration and go to config/webpack.config.dev.js then add

var BundleTracker  = require('webpack-bundle-tracker');
//...

module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This add BundleTracker plugin to Webpack and instruct it to generate webpack-stats.json in the parent folder.

Make sure also to do the same in config/webpack.config.prod.js for production.

Now if you re-run your React server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by React dev server.

There are some other things to. You can find more information from this tutorial.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I agree with Beytan Kurt.

I had 503 thrown for both the Central Admin site as well as the SharePoint landing page. In both cases the Passwords were expired.

After resetting the password in the AD, and refreshing the Identity, CA worked but the SharePoint landing page threw a 500 error.

It turned out that the .Net Framework Version was set to V4.0. I changed it to V2.0 and it worked.

Remember after each change you need to recycle the appropriate app pool.

Getting a random value from a JavaScript array

~~ is much faster than Math.Floor(), so when it comes to performance optimization while producing output using UI elements, ~~ wins the game. MORE INFO

var rand = myArray[~~(Math.random() * myArray.length)];

But if you know that the array is going to have millions of elements than you might want to reconsider between Bitwise Operator and Math.Floor(), as bitwise operator behave weirdly with large numbers. See below example explained with the output. MORE INFO(deadlink)

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

mysql data directory location

If you install MySQL via homebrew on MacOS, you might need to delete your old data directory /usr/local/var/mysql. Otherwise, it will fail during the initialization process with the following error:

==> /usr/local/Cellar/mysql/8.0.16/bin/mysqld --initialize-insecure --user=hohoho --basedir=/usr/local/Cellar/mysql/8.0.16 --datadir=/usr/local/var/mysql --tmpdir=/tmp
2019-07-17T16:30:51.828887Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld (mysqld 8.0.16) initializing of server in progress as process 93487
2019-07-17T16:30:51.830375Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-07-17T16:30:51.830381Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-07-17T16:30:51.830410Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-07-17T16:30:51.830540Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld: Shutdown complete (mysqld 8.0.16)  Homebrew.

Django: Redirect to previous page after login

I encountered the same problem. This solution allows me to keep using the generic login view:

urlpatterns += patterns('django.views.generic.simple',
    (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
)

Get int value from enum in C#

Use:

Question question = Question.Role;
int value = question.GetHashCode();

It will result in value == 2.

This is only true if the enum fits inside an int.

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

What is Node.js' Connect, Express and "middleware"?

The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).

What Node.js comes with

http / https createServer which simply takes a callback(req,res) e.g.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

What connect adds

Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework

The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect(); you get a function app that can:

  1. Can handle a request and return a response. This is because you basically get this function
  2. Has a member function .use (source) to manage plugins (that comes from here because of this simple line of code).

Because of 1.) you can do the following :

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

Combine with 2.) and you get:

var connect = require('connect');

// Create a connect dispatcher
var app = connect()
      // register a middleware
      .use(function (req, res, next) { next(); });

// Register with http
http.createServer(app)
    .listen(3000);

Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

So, you can do:

var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

It's still your good old http.createServer with a plugin framework on top.

What ExpressJS adds

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  1. Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
  2. A use function to register middleware.
  3. A utility listen function to register itself with http

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

  1. Has view engine support.
  2. Has top level verbs (get/post etc.) for its router.
  3. Has application settings support.

The middleware is shared

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

Which one should you use?

My opinion: you are informed enough ^based on above^ to make your own choice.

  • Use http.createServer if you are creating something like connect / expressjs from scratch.
  • Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
  • Use ExpressJS if you are authoring websites.

Most people should just use ExpressJS.

What's wrong about the accepted answer

These might have been true as some point in time, but wrong now:

that inherits an extended version of http.Server

Wrong. It doesn't extend it and as you have seen ... uses it

Express does to Connect what Connect does to the http module

Express 4.0 doesn't even depend on connect. see the current package.json dependencies section

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I set the artifact baseName so it is independent of the build project name, which allows me to achieve what you want:

jar {
    baseName "core"
}

With this property set, even if my project name is "foo", when I run gradle install, the artifact is published with the name core instead of foo.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Find root build.gradle file and add google maven repo inside allprojects tag

repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
            url 'https://maven.google.com/' 
            name 'Google'
        }
    } 

It's better to use specific version instead of variable version

compile 'com.android.support:appcompat-v7:27.0.0'

If you're using Android Plugin for Gradle 3.0.0 or latter version

repositories {
      mavenLocal()
      mavenCentral()
      google()        //---> Add this
} 

and inject dependency in this way :

implementation 'com.android.support:appcompat-v7:27.0.0'

Convert CString to const char*

I recommendo to you use TtoC from ConvUnicode.h

const CString word= "hello";
const char* myFile = TtoC(path.GetString());

It is a macro to do conversions per Unicode

generate days from date range

Accepted answer didn't work for PostgreSQL (syntax error at or near "a").

The way you do this in PostgreSQL is by using generate_series function, i.e.:

SELECT day::date
FROM generate_series('2010-01-20', '2010-01-24', INTERVAL '1 day') day;

    day
------------
 2010-01-20
 2010-01-21
 2010-01-22
 2010-01-23
 2010-01-24
(5 rows)

FileNotFoundException while getting the InputStream object from HttpURLConnection

The solution:
just change localhost for the IP of your PC
if you want to know this: Windows+r > cmd > ipconfig
example: http://192.168.0.107/directory/service/program.php?action=sendSomething
just replace 192.168.0.107 for your own IP (don't try 127.0.0.1 because it's same as localhost)

VB.Net: Dynamically Select Image from My.Resources

Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.

PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name") 

Storing C++ template function definitions in a .CPP file

This should work fine everywhere templates are supported. Explicit template instantiation is part of the C++ standard.

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

Programmatically go back to the previous fragment in the backstack

By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.

adding new fragment:

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

How to get a value from the last inserted row?

for example:

 Connection conn = null;
            PreparedStatement sth = null;
            ResultSet rs =null;
            try {
                conn = delegate.getConnection();
                sth = conn.prepareStatement(INSERT_SQL);
                sth.setString(1, pais.getNombre());
                sth.executeUpdate();
                rs=sth.getGeneratedKeys();
                if(rs.next()){
                    Integer id = (Integer) rs.getInt(1);
                    pais.setId(id);
                }
            } 

with ,Statement.RETURN_GENERATED_KEYS);" no found.

How do I remove repeated elements from ArrayList?

Time Complexity : O(n) : Without Set

private static void removeDup(ArrayList<String> listWithDuplicateElements) {
    System.out.println(" Original Duplicate List :" + listWithDuplicateElements);
    List<String> listWithoutDuplicateElements = new ArrayList<>(listWithDuplicateElements.size());

    listWithDuplicateElements.stream().forEach(str -> {
        if (listWithoutDuplicateElements.indexOf(str) == -1) {
            listWithoutDuplicateElements.add(str);
        }
    });     

    System.out.println(" Without Duplicate List :" + listWithoutDuplicateElements);
}

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.

The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.

You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

IE6/IE7 css border on select element

Just add an doctype declaration before the html tag

ex.: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd">

It is gonna work in JSP files as well. For further info: HTML Doctype Declaration

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Retrieve the maximum length of a VARCHAR column in SQL Server

For IBM Db2 its LENGTH, not LEN:

SELECT MAX(LENGTH(Desc)) FROM table_name;

How can I escape white space in a bash loop list?

find . -print0|while read -d $'\0' file; do echo "$file"; done

Get refresh token google api

This is complete code in PHP using google official SDK

$client = new Google_Client();
## some need parameter
$client->setApplicationName('your application name');
$client->setClientId('****************');
$client->setClientSecret('************');
$client->setRedirectUri('http://your.website.tld/complete/url2redirect');
$client->setScopes('https://www.googleapis.com/auth/userinfo.email');
## these two lines is important to get refresh token from google api
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); # this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

How can I delete derived data in Xcode 8?

(Working in Xcode 11 and 12)

You can go to File > Workspace Settings if you are in a workspace environment or File > Project Settings for a regular project environment.

Then click over the little grey arrow under Derived data section and select your project folder to delete it.

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Putty: Getting Server refused our key Error

When using Cpanel you can check if the key is authorized in

SSH Access >> Public keys >> Manage >> Authorize or Deauthorize.

How to get the last row of an Oracle a table

The last row according to a strict total order over composite key K(k1, ..., kn):

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

Given the special case where K is simple (i.e. not composite), the above is shortened to:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

Note that for this query to return just one row the key must order without ties. If ties are allowed, this query will return all the rows tied with the greatest key.

Specify system property to Maven project

I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>${maven.exec.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>${exec.main-class}</mainClass>
                <systemProperties>
                    <systemProperty>
                        <key>myproperty</key>
                        <value>myvalue</value>
                    </systemProperty>
                </systemProperties>
            </configuration>
        </plugin>

How to detect idle time in JavaScript elegantly?

You can use the below mentioned solution

var idleTime;
$(document).ready(function () {
         reloadPage();
        $('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
            clearTimeout(idleTime);
            reloadPage();
        });
});
function reloadPage() {
    clearTimeout(idleTime);
    idleTime = setTimeout(function () {
        location.reload();
    }, 3000);
}

multiple plot in one figure in Python

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

How to get all subsets of a set? (powerset)

def powerset(lst):
    return reduce(lambda result, x: result + [subset + [x] for subset in result],
                  lst, [[]])

Windows batch file file download from a URL

There's a standard Windows component which can achieve what you're trying to do: BITS. It has been included in Windows since XP and 2000 SP3.

Run:

bitsadmin.exe /transfer "JobName" http://download.url/here.exe C:\destination\here.exe

The job name is simply the display name for the download job - set it to something that describes what you're doing.

get specific row from spark dataframe

There is a scala way (if you have a enough memory on working machine):

val arr = df.select("column").rdd.collect
println(arr(100))

If dataframe schema is unknown, and you know actual type of "column" field (for example double), than you can get arr as following:

val arr = df.select($"column".cast("Double")).as[Double].rdd.collect

Calling ASP.NET MVC Action Methods from JavaScript

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

c++ Read from .csv file

a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume

getline(file, genero, ' ') ; 

it is newline \n

so change that line to

getline(file, genero); // \n is default delimiter

Disable mouse scroll wheel zoom on embedded Google Maps

I stumbled upon this issue myself and used some of a mashup of two very useful answers on this question: czerasz's answer and massa's answer.

They both have a lot of truth, but somewhere in my tests, I found out that one didn't work for mobile and had poor IE support (only works on IE11). This is the solution by nathanielperales, then extended by czerasz, which relies on pointer-events css and that doesn't work on mobile (there is no pointer in mobile) and it doesn't work on any version of IE that is not v11. Normally I wouldn't care less, but there are a ton of users out there and we want consistent functionality, so I went with the overlay solution, using a wrapper to make it easier to code.

So, my markup looks like this:

<div class="map embed-container">
  <div id="map-notice" style="display: block;"> {Tell your users what to do!} </div>
  <div class="map-overlay" style="display: block;"></div>
  <iframe style="width:100%" src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3785.684302567802!2d-66.15578327375803!3d18.40721382009222!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8c036a35d02b013f%3A0x5962cad95b9ec7f8!2sPlaza+Del+Sol!5e0!3m2!1sen!2spr!4v1415284687548" width="633" height="461" frameborder="0"></iframe>
</div>

Then the styles are like this:

.map.embed-container {
  position:relative;
}

.map.embed-container #map-notice{
  position:absolute;
  right:0;
  top:0;
  background-color:rgb(100,100,100);/*for old IE browsers with no support for rgba()*/
  background-color: rgba(0,0,0,.50);
  color: #ccc;
  padding: 8px;
}
.map.embed-container .map-overlay{
  height:100%;
  width:100%;
  position:absolute;
  z-index:9999;
  background-color:rgba(0,0,0,0.10);/*should be transparent but this will help you see where the overlay is going in relation with the markup*/
}

Lastly the script:

//using jquery...
var onMapMouseleaveHandler = function (event) {
  $('#map-notice').fadeIn(500);
  var elemento = $$(this);
  elemento.on('click', onMapClickHandler);
  elemento.off('mouseleave', onMapMouseleaveHandler);
  $('.map-overlay').fadeIn(500);
}

var onMapClickHandler = function (event) {
  $('#map-notice').fadeOut(500);
  var elemento = $$(this);
  elemento.off('click', onMapClickHandler);
  $('.map-overlay').fadeOut(500);
  elemento.on('mouseleave', onMapMouseleaveHandler);
}
$('.map.embed-container').on('click', onMapClickHandler);

I also added my tested solution in a GitHub gist, if you like to get stuff from there...

Class file has wrong version 52.0, should be 50.0

If you are using javac to compile, and you get this error, then remove all the .class files

rm *.class     # On Unix-based systems

and recompile.

javac fileName.java

How to check if NSString begins with a certain character

NSString *stringWithoutAsterisk(NSString *string) {
    NSRange asterisk = [string rangeOfString:@"*"];
    return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}

How to read a local text file?

After the introduction of fetch api in javascript, reading file contents could not be simpler.

reading a text file

fetch('file.txt')
  .then(response => response.text())
  .then(text => console.log(text))
  // outputs the content of the text file

reading a json file

fetch('file.json')
  .then(response => response.json())
  .then(jsonResponse => console.log(jsonResponse))     
   // outputs a javascript object from the parsed json

Update 30/07/2018 (disclaimer):

This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

Update-2 (disclaimer):

This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

Run a .bat file using python code

So I do in Windows 10 and Python 3.7.1 (tested):

import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)

Easiest way to flip a boolean value?

Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:

Example:

bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;

What are unit tests, integration tests, smoke tests, and regression tests?

I just wanted to add and give some more context on why we have these levels of test, what they really mean with examples

Mike Cohn in his book “Succeeding with Agile” came up with the “Testing Pyramid” as a way to approach automated tests in projects. There are various interpretations of this model. The model explains what kind of automated tests need to be created, how fast they can give feedback on the application under test and who writes these tests. There are basically 3 levels of automated testing needed for any project and they are as follows.

Unit Tests- These test the smallest component of your software application. This could literally be one function in a code which computes a value based on some inputs. This function is part of several other functions of the hardware/software codebase that makes up the application.

For example - Let’s take a web based calculator application. The smallest components of this application that needs to be unit tested could be a function that performs addition, another that performs subtraction and so on. All these small functions put together makes up the calculator application.

Historically developer writes these tests as they are usually written in the same programming language as the software application. Unit testing frameworks such as JUnit and NUnit (for java), MSTest (for C# and .NET) and Jasmine/Mocha (for JavaScript) are used for this purpose.

The biggest advantage of unit tests are, they run really fast underneath the UI and we can get quick feedback about the application. This should comprise more than 50% of your automated tests.

API/Integration Tests- These test various components of the software system together. The components could include testing databases, API’s (Application Programming Interface), 3rd party tools and services along with the application.

For example - In our calculator example above, the web application may use a database to store values, use API’s to do some server side validations and it may use a 3rd party tool/service to publish results to the cloud to make it available across different platforms.

Historically a developer or technical QA would write these tests using various tools such as Postman, SoapUI, JMeter and other tools like Testim.

These run much faster than UI tests as they still run underneath the hood but may consume a little more time than unit tests as it has to check the communication between various independent components of the system and ensure they have seamless integration. This should comprise more that 30% of the automated tests.

UI Tests- Finally, we have tests that validate the UI of the application. These tests are usually written to test end to end flows through the application.

For example - In the calculator application, an end to end flow could be, opening up the browser-> Entering the calculator application url -> Logging in with username/password -> Opening up the calculator application -> Performing some operations on the calculator -> verifying those results from the UI -> Logging out of the application. This could be one end to end flow that would be a good candidate for UI automation.

Historically, technical QA’s or manual testers write UI tests. They use open source frameworks like Selenium or UI testing platforms like Testim to author, execute and maintain the tests. These tests give more visual feedback as you can see how the tests are running, the difference between the expected and actual results through screenshots, logs, test reports.

The biggest limitation of UI tests is, they are relatively slow compared to Unit and API level tests. So, it should comprise only 10-20% of the overall automated tests.

The next two types of tests can vary based on your project but the idea is-

Smoke Tests

This can be a combination of the above 3 levels of testing. The idea is to run it during every code check in and ensure the critical functionalities of the system are still working as expected; after the new code changes are merged. They typically need to run with 5 - 10 mins to get faster feedback on failures

Regression Tests

They usually are run once a day at least and cover various functionalities of the system. They ensure the application is still working as expected. They are more details than the smoke tests and cover more scenarios of the application including the non-critical ones.

Wait some seconds without blocking UI execution

In my case I needed to do this because I had passed a method to the thread I was waiting for and that caused the lock becuase the metod was run on the GUI thread and the thread code called that method sometimes.

Task<string> myTask = Task.Run(() => {
    // Your code or method call
    return "Maybe you want to return other datatype, then just change it.";
});
// Some other code maybe...
while (true)
{
    myTask.Wait(10);
    Application.DoEvents();
    if (myTask.IsCompleted) break;
}

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

Correctly determine if date string is a valid date in that format

Validate with checkdate function:

$date = '2019-02-30';

$date_parts = explode( '-', $date );

if(checkdate( $date_parts[1], $date_parts[2], $date_parts[0] )){
    //date is valid
}else{
    //date is invalid
}

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

How to stop the task scheduled in java.util.Timer class

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

Return positions of a regex match() in Javascript?

In modern browsers, you can accomplish this with string.matchAll().

The benefit to this approach vs RegExp.exec() is that it does not rely on the regex being stateful, as in @Gumbo's answer.

_x000D_
_x000D_
let regexp = /bar/g;
let str = 'foobarfoobar';

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});
_x000D_
_x000D_
_x000D_

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Depending on the actual value and what exception fits best:

If this is not precise enough, just derive your own exception class from ArgumentException.

Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException is a reasonable choice.

Best way to list files in Java, sorted by Date Modified?

This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only once rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).

It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).

class Pair implements Comparable {
    public long t;
    public File f;

    public Pair(File file) {
        f = file;
        t = file.lastModified();
    }

    public int compareTo(Object o) {
        long u = ((Pair) o).t;
        return t < u ? -1 : t == u ? 0 : 1;
    }
};

// Obtain the array of (file, timestamp) pairs.
File[] files = directory.listFiles();
Pair[] pairs = new Pair[files.length];
for (int i = 0; i < files.length; i++)
    pairs[i] = new Pair(files[i]);

// Sort them by timestamp.
Arrays.sort(pairs);

// Take the sorted pairs and extract only the file part, discarding the timestamp.
for (int i = 0; i < files.length; i++)
    files[i] = pairs[i].f;

How can I join multiple SQL tables using the IDs?

Simple INNER JOIN VIEW code....

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;

How to declare an array of strings in C++?

One possiblity is to use a NULL pointer as a flag value:

const char *list[] = {"dog", "cat", NULL};
for (char **iList = list; *iList != NULL; ++iList)
{
    cout << *iList;
}

How to restart a node.js server

During development the best way to restart server for seeing changes made is to use nodemon

npm install nodemon -g

nodemon [your app name]

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Check nodemon git repo: https://github.com/remy/nodemon

How do I override nested NPM dependency versions?

I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:

  1. Remove the nested dependency under the 'requires' section in package-lock.json
  2. Add the updated dependency under DevDependencies in package.json, so that modules that require it will still be able to access it.
  3. npm i

Catch an exception thrown by an async void method

Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.

public async Task DoFoo()
    {
        try
        {
            return await Foo();
        }
        catch (ProtocolException ex)
        {
            /* Exception with chronological stack trace */     
        }
    }

Convert integers to strings to create output filenames at run time

I've tried @Alejandro and @user2361779 already but it gives me an unsatisfied result such as file 1.txt or file1 .txt instead of file1.txt. However i find the better solution:

...
integer :: i
character(len=5) :: char_i     ! use your maximum expected len
character(len=32) :: filename

write(char_i, '(I5)') i        ! convert integer to char
write(filename, '("path/to/file/", A, ".dat")') trim(adjustl(char_i))
...

Explanation:

e.g. set i = 10 and write(char_i, '(I5)') i

char_i                gives  "   10" ! this is original value of char_i

adjustl(char_i)       gives  "10   " ! adjust char_i to the left

trim(adjustl(char_i)) gives  "10"    ! adjust char_i to the left then remove blank space on the right

I think this is a simplest solution that give you a dynamical length filename without any legacy blank spaces from integer to string conversion process.

Plugin with id 'com.google.gms.google-services' not found

In build.gradle(Module:app) add this code

dependencies {
    ……..
    compile 'com.google.android.gms:play-services:10.0.1’
    ……  
}

If you still have a problem after that, then add this code in build.gradle(Module:app)

defaultConfig {
    ….
    …...
    multiDexEnabled true
}


dependencies {
    …..
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.android.support:multidex:1.0.1'
}

Send JSON via POST in C# and Receive the JSON returned?

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

(Edit: Adding JSON from question for clarity)

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

With two classes representing the JSON-Structure you posted that may look like this:

public class Credentials
{
    [JsonProperty("agent")]
    public Agent Agent { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }
}

public class Agent
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("version")]
    public int Version { get; set; }
}

you could have a method like this, which would do your POST request:

var payload = new Credentials { 
    Agent = new Agent { 
        Name = "Agent Name",
        Version = 1 
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();

        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
}

Django: Calling .update() on a single model instance retrieved by .get()?

I am using the following code in such cases:

obj, created = Model.objects.get_or_create(id=some_id)

if not created:
   resp= "It was created"
else:
   resp= "OK"
   obj.save()

How do you tell if a string contains another string in POSIX sh?

case $(pwd) in
  *path) echo "ends with path";;
  path*) echo "starts with path";;
  *path*) echo "contains path";;
  *) echo "this is the default";;
esac

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

Python script to do something at the same time every day

I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.

You will have to install their Python library:

pip install schedule

This is modified from their sample program:

import schedule
import time

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

You will need to put your own function in place of job and run it with nohup, e.g.:

nohup python2.7 MyScheduledProgram.py &

Don't forget to start it again if you reboot.

Unzip files programmatically in .net

I found out about this one (Unzip package on NuGet) today, since I ran into a hard bug in DotNetZip, and I realized there hasn't been really that much work done on DotNetZip for the last two years.

The Unzip package is lean, and it did the job for me - it didn't have the bug that DotNetZip had. Also, it was a reasonably small file, relying upon the Microsoft BCL for the actual decompression. I could easily make adjustments which I needed (to be able to keep track of the progress while decompressing). I recommend it.

How to hide app title in android?

You can do it programatically: Or without action bar

//It's enough to remove the line
     requestWindowFeature(Window.FEATURE_NO_TITLE);

//But if you want to display  full screen (without action bar) write too

     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     WindowManager.LayoutParams.FLAG_FULLSCREEN);

     setContentView(R.layout.your_activity);

Javascript to set hidden form value on drop down change

$(function() {
$('#myselect').change(function() {
   $('#myhidden').val =$("#myselect option:selected").text();
    });
});

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

How do you iterate through every file/directory recursively in standard C++?

You can use ftw(3) or nftw(3) to walk a filesystem hierarchy in C or C++ on POSIX systems.

How to add text to JFrame?

You can add a multi-line label with the following:

JLabel label = new JLabel("My label");

label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");

From here, simply add the label to the frame using the add() method, and you're all set!

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

The manner in which you cause your program to terminate and print information is entirely up to you.

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Use mvn spring-boot:run. No mvn sprint-boot:run Error Writing.

When should iteritems() be used instead of items()?

dict.iteritems was removed because dict.items now does the thing dict.iteritems did in python 2.x and even improved it a bit by making it an itemview.

How do you loop in a Windows batch file?

If you want to do something x times, you can do this:

Example (x = 200):

FOR /L %%A IN (1,1,200) DO (
  ECHO %%A
)

1,1,200 means:

  • Start = 1
  • Increment per step = 1
  • End = 200

What is the syntax for Typescript arrow functions with generics?

so late, but with ES6 no need extends it still work for me.... :)

let getArray = <T>(items: T[]): T[] => {
    return new Array<T>().concat(items)
}

let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)

How could others, on a local network, access my NodeJS app while it's running on my machine?

If you are using a router then:

  1. Replace server.listen(yourport, 'localhost'); with server.listen(yourport, 'your ipv4 address');

    in my machine it is

     server.listen(3000, '192.168.0.3');
    
  2. Make sure your port is forwarded to your ipv4 address.

  3. On Windows Firewall, tick all on Node.js:Server-side JavaScript.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Conditional WHERE clause in SQL Server

This seemed easier to think about where either of two parameters could be passed into a stored procedure. It seems to work:

SELECT * 
FROM x 
WHERE CONDITION1
AND ((@pol IS NOT NULL AND x.PolicyNo = @pol) OR (@st IS NOT NULL AND x.State = @st))
AND OTHERCONDITIONS

How do I create ColorStateList programmatically?

Sometimes this will be enough:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);

How do I enable saving of filled-in fields on a PDF form?

There is a setting inside the PDF file that turns on the allow saving with data bit. However, it requires that you have a copy of Adobe Acrobat installed to change the bit.

The only other option is to print it to a PDF print driver which would save the data merged with the pdf file.

UPDATE: The relevant information from adobe is at: http://www.adobeforums.com/webx?13@@.3bbb313f/7

How can I add some small utility functions to my AngularJS application?

Here is a simple, compact and easy to understand method I use.
First, add a service in your js.

app.factory('Helpers', [ function() {
      // Helper service body

        var o = {
        Helpers: []

        };

        // Dummy function with parameter being passed
        o.getFooBar = function(para) {

            var valueIneed = para + " " + "World!";

            return valueIneed;

          };

        // Other helper functions can be added here ...

        // And we return the helper object ...
        return o;

    }]);

Then, in your controller, inject your helper object and use any available function with something like the following:

app.controller('MainCtrl', [

'$scope',
'Helpers',

function($scope, Helpers){

    $scope.sayIt = Helpers.getFooBar("Hello");
    console.log($scope.sayIt);

}]);

How do I check if a cookie exists?

For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie module!

First install the cookie module (and save as a dependency):

npm install --save cookie

Then import and use:

import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed) 
    console.log(parsed.cookie1);

How can I reduce the waiting (ttfb) time

If you are using PHP, try using <?php flush(); ?> after </head> and before </body> or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.

More info

How to send a html email with the bash command "sendmail"?

-a option?

Cf. man page:

-a file
          Attach the given file to the message.

Result:

Content-Type: text/html: No such file or directory

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

Table-level backup

Create new filegroup, put this table on it, and backup this filegroup only.

How do I auto size a UIScrollView to fit its content

Set dynamic content size like this.

 self.scroll_view.contentSize = CGSizeMake(screen_width,CGRectGetMaxY(self.controlname.frame)+20);

What is the difference between Serialization and Marshaling?

Here's more specific examples of both:

Serialization Example:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct {
    char value[11];
} SerializedInt32;

SerializedInt32 SerializeInt32(int32_t x) 
{
    SerializedInt32 result;

    itoa(x, result.value, 10);

    return result;
}

int32_t DeserializeInt32(SerializedInt32 x) 
{
    int32_t result;

    result = atoi(x.value);

    return result;
}

int main(int argc, char **argv)
{    
    int x;   
    SerializedInt32 data;
    int32_t result;

    x = -268435455;

    data = SerializeInt32(x);
    result = DeserializeInt32(data);

    printf("x = %s.\n", data.value);

    return result;
}

In serialization, data is flattened in a way that can be stored and unflattened later.

Marshalling Demo:

(MarshalDemoLib.cpp)

#include <iostream>
#include <string>

extern "C"
__declspec(dllexport)
void *StdCoutStdString(void *s)
{
    std::string *str = (std::string *)s;
    std::cout << *str;
}

extern "C"
__declspec(dllexport)
void *MarshalCStringToStdString(char *s)
{
    std::string *str(new std::string(s));

    std::cout << "string was successfully constructed.\n";

    return str;
}

extern "C"
__declspec(dllexport)
void DestroyStdString(void *s)
{
    std::string *str((std::string *)s);
    delete str;

    std::cout << "string was successfully destroyed.\n";
}

(MarshalDemo.c)

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(int argc, char **argv)
{
    void *myStdString;

    LoadLibrary("MarshalDemoLib");

    myStdString = ((void *(*)(char *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "MarshalCStringToStdString"
    ))("Hello, World!\n");

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "StdCoutStdString"
    ))(myStdString);

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "DestroyStdString"
    ))(myStdString);    
}

In marshaling, data does not necessarily need to be flattened, but it needs to be transformed to another alternative representation. all casting is marshaling, but not all marshaling is casting.

Marshaling doesn't require dynamic allocation to be involved, it can also just be transformation between structs. For example, you might have a pair, but the function expects the pair's first and second elements to be other way around; you casting/memcpy one pair to another won't do the job because fst and snd will get flipped.

#include <stdio.h>

typedef struct {
    int fst;
    int snd;
} pair1;

typedef struct {
    int snd;
    int fst;
} pair2;

void pair2_dump(pair2 p)
{
    printf("%d %d\n", p.fst, p.snd);
}

pair2 marshal_pair1_to_pair2(pair1 p)
{
    pair2 result;
    result.fst = p.fst;
    result.snd = p.snd;
    return result;
}

pair1 given = {3, 7};

int main(int argc, char **argv)
{    
    pair2_dump(marshal_pair1_to_pair2(given));

    return 0;
}

The concept of marshaling becomes especially important when you start dealing with tagged unions of many types. For example, you might find it difficult to get a JavaScript engine to print a "c string" for you, but you can ask it to print a wrapped c string for you. Or if you want to print a string from JavaScript runtime in a Lua or Python runtime. They are all strings, but often won't get along without marshaling.

An annoyance I had recently was that JScript arrays marshal to C# as "__ComObject", and has no documented way to play with this object. I can find the address of where it is, but I really don't know anything else about it, so the only way to really figure it out is to poke at it in any way possible and hopefully find useful information about it. So it becomes easier to create a new object with a friendlier interface like Scripting.Dictionary, copy the data from the JScript array object into it, and pass that object to C# instead of JScript's default array.

test.js:

var x = new ActiveXObject("Dmitry.YetAnotherTestObject.YetAnotherTestObject");

x.send([1, 2, 3, 4]);

YetAnotherTestObject.cs

using System;
using System.Runtime.InteropServices;

namespace Dmitry.YetAnotherTestObject
{
    [Guid("C612BD9B-74E0-4176-AAB8-C53EB24C2B29"), ComVisible(true)]
    public class YetAnotherTestObject
    {
        public void send(object x)
        {
            System.Console.WriteLine(x.GetType().Name);
        }
    }
}

above prints "__ComObject", which is somewhat of a black box from the point of view of C#.

Another interesting concept is that you might have the understanding how to write code, and a computer that knows how to execute instructions, so as a programmer, you are effectively marshaling the concept of what you want the computer to do from your brain to the program image. If we had good enough marshallers, we could just think of what we want to do/change, and the program would change that way without typing on the keyboard. So, if you could have a way to store all the physical changes in your brain for the few seconds where you really want to write a semicolon, you could marshal that data into a signal to print a semicolon, but that's an extreme.

Run a controller function whenever a view is opened/shown

For example to @Michael Trouw,

inside your controller put this code. this will run everytime when this state is entered or active, you do not need to worry about disabling cache and it's a better approach.

.controller('exampleCtrl',function($scope){
$scope.$on('$ionicView.enter', function(){
        // Any thing you can think of
        alert("This function just ran away");   
    });
})

You can have more examples of flexibility like $ionicView.beforeEnter -> which runs before a view is shown. And there are some more to it.

How to get the URL without any parameters in JavaScript?

I'm LATE to the party, but I had to solve this recently, figured I'd share the wealth.

const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/

window.location.origin will give you the base url, in our test case: http://example.com

window.location.pathname will give you the route path (after the base url), in our test case /somedir/somefile

SOLUTION 2

You can simply do the following to get rid of the query parameters.

const url = window.location.href.split('?')[0]

Javascript: Fetch DELETE and PUT requests

Some examples:

async function loadItems() { try { let response = await fetch(https://url/${AppID}); let result = await response.json(); return result; } catch (err) { } }

async function addItem(item) {
    try {
        let response = await fetch("https://url", {
            method: "POST",
            body: JSON.stringify({
                AppId: appId,
                Key: item,
                Value: item,
                someBoolean: false,
            }),
            headers: {
                "Content-Type": "application/json",
            },
        });
        let result = await response.json();
        return result;
    } catch (err) {
    }
}

async function removeItem(id) {
    try {
        let response = await fetch(`https://url/${id}`, {
            method: "DELETE",
        });
    } catch (err) {
    }
}

async function updateItem(item) {
    try {
        let response = await fetch(`https://url/${item.id}`, {
            method: "PUT",
            body: JSON.stringify(todo),
            headers: {
                "Content-Type": "application/json",
            },
        });
    } catch (err) {
    }
}

How can I issue a single command from the command line through sql plus?

sqlplus user/password@sid < sqlfile.sql

This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.

Find the most common element in a list

I am doing this using scipy stat module and lambda:

import scipy.stats
lst = [1,2,3,4,5,6,7,5]
most_freq_val = lambda x: scipy.stats.mode(x)[0][0]
print(most_freq_val(lst))

Result:

 most_freq_val = 5

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

I saw the same error but in my case it was a fresh Git installation without LFS installed. The repo in question was set up with LFS and the gradle-wrapper.jar was in LFS so it only contained a pointer to the LFS server. The solution was simple, just run:

git lfs install

And a fresh clone did the trick. I suppose git lfs pull or just a git pull could have helped as well but the person with the problem decided to do a fresh clone instead.

How to pass 2D array (matrix) in a function in C?

2D array:

int sum(int array[][COLS], int rows)
{

}

3D array:

int sum(int array[][B][C], int A)
{

}

4D array:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

What is inf and nan?

Inf is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf. -Inf is similar, but smaller than everything.

NaN means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN. Inf - Inf is one such computation. Usually NaN is used to just mean that some data is missing.

mysql datatype for telephone number and address

Consider normalizing to E.164 format. For full international support, you'd need a VARCHAR of 15 digits.

See Twilio's recommendation for more information on localization of phone numbers.

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

C# Test if user has write access to a folder

For example for all users (Builtin\Users), this method works fine - enjoy.

public static bool HasFolderWritePermission(string destDir)
{
   if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
   try
   {
      DirectorySecurity security = Directory.GetAccessControl(destDir);
      SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
      foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
      {
          if(rule.IdentityReference == users)
          {
             FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
             if(rights.AccessControlType == AccessControlType.Allow)
             {
                    if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
             }
          }
       }
       return false;
    }
    catch
    {
        return false;
    }
}

How to restart kubernetes nodes?

I had an onpremises HA installation, a master and a worker stopped working returning a NOTReady status. Checking the kubelet logs on the nodes I found out this problem:

failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false

Disabling swap on nodes with

swapoff -a

and restarting the kubelet

systemctl restart kubelet

did the work.

What is the difference between "is None" and "== None"

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

Android Studio - Unable to find valid certification path to requested target

My company has us using FortiClient VPN, which caused this error to occur.

Try disconnecting from your VPN if applicable, and try again.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.

How do I size a UITextView to its content?

This no longer works on iOS 7 or above

There is actually a very easy way to do resizing of the UITextView to its correct height of the content. It can be done using the UITextView contentSize.

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

One thing to note is that the correct contentSize is only available after the UITextView has been added to the view with addSubview. Prior to that it is equal to frame.size

This will not work if auto layout is ON. With auto layout, the general approach is to use the sizeThatFits method and update the constant value on a height constraint.

CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];
heightConstraint.constant = sizeThatShouldFitTheContent.height;

heightConstraint is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.


Just to add to this amazing answer, 2014, if you:

[self.textView sizeToFit];

there is a difference in behaviour with the iPhone6+ only:

enter image description here

With the 6+ only (not the 5s or 6) it does add "one more blank line" to the UITextView. The "RL solution" fixes this perfectly:

CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f;

It fixes the "extra line" problem on 6+.

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

How to add colored border on cardview?

try doing:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardElevation="2dp"
    card_view:cardCornerRadius="5dp">

    <FrameLayout
        android:background="#FF0000"
        android:layout_width="4dp"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:orientation="vertical">

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Headline"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Title" />

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Body1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Content here" />

    </LinearLayout>

</android.support.v7.widget.CardView>

this removes the padding from the cardview and adds a FrameLayout with a color. You then need to fix the padding in the LinearLayout then for the other fields

Update

If you want to preserve the card corner radius create card_edge.xml in drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#F00" />
    <size android:width="10dp"/>
    <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>
    <corners android:topLeftRadius="5dp" android:bottomLeftRadius="5dp"
        android:topRightRadius="0.1dp" android:bottomRightRadius="0.1dp"/>
</shape>

and in the frame layout use android:background="@drawable/card_edge"

Getting result of dynamic SQL into a variable for sql-server

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
RETURN @cnt

no module named zlib

By default when you configuring Python source, zlib module is disabled, so you can enable it using option --with-zlib when you configure it. So it becomes

./configure --with-zlib

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

C# Linq Where Date Between 2 Dates

Just change it to

var appointmentNoShow = from a in appointments
                        from p in properties
                        from c in clients
                        where a.Id == p.OID && 
                       (a.Start.Date >= startDate.Date && a.Start.Date <= endDate)

Finding current executable's path without /proc/self/exe

Some OS-specific interfaces:

There are also third party libraries that can be used to get this information, such as whereami as mentioned in prideout's answer, or if you are using Qt, QCoreApplication::applicationFilePath() as mentioned in the comments.

The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH.

Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.

Attributes / member variables in interfaces?

Interfaces cannot require instance variables to be defined -- only methods.

(Variables can be defined in interfaces, but they do not behave as might be expected: they are treated as final static.)

Happy coding.

How to prevent "The play() request was interrupted by a call to pause()" error?

The cleanest and simplest solution:

var p = video.play();
if (p !== undefined) p.catch(function(){});

How to show first commit by 'git log'?

Not the most beautiful way of doing it I guess:

git log --pretty=oneline | wc -l

This gives you a number then

git log HEAD~<The number minus one>

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

How to read a file in reverse order?

Here you can find my my implementation, you can limit the ram usage by changing the "buffer" variable, there is a bug that the program prints an empty line in the beginning.

And also ram usage may be increase if there is no new lines for more than buffer bytes, "leak" variable will increase until seeing a new line ("\n").

This is also working for 16 GB files which is bigger then my total memory.

import os,sys
buffer = 1024*1024 # 1MB
f = open(sys.argv[1])
f.seek(0, os.SEEK_END)
filesize = f.tell()

division, remainder = divmod(filesize, buffer)
line_leak=''

for chunk_counter in range(1,division + 2):
    if division - chunk_counter < 0:
        f.seek(0, os.SEEK_SET)
        chunk = f.read(remainder)
    elif division - chunk_counter >= 0:
        f.seek(-(buffer*chunk_counter), os.SEEK_END)
        chunk = f.read(buffer)

    chunk_lines_reversed = list(reversed(chunk.split('\n')))
    if line_leak: # add line_leak from previous chunk to beginning
        chunk_lines_reversed[0] += line_leak

    # after reversed, save the leakedline for next chunk iteration
    line_leak = chunk_lines_reversed.pop()

    if chunk_lines_reversed:
        print "\n".join(chunk_lines_reversed)
    # print the last leaked line
    if division - chunk_counter < 0:
        print line_leak

What is a good game engine that uses Lua?

World of Warcraft's engine seems all right, and it uses Lua. :)

Regex to match alphanumeric and spaces

The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.

How do you detect the clearing of a "search" HTML5 input?

Found this post and I realize it's a bit old, but I think I might have an answer. This handles the click on the cross, backspacing and hitting the ESC key. I am sure it could probably be written better - I'm still relatively new to javascript. Here is what I ended up doing - I am using jQuery (v1.6.4):

var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
  $("input[type=search]").keyup(function(e) {
    if (e.which == 27) {  // catch ESC key and clear input
      $(this).val('');
    }
    if (($(this).val() === "" && searchVal != "") || e.which == 27) {
      // do something
      searchVal = "";
    }
    searchVal = $(this).val();
  });
  $("input[type=search]").click(function() {
    if ($(this).val() != filterVal) {
      // do something
      searchVal = "";
    }
  });
});

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Recover SVN password from local cache

For those interested in the OS X solution for apps like Intelli-J where authorizations are stored by OSX:

  1. Hit CMD+SPACE
  2. Type "keychain"
  3. Open keychain access
  4. Under "Keychains" on the left, choose "login"
  5. Under "Category" on the right, choose "All items"
  6. At the top right in the search box, type in the the host URL (e.g. svn.mycompany.com)
  7. Your keychain item will show if you chose to have your Mac remember your login credentials.
  8. Double click the item and check the "Show password" checkbox at the bottom of the dialog that pops up. You will have to enter your Mac login to reveal the password.

Much easier than having to try to decrypt a password :-)

In MySQL, can I copy one row to insert into the same table?

I used Grim's technique with a little change: If someone looking for this query is because can't do a simple query due to primary key problem:

INSERT INTO table SELECT * FROM table WHERE primakey=1;

With my MySql install 5.6.26, key isn't nullable and produce an error:

#1048 - Column 'primakey' cannot be null 

So after create temporary table I change the primary key to a be nullable.

CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM table WHERE primarykey = 1;
ALTER TABLE tmptable_1 MODIFY primarykey int(12) null;
UPDATE tmptable_1 SET primarykey = NULL;
INSERT INTO table SELECT * FROM tmptable_1;
DROP TEMPORARY TABLE IF EXISTS tmptable_1;

libpng warning: iCCP: known incorrect sRGB profile

some background info on this:

Some changes in libpng version 1.6+ cause it to issue a warning or even not work correctly with the original HP/MS sRGB profile, leading to the following stderr: libpng warning: iCCP: known incorrect sRGB profile The old profile uses a D50 whitepoint, where D65 is standard. This profile is not uncommon, being used by Adobe Photoshop, although it was not embedded into images by default.

(source: https://wiki.archlinux.org/index.php/Libpng_errors)

Error detection in some chunks has improved; in particular the iCCP chunk reader now does pretty complete validation of the basic format. Some bad profiles that were previously accepted are now rejected, in particular the very old broken Microsoft/HP sRGB profile. The PNG spec requirement that only grayscale profiles may appear in images with color type 0 or 4 and that even if the image only contains gray pixels, only RGB profiles may appear in images with color type 2, 3, or 6, is now enforced. The sRGB chunk is allowed to appear in images with any color type.

(source: https://forum.qt.io/topic/58638/solved-libpng-warning-iccp-known-incorrect-srgb-profile-drive-me-nuts/16)

Wait until all jQuery Ajax requests are done?

I highly recommend using $.when() if you're starting from scratch.

Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.

We can easily take advantage of jQuery .data, .on and .trigger functions which have been a part of jQuery since forever.

Codepen

The good stuff about my solution is:

  • it's obvious what the callback exactly depends on

  • the function triggerNowOrOnLoaded doesn't care if the data has been already loaded or we're still waiting for it

  • it's super easy to plug it into an existing code

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  // wait for posts to be loaded_x000D_
  triggerNowOrOnLoaded("posts", function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + "</div>");_x000D_
  });_x000D_
_x000D_
_x000D_
  // some ajax requests_x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {_x000D_
    $("body").data("posts", data).trigger("posts");_x000D_
  });_x000D_
_x000D_
  // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests _x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {_x000D_
    $("body").data("users", data).trigger("users");_x000D_
  });_x000D_
_x000D_
_x000D_
  // wait for both types_x000D_
  triggerNowOrOnLoaded(["posts", "users"], function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
    var users = $body.data("users");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");_x000D_
  });_x000D_
_x000D_
  // works even if everything has already loaded!_x000D_
  setTimeout(function() {_x000D_
_x000D_
    // triggers immediately since users have been already loaded_x000D_
    triggerNowOrOnLoaded("users", function() {_x000D_
      var $body = $("body");_x000D_
      var users = $body.data("users");_x000D_
_x000D_
      $body.append("<div>Delayed Users: " + users.length + "</div>");_x000D_
    });_x000D_
_x000D_
  }, 2000); // 2 seconds_x000D_
_x000D_
});_x000D_
_x000D_
// helper function_x000D_
function triggerNowOrOnLoaded(types, callback) {_x000D_
  types = $.isArray(types) ? types : [types];_x000D_
_x000D_
  var $body = $("body");_x000D_
_x000D_
  var waitForTypes = [];_x000D_
  $.each(types, function(i, type) {_x000D_
_x000D_
    if (typeof $body.data(type) === 'undefined') {_x000D_
      waitForTypes.push(type);_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var isDataReady = waitForTypes.length === 0;_x000D_
  if (isDataReady) {_x000D_
    callback();_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  // wait for the last type and run this function again for the rest of the types_x000D_
  var waitFor = waitForTypes.pop();_x000D_
  $body.on(waitFor, function() {_x000D_
    // remove event handler - we only want the stuff triggered once_x000D_
    $body.off(waitFor);_x000D_
_x000D_
    triggerNowOrOnLoaded(waitForTypes, callback);_x000D_
  });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>Hi!</body>
_x000D_
_x000D_
_x000D_

How to get Activity's content view?

this.getWindow().getDecorView().findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content).getRootView()

Float a div above page content

The below code is working,

<style>
    .PanelFloat {
        position: fixed;
        overflow: hidden;
        z-index: 2400;
        opacity: 0.70;
        right: 30px;
        top: 0px !important;
        -webkit-transition: all 0.5s ease-in-out;
        -moz-transition: all 0.5s ease-in-out;
        -ms-transition: all 0.5s ease-in-out;
        -o-transition: all 0.5s ease-in-out;
        transition: all 0.5s ease-in-out;
    }
</style>

<script>
 //The below script will keep the panel float on normal state
 $(function () {
        $(document).on('scroll', function () {
            //Multiplication value shall be changed based on user window
            $('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
        });
    });
 //To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
 $(document).on('click', '.btnSearchView', function () {
      $('#MyFloatPanel').addClass('PanelFloat');
  });

  $(document).on('click', '.btnSearchClose', function () {
      $('#MyFloatPanel').removeClass('PanelFloat');
  });
 </script>

 <div class="col-lg-12 col-md-12">
   <div class="col-lg-8 col-md-8" >
    //My scrollable content is here
   </div>
   //This below panel will float while scrolling the above div content
   <div class="col-lg-4 col-md-4" id="MyFloatPanel">
    <div class="row">
     <div class="panel panel-default">
      <div class="panel-heading">Panel Head </div>
     <div class="panel-body ">//Your panel content</div>
   </div>
  </div>
 </div>
</div>

Abstract Class vs Interface in C++

Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.

class IInterface() 
{ 
   Public: 
   Virtual ~IInterface(){}; 
   … 
} 

Class ClassImpl : public IInterface 
{ 
    … 
} 

Int main() 
{ 

  IInterface* pInterface = new ClassImpl(); 
  … 
  delete pInterface; // Wrong in OO Programming, correct in C++.
}