Programs & Examples On #Google closure library

Closure Library is a JavaScript framework used by Google and one of three components to Closure Tools, an open source toolset to aid with developing front-end web applications

Discard all and get clean copy of latest revision?

To delete untracked on *nix without the purge extension you can use

hg pull
hg update -r MY_BRANCH -C
hg status -un|xargs rm

Which is using

update -r --rev REV revision

update -C --clean discard uncommitted changes (no backup)

status -u --unknown show only unknown (not tracked) files

status -n --no-status hide status prefix

How can I find an element by CSS class with XPath?

Most easy way..

//div[@class="Test"]

Assuming you want to find <div class="Test"> as described.

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

In my case, I was using the ASP.NET Identity Framework. I had used the built in UserManager.FindByNameAsync method to retrieve an ApplicationUser entity. I then tried to reference this entity on a newly created entity on a different DbContext. This resulted in the exception you originally saw.

I solved this by creating a new ApplicationUser entity with only the Id from the UserManager method and referencing that new entity.

Turning off eslint rule for a specific file

You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/

/* eslint no-console: "off", no-mixed-operators: "off" */

Version: [email protected]

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

SimpleXML - I/O warning : failed to load external entity

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

How do I get the directory that a program is running from?

Boost Filesystem's initial_path() behaves like POSIX's getcwd(), and neither does what you want by itself, but appending argv[0] to either of them should do it.

You may note that the result is not always pretty--you may get things like /foo/bar/../../baz/a.out or /foo/bar//baz/a.out, but I believe that it always results in a valid path which names the executable (note that consecutive slashes in a path are collapsed to one).

I previously wrote a solution using envp (the third argument to main() which worked on Linux but didn't seem workable on Windows, so I'm essentially recommending the same solution as someone else did previously, but with the additional explanation of why it is actually correct even if the results are not pretty.

How to make the tab character 4 spaces instead of 8 spaces in nano?

For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.

How to create batch file in Windows using "start" with a path and command with spaces

Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.

Scanner is skipping nextLine() after using next() or nextFoo()?

The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

Error 5 : Access Denied when starting windows service

For me - the folder from which the service was to run, and the files in it, were encrypted using the Windows "Encrypt" option. Removing that and - voila!

Returning a C string from a function

Your function signature needs to be:

const char * myFunction()
{
    return "My String";
}

Background:

It's so fundamental to C & C++, but little more discussion should be in order.

In C (& C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term "string-zero" is used to represent this particular flavour of string. There are other kinds of strings, but in C (& C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand "my string".

If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: "LPCSTR lpszName". The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.

Clarification:

For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (mbcs)) that are used to cope with international characters. UTF-8 is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.

Memory:

This means that a string like "my string" actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.

So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.

Longevity of data:

The use of the function this way:

const char * myFunction()
{
    return "My String";
}

int main()
{
    const char* szSomeString = myFunction(); // Fraught with problems
    printf("%s", szSomeString);
}

... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.

In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.

For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:

const char * myFunction(const char* name)
{
    char szBuffer[255];
    snprintf(szBuffer, sizeof(szBuffer), "Hi %s", name);
    return szBuffer;
}

That is, your program will crash because the compiler (may/may not) have released the memory used by szBuffer by the time the printf() in main() is called. (Your compiler should also warn you of such problems beforehand.)

There are two ways to return strings that won't barf so readily.

  1. returning buffers (static or dynamically allocated) that live for a while. In C++ use 'helper classes' (for example, std::string) to handle the longevity of data (which requires changing the function's return value), or
  2. pass a buffer to the function that gets filled in with information.

Note that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.

So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)

Safer Answers:

Example 1, using statically allocated strings:

const char* calculateMonth(int month)
{
    static char* months[] = {"Jan", "Feb", "Mar" .... };
    static char badFood[] = "Unknown";
    if (month<1 || month>12)
        return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however.
    else
        return months[month-1];
}

int main()
{
    printf("%s", calculateMonth(2)); // Prints "Feb"
}

What the 'static' does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.

If you move over to C++ you'll use similar strategies:

class Foo
{
    char _someData[12];
public:
    const char* someFunction() const
    { // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called.
        return _someData;
    }
}

... but it's probably easier to use helper classes, such as std::string, if you're writing the code for your own use (and not part of a library to be shared with others).

Example 2, using caller-defined buffers:

This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):

void calculateMonth(int month, char* pszMonth, int buffersize)
{
    const char* months[] = {"Jan", "Feb", "Mar" .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler)
    if (!pszMonth || buffersize<1)
        return; // Bad input. Let junk deal with junk data.
    if (month<1 || month>12)
    {
        *pszMonth = '\0'; // Return an 'empty' string
        // OR: strncpy(pszMonth, "Bad Month", buffersize-1);
    }
    else
    {
        strncpy(pszMonth, months[month-1], buffersize-1);
    }
    pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this!
}

int main()
{
    char month[16]; // 16 bytes allocated here on the stack.
    calculateMonth(3, month, sizeof(month));
    printf("%s", month); // Prints "Mar"
}

There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)

Disclaimer:

I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).

SSIS Connection not found in package

I generally find that when SSIS seems to be irrationally complaining about an apparently good connection, it is because I am trying to define the Connection directly using a package variable rather than via a Connection Manager. Example: today I had a Web Service Task where I made the mistake of directly creating an Expression defining its "Connection" property in terms of a package variable that contained the URL of the web service. Note however that a Connection is not the same thing as a ConnectionString! So when I looked at the task, it looked for all the world like it had everything valid, because it displayed a perfectly valid URL as the "Connection". The problem is that the Connection cannot be a string; it must be a Connection Manager.

How to set the height of table header in UITableView?

Just create Footer Wrapper View using constructor UIView(frame:_) then if you are using xib file for FooterView, create view from xib and add as subView to wrapper view. then assign wrapper to tableView.tableFooterView = fixWrapper .

    let fixWrapper = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 54)) // dont remove
    let footer = UIView.viewFromNib("YourViewXibFileName") as! YourViewClassName
    fixWrapper.addSubview(footer)
    tableView.tableFooterView = fixWrapper
    tableFootterCostView = footer

It works perfectly for me! the point is to create footer view with constructor (frame:_). Even though you create UIView() and assign frame property it may not work.

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

This does not disable curl exceptions for something like timeouts, but now you can get every status code easily:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

To check, if you got a valid code, you can use something like this:

if ($statuscode > 300) {
  // Do some error handling
}

... or better handle all expected codes:

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

For Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

Thanks to @mika

For Guzzle 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);

What is the scope of variables in JavaScript?

There are only function scopes in JS. Not block scopes! You can see what is hoisting too.

var global_variable = "global_variable";
var hoisting_variable = "global_hoist";

// Global variables printed
console.log("global_scope: - global_variable: " + global_variable);
console.log("global_scope: - hoisting_variable: " + hoisting_variable);

if (true) {
    // The variable block will be global, on true condition.
    var block = "block";
}
console.log("global_scope: - block: " + block);

function local_function() {
    var local_variable = "local_variable";
    console.log("local_scope: - local_variable: " + local_variable);
    console.log("local_scope: - global_variable: " + global_variable);
    console.log("local_scope: - block: " + block);
    // The hoisting_variable is undefined at the moment.
    console.log("local_scope: - hoisting_variable: " + hoisting_variable);

    var hoisting_variable = "local_hoist";
    // The hoisting_variable is now set as a local one.
    console.log("local_scope: - hoisting_variable: " + hoisting_variable);
}

local_function();

// No variable in a separate function is visible into the global scope.
console.log("global_scope: - local_variable: " + local_variable);

How to find the parent element using javascript

Using plain javascript:

element.parentNode

In jQuery:

element.parent()

Getting unique values in Excel by using formulas only

This is an oldie, and there are a few solutions out there, but I came up with a shorter and simpler formula than any other I encountered, and it might be useful to anyone passing by.

I have named the colors list Colors (A2:A7), and the array formula put in cell C2 is this (fixed):

=IFERROR(INDEX(Colors,MATCH(SUM(COUNTIF(C$1:C1,Colors)),COUNTIF(Colors,"<"&Colors),0)),"")

Use Ctrl+Shift+Enter to enter the formula in C2, and copy C2 down to C3:C7.

Explanation with sample data {"red"; "blue"; "red"; "green"; "blue"; "black"}:

  1. COUNTIF(Colors,"<"&Colors) returns an array (#1) with the count of values that are smaller then each item in the data {4;1;4;3;1;0} (black=0 items smaller, blue=1 item, red=4 items). This can be translated to a sort value for each item.
  2. COUNTIF(C$1:C...,Colors) returns an array (#2) with 1 for each data item that is already in the sorted result. In C2 it returns {0;0;0;0;0;0} and in C3 {0;0;0;0;0;1} because "black" is first in the sort and last in the data. In C4 {0;1;0;0;1;1} it indicates "black" and all the occurrences of "blue" are already present.
  3. The SUM returns the k-th sort value, by counting all the smaller values occurrences that are already present (sum of array #2).
  4. MATCH finds the first index of the k-th sort value (index in array #1).
  5. The IFERROR is only to hide the #N/A error in the bottom cells, when the sorted unique list is complete.

To know how many unique items you have you can use this regular formula:

=SUM(IF(FREQUENCY(COUNTIF(Colors,"<"&Colors),COUNTIF(Colors,"<"&Colors)),1))

rsync - mkstemp failed: Permission denied (13)

Make sure the user you're rsync'd into on the remote machine has write access to the contents of the folder AND the folder itself, as rsync tried to update the modification time on the folder itself.

CodeIgniter activerecord, retrieve last insert id?

$this->db->insert_id()  

//please try this

OWIN Startup Class Missing

Have a look for the Startup.cs file, you might be missing one of these. This file is the entry point for OWIN, so it sounds like this is missing. Take a look at OWIN Startup class here to understand whats going on.

As your error specifies, you can disable this in the web.config by doing the following...

To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

Get unique values from arraylist in java

you can use this for making a list Unique

ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");

ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());

What's the difference between an argument and a parameter?

An argument is an instantiation of a parameter.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

   Add Button in xml and give onclick attribute name that is the name of Method.
   <!--xml --!>
   <Button
  android:id="@+id/btn_register"
  android:layout_margin="1dp"
  android:onClick="addNumber"
  android:text="Add"
  />


    Button btnAdd = (Button) findViewById(R.id.mybutton); btnAdd.setOnClickListener(new View.OnClickListener() {
   @Override
    public void onClick(View v) {
      addNumber(v);
    }
    });

  Private void addNumber(View v){
  //Logic implement 
    switch (v.getId()) {
    case R.id.btnAdd :
        break;
     default:
        break;
    }}

How can I use iptables on centos 7?

And to add, you should also be able to do the same for ip6tables after running the systemctl mask firewalld command:

    systemctl start ip6tables.service
    systemctl enable ip6tables.service

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

MySQL error 1449: The user specified as a definer does not exist

Try the following:

mysqldump --routines --single-transaction -u root -proot portalv3 > c:\portal.sql

Finding all positions of substring in a larger string in C#

It could be done in efficient time complexity using KMP algorithm in O(N + M) where N is the length of text and M is the length of the pattern.

This is the implementation and usage:

static class StringExtensions
{
    public static IEnumerable<int> AllIndicesOf(this string text, string pattern)
    {
        if (string.IsNullOrEmpty(pattern))
        {
            throw new ArgumentNullException(nameof(pattern));
        }
        return Kmp(text, pattern);
    }

    private static IEnumerable<int> Kmp(string text, string pattern)
    {
        int M = pattern.Length;
        int N = text.Length;

        int[] lps = LongestPrefixSuffix(pattern);
        int i = 0, j = 0; 

        while (i < N)
        {
            if (pattern[j] == text[i])
            {
                j++;
                i++;
            }
            if (j == M)
            {
                yield return i - j;
                j = lps[j - 1];
            }

            else if (i < N && pattern[j] != text[i])
            {
                if (j != 0)
                {
                    j = lps[j - 1];
                }
                else
                {
                    i++;
                }
            }
        }
    }

    private static int[] LongestPrefixSuffix(string pattern)
    {
        int[] lps = new int[pattern.Length];
        int length = 0;
        int i = 1;

        while (i < pattern.Length)
        {
            if (pattern[i] == pattern[length])
            {
                length++;
                lps[i] = length;
                i++;
            }
            else
            {
                if (length != 0)
                {
                    length = lps[length - 1];
                }
                else
                {
                    lps[i] = length;
                    i++;
                }
            }
        }
        return lps;
    }

and this is an example of how to use it:

static void Main(string[] args)
    {
        string text = "this is a test";
        string pattern = "is";
        foreach (var index in text.AllIndicesOf(pattern))
        {
            Console.WriteLine(index); // 2 5
        }
    }

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 
}

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:focus,
.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;
}

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

One solution is to first encode data and then decode it in the same file:

$string =json_encode($input, JSON_UNESCAPED_UNICODE) ; 
echo $decoded = html_entity_decode( $string );

Failed to load resource: the server responded with a status of 404 (Not Found)

For me the error was the files under js folder not included in the project this solve my issue :

1- In the solution explorer toolbar click Show All Files.

2- open js folder and select all files under the folder

3- right click then select include In Project

4- Save and build your application then its working correct and load .css and .js files

Uncaught TypeError: data.push is not a function

Try This Code $scope.DSRListGrid.data = data; this one for source data

            for (var prop in data[0]) {
                if (data[0].hasOwnProperty(prop)) {
                    $scope.ListColumns.push(
                            {
                                "name": prop,
                                "field": prop,
                                "width": 150,
                                "headerCellClass": 'font-12'
                            }
                    );
                }
            }
            console.log($scope.ListColumns);

Using the Web.Config to set up my SQL database connection string?

If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS

Here is the connectionString in the web config file which you can add:

<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>

Place is just above the system.web tag.

Then you can call it by:

connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;

Why do people hate SQL cursors so much?

The optimizer often cannot use the relational algebra to transform the problem when a cursor method is used. Often a cursor is a great way to solve a problem, but SQL is a declarative language, and there is a lot of information in the database, from constraints, to statistics and indexes which mean that the optimizer has a lot of options to solve the problem, whereas a cursor pretty much explicitly directs the solution.

How to append multiple values to a list in Python

Other than the append function, if by "multiple values" you mean another list, you can simply concatenate them like so.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]

CSS to select/style first word

An easy way to do with HTML+CSS:

TEXT A <b>text b</b>

<h1>text b</h1>

<style>
    h1 { /* the css style */}
    h1:before {content:"text A (p.e.first word) with different style";    
    display:"inline";/* the different css style */}
</style>

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try this:

  $('.select').on('select2:selecting select2:unselecting', function(e) {

      var value = e.params.args.data.id;

  });

R: rJava package install failing

The rJava package looks for the /usr/lib/jvm/default-java/ folder. But it's not available as default. This folder have a symlink for the default java configured for the system.

To activate the default java install the following packages:

sudo apt-get install default-jre default-jre-headless

Tested on ubuntu 17.04 with CRAN R 3.4.1

How can I play sound in Java?

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Here is the code for reference.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

    AudioInputStream in;

    AudioFormat decodedFormat;

    AudioInputStream din;

    AudioFormat baseFormat;

    SourceDataLine line;

    private boolean loop;

    private BufferedInputStream stream;

    // private ByteArrayInputStream stream;

    /**
     * recreate the stream
     * 
     */
    public void reset() {
        try {
            stream.reset();
            in = AudioSystem.getAudioInputStream(stream);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            line = getLine(decodedFormat);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            line.close();
            din.close();
            in.close();
        } catch (IOException e) {
        }
    }

    Sound(String filename, boolean loop) {
        this(filename);
        this.loop = loop;
    }

    Sound(String filename) {
        this.loop = false;
        try {
            InputStream raw = Object.class.getResourceAsStream(filename);
            stream = new BufferedInputStream(raw);

            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            // byte[] buffer = new byte[1024];
            // int read = raw.read(buffer);
            // while( read > 0 ) {
            // out.write(buffer, 0, read);
            // read = raw.read(buffer);
            // }
            // stream = new ByteArrayInputStream(out.toByteArray());

            in = AudioSystem.getAudioInputStream(stream);
            din = null;

            if (in != null) {
                baseFormat = in.getFormat();

                decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                .getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat
                                .getSampleRate(), false);

                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                line = getLine(decodedFormat);
            }
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public void play() {

        try {
            boolean firstTime = true;
            while (firstTime || loop) {

                firstTime = false;
                byte[] data = new byte[4096];

                if (line != null) {

                    line.start();
                    int nBytesRead = 0;

                    while (nBytesRead != -1) {
                        nBytesRead = din.read(data, 0, data.length);
                        if (nBytesRead != -1)
                            line.write(data, 0, nBytesRead);
                    }

                    line.drain();
                    line.stop();
                    line.close();

                    reset();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

database_password: password would between quotes: " or '.

like so:

database_password: "password"

Switch: Multiple values in one case?

In C# 7 it's possible to use a when clause in a case statement.

int age = 12;
switch (age) 
{
  case int i when i >=1 && i <= 8:
    System.Console.WriteLine("You are only " + age + " years old. You must be kidding right. Please fill in your *real* age.");
    break;
  case int i when i >=9 && i <= 15:
    System.Console.WriteLine("You are only " + age + " years old. That's too young!");
    break;
  case int i when i >=16 && i <= 100:
    System.Console.WriteLine("You are " + age + " years old. Perfect.");
    break;
  default:
    System.Console.WriteLine("You an old person.");
    break;
}

Codesign error: Provisioning profile cannot be found after deleting expired profile

Here's a simpler solution that worked for me and which doesn't require the manual editing of the project file:

In Xcode, in the "Groups & Files" pane, expand "Targets" and double-click on your app's target. This brings up the Info pane for the target. In the "Build" section, check the "code signing" section for any old profiles and replace with the correct one.

Note that this is different from double-clicking on your project icon and changing the profile from there. Quite amazing :)

Ori

How to remove all MySQL tables from the command-line without DROP database permissions?

The accepted answer does not work for databases that have large numbers of tables, e.g. Drupal databases. Instead, see the script here: https://stackoverflow.com/a/12917793/1507877 which does work on MySQL 5.5. CAUTION: Around line 11, there is a "WHERE table_schema = SCHEMA();" This should instead be "WHERE table_schema = 'INSERT NAME OF DB INTO WHICH IMPORT WILL OCCUR';"

Maven: mvn command not found

  1. Run 'path' in command prompt and ensure that the maven installation directory is listed.
  2. Ensure the maven is installed in 'C:\Program Files\Maven'.

Make element fixed on scroll

There are some problems implementing this which the original accepted answer does not answer:

  1. The onscroll event of the window is firing very often. This implies that you either have to use a very performant listener, or you have to delay the listener somehow. jQuery Creator John Resig states here how a delayed mechanism can be implemented, and the reasons why you should do it. In my opinion, given todays browsers and environments, a performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
  2. The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
  3. Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here

Here's the code:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

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

How to create duplicate table with new name in SQL Server 2008

Right click on the table in SQL Management Studio.

Select Script... Create to... New Query Window.

This will generate a script to recreate the table in a new query window.

Change the name of the table in the script to whatever you want the new table to be named.

Execute the script.

Delete all files in directory (but not directory) - one liner solution

Or to use this in Java 8:

try {
  Files.newDirectoryStream( directory ).forEach( file -> {
    try { Files.delete( file ); }
    catch ( IOException e ) { throw new UncheckedIOException(e); }
  } );
}
catch ( IOException e ) {
  e.printStackTrace();
}

It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

Difference between fprintf, printf and sprintf?

printf(...) is equivalent to fprintf(stdout,...).

fprintf is used to output to stream.

sprintf(buffer,...) is used to format a string to a buffer.

Note there is also vsprintf, vfprintf and vprintf

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

How to find the minimum value of a column in R?

df <- read.table(text = 
             "X  Y
             1  2  3
             2  4  5
             3  6  7
             4  8  9
             5 10 11",
             header = TRUE)


y_min <- min(df[,"Y"])

# Corresponding X value
x_val_associated <- df[df$Y == y_min, "X"]

x_val_associated

First, you find the Y min using the min function on the "Y" column only. Notice the returned result is just an integer value. Then, to find the associated X value, you can subset the data.frame to only the rows where the minimum Y value is located and extract just the "X" column.

You now have two integer values for X and Y where Y is the min.

How to join on multiple columns in Pyspark?

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

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

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

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

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

'True' and 'False' in Python

While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

I thought Python treats anything with value as True. Why is this happening?

Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

if 0:
    print("Won't get here")

This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

from decimal import *
from fractions import *

if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
    print("Won't get here")

Here are the other value which evaluate to False:

if None or False or '' or () or [] or {} or set() or range(0):
    print("Won't get here")

Sources:

  1. Python Truth Value Testing is Awesome
  2. Truth Value Testing (in Built-in Types)

How to move table from one tablespace to another in oracle 11g

Moving tables:

First run:

SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';

-- Or suggested in the comments (did not test it myself)

SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; ' 
FROM dba_tables 
WHERE OWNER = '<SCHEMA>' 
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>

Where <schema_name> is the name of the user. And <tablespace_name> is the destination tablespace.

As a result you get lines like:

ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Moving indexes:

First run:

SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;' 
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';

The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.

As a result you should get something like:

ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Last but not least, moving LOBs:

First run:

SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';

This moves the LOB objects to the other tablespace.

As a result you should get something like:

ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);

Paste the results in a script or in a oracle sql developer like application and run it.

O and there is one more thing:

For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.

Singleton in Android

I put my version of Singleton below:

public class SingletonDemo {
    private static SingletonDemo instance = null;
    private static Context context;

    /**
     * To initialize the class. It must be called before call the method getInstance()
     * @param ctx The Context used

     */
    public static void initialize(Context ctx) {
     context = ctx;
    }

    /**
     * Check if the class has been initialized
     * @return true  if the class has been initialized
     *         false Otherwise
     */
    public static boolean hasBeenInitialized() {
     return context != null;

    }

    /**
    * The private constructor. Here you can use the context to initialize your variables.
    */
    private SingletonDemo() {
        // Use context to initialize the variables.
    }

    /**
    * The main method used to get the instance
    */
    public static synchronized SingletonDemo getInstance() {
     if (context == null) {
      throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before");
     }

     if (instance == null) {
      instance = new SingletonDemo();
     }

     return instance;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }
}

Note that the method initialize could be called in the main class(Splash) and the method getInstance could be called from other classes. This will fix the problem when the caller class requires the singleton but it does not have the context.

Finally the method hasBeenInitialized is uses to check if the class has been initialized. This will avoid that different instances have different contexts.

Counting the number of option tags in a select tag in jQuery

Another approach that can be useful.

$('#select-id').find('option').length

Bootstrap navbar Active State not working

This worked perfectly for me, because "window.location.pathname" also contains data before the real page name, e.g. directory/page.php. So the actual navbar link will only be set to active if the url contains this link.

$(document).ready(function() {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active', 
            window.location.pathname.indexOf($(this).find('a').attr('href')) > -1);
    }); 
});

Calculate RSA key fingerprint

To see your key on Ubuntu, just enter the following command on your terminal:

ssh-add -l

You will get an output like this: 2568 0j:20:4b:88:a7:9t:wd:19:f0:d4:4y:9g:27:cf:97:23 yourName@ubuntu (RSA)

If however you get an error like; Could not open a connection to your authentication agent.
Then it means that ssh-agent is not running. You can start/run it with: ssh-agent bash (thanks to @Richard in the comments) and then re-run ssh-add -l

Android - Package Name convention

http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

If you have a company domain www.example.com

Then you should use:

com.example.region.projectname

If you own a domain name like example.co.uk than it should be:

uk.co.example.region.projectname

If you do not own a domain, you should then use your email address:

for [email protected] it should be:

com.example.name.region.projectname

How to unzip a list of tuples into individual lists?

If you want a list of lists:

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

If a list of tuples is OK:

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

How to insert default values in SQL table?

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

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

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

How to extract a string between two delimiters

If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:

\[(.*?)\] this is your pattern. And in each group(1) will get you your string.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
    m.group(1); //is your string. do what you want
}

how to get current month and year

Find Current Year Using Razor try this

@DateTime.Now.Year

iOS: set font size of UILabel Programmatically

This code is perfectly working for me.

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
  [label setFont:[UIFont systemFontOfSize:11]];

Shorthand for if-else statement

Try like

var hasName = 'N';
if (name == "true") {
    hasName = 'Y';
}

Or even try with ternary operator like

var hasName = (name == "true") ? "Y" : "N" ;

Even simply you can try like

var hasName = (name) ? "Y" : "N" ;

Since name has either Yes or No but iam not sure with it.

Function for Factorial in Python

Another way to do it is to use np.prod shown below:

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))

How do I get the object if it exists, or None if it does not exist?

Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like

class ContentManager(model.Manager):
    def get_nicely(self, **kwargs):
        try:
            return self.get(kwargs)
        except(KeyError, Content.DoesNotExist):
            return None

and then including it in the content Model class

class Content(model.Model):
    ...
    objects = ContentManager()

In this way it can be easily dealt in the views i.e.

post = Content.objects.get_nicely(pk = 1)
if post:
    # Do something
else:
    # This post doesn't exist

How to close IPython Notebook properly?

For those of you who work on a remote computer with ssh, and maintain a Jupyter notebook server inside a tmux session, then after you exit the Jupyter notebook, you also have to close the pane that was used to maintain your Jupyter notebook server. Otherwise, it could cause issues when you try to log out from the ssh.

Set transparent background of an imageview on Android

Try this code :)

Its an fully transparent hexa code - "#00000000"

Save PL/pgSQL output from PostgreSQL to a CSV file

Do you want the resulting file on the server, or on the client?

Server side

If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;

This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

  1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
  2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.


Client side

The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

\copy (Select * From foo) To '/tmp/test.csv' With CSV

Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

From the docs:

Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.

How to get substring in C

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "SexDrugsRocknroll";
    char dest[5] = { 0 }; // 4 chars + terminator */
    int len = strlen(src);
    int i = 0;

    while (i*4 < len) {
        strncpy(dest, src+(i*4), 4);
        i++;

        printf("loop %d : %s\n", i, dest);
    }
}

Rotating a two-dimensional array in Python

Consider the following two-dimensional list:

original = [[1, 2],
            [3, 4]]

Lets break it down step by step:

>>> original[::-1]   # elements of original are reversed
[[3, 4], [1, 2]]

This list is passed into zip() using argument unpacking, so the zip call ends up being the equivalent of this:

zip([3, 4],
    [1, 2])
#    ^  ^----column 2
#    |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise

Hopefully the comments make it clear what zip does, it will group elements from each input iterable based on index, or in other words it groups the columns.

PHP ini file_get_contents external url

The is related to the ini configuration setting allow_url_fopen.

You should be aware that enable that option may make some bugs in your code exploitable.

For instance, this failure to validate input may turn into a full-fledged remote code execution vulnerability:

copy($_GET["file"], "."); 

Django set default form values

If you are creating modelform from POST values initial can be assigned this way:

form = SomeModelForm(request.POST, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Suppose you face this issue while running your go binary with in alpine container. Export the following variable before building your bin

# CGO has to be disabled for alpine
export CGO_ENABLED=0

Then go build

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

The above solutions like run a query

SET session wait_timeout=600;

Will only work until mysql is restarted. For a persistant solution, edit mysql.conf and add after [mysqld]:

wait_timeout=300
interactive_timeout = 300

Where 300 is the number of seconds you want.

Sublime 3 - Set Key map for function Goto Definition

ctrl != super on windows and linux machines.

If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff

    $(anyDomElement).trigger("myCustomEvent");
}


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff
});

How to get the part of a file after the first line that matches a regular expression?

A tool to use here is awk:

cat file | awk 'BEGIN{ found=0} /TERMINATE/{found=1}  {if (found) print }'

How does this work:

  1. We set the variable 'found' to zero, evaluating false
  2. if a match for 'TERMINATE' is found with the regular expression, we set it to one.
  3. If our 'found' variable evaluates to True, print :)

The other solutions might consume a lot of memory if you use them on very large files.

What are "named tuples" in Python?

Another way (a new way) to use named tuple is using NamedTuple from typing package: Type hints in namedtuple

Let's use the example of the top answer in this post to see how to use it.

(1) Before using the named tuple, the code is like this:

pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)

from math import sqrt

line_length = sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
print(line_length)

(2) Now we use the named tuple

from typing import NamedTuple

inherit the NamedTuple class and define the variable name in the new class. test is the name of the class.

class test(NamedTuple):
    x: float
    y: float

create instances from the class and assign values to them

pt1 = test(1.0, 5.0)   # x is 1.0, and y is 5.0. The order matters
pt2 = test(2.5, 1.5)

use the variables from the instances to calculate

line_length = sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2)
print(line_length)

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

formGroup expects a FormGroup instance

I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup in the class. Something like this:

myFormGroup: FormGroup = this.builder.group({
    dob: ['', Validators.required]
});

Firing a Keyboard Event in Safari, using JavaScript

Did you dispatch the event correctly?

function simulateKeyEvent(character) {
  var evt = document.createEvent("KeyboardEvent");
  (evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, character.charCodeAt(0)) 
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

If you use jQuery, you could do:

function simulateKeyPress(character) {
  jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

I decided that most popular symbols recommended here (? and ?) are looking too bold, so on the site codepoints.net, recommended by user ADJenks, I found these symbols which are looking better for my taste: (U+1F780) (U+1F781) (U+1F782) (U+1F783)

How to create an android app using HTML 5

When people talk about HTML5 applications they're most likely talking about writing just a simple web page or embedding a web page into their app (which will essentially provide the user interface). For the later there are different frameworks available, e.g. PhoneGap. These are used to provide more than the default browser features (e.g. multi touch) as well as allowing the app to run seamingly "standalone" and without the browser's navigation bars etc.

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

What is SOA "in plain english"?

Reading the responses above, it sounds to me that SOA is what developers (good ones at least) have been doing from day one.

How to give a time delay of less than one second in excel vba?

You can use an API call and Sleep:

Put this at the top of your module:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Then you can call it in a procedure like this:

Sub test()
Dim i As Long

For i = 1 To 10
    Debug.Print Now()
    Sleep 500    'wait 0.5 seconds
Next i
End Sub

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Good tutorial for using HTML5 History API (Pushstate?)

I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.html and history demo - http://diveintohtml5.info/examples/history/fer.html

How does HTTP file upload work?

I have this sample Java Code:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class TestClass {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8081);
        Socket accept = socket.accept();
        InputStream inputStream = accept.getInputStream();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        char readChar;
        while ((readChar = (char) inputStreamReader.read()) != -1) {
            System.out.print(readChar);
        }

        inputStream.close();
        accept.close();
        System.exit(1);
    }
}

and I have this test.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input type="submit">
</form>
</body>
</html>

and finally the file I will be using for testing purposes, named a.dat has the following content:

0x39 0x69 0x65

if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:

9ie

So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat and submit the form and see what our server receives:

POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF

------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream

9ie
------WebKitFormBoundary06f6g54NVbSieT6y--

Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..

Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF 

is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.

How to edit/save a file through Ubuntu Terminal

If you are not root user then, use following commands:

There are two ways to do it -

1.

sudo vi path_to_file/file_name

Press Esc and then type below respectively

:wq //save and exit
:q! //exit without saving
  1. sudo nano path_to_file/file_name

When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.

Entityframework Join using join method and lambdas

If you have configured navigation property 1-n I would recommend you to use:

var query = db.Categories                                  // source
   .SelectMany(c=>c.CategoryMaps,                          // join
      (c, cm) => new { Category = c, CategoryMaps = cm })  // project result
   .Select(x => x.Category);                               // select result

Much more clearer to me and looks better with multiple nested joins.

Working Copy Locked

error "working copy locked", Just follow the steps :

  1. In which directory you are getting error on update
  2. Go to its parent directory
  3. In parent directory go to ".svn" hidden directory
  4. Remove file with name "lock"
  5. Clean up and Done

You can update the svn properly without error

Python pip install fails: invalid command egg_info

I just convert liquidki's answer into Ubuntu commands. On an Ubuntu based system it works!:

sudo apt -y install python-pip
pip install -U pip
sudo pip install -U setuptools

Printing 1 to 1000 without loop or conditionals

We can launch 1000 threads, each printing one of the numbers. Install OpenMPI, compile using mpicxx -o 1000 1000.cpp and run using mpirun -np 1000 ./1000. You will probably need to increase your descriptor limit using limit or ulimit. Note that this will be rather slow, unless you have loads of cores!

#include <cstdio>
#include <mpi.h>
using namespace std;

int main(int argc, char **argv) {
  MPI::Init(argc, argv);
  cout << MPI::COMM_WORLD.Get_rank() + 1 << endl;
  MPI::Finalize();
}

Of course, the numbers won't necessarily be printed in order, but the question doesn't require them to be ordered.

Creating a Menu in Python

There were just a couple of minor amendments required:

ans=True
while ans:
    print ("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ") 
    if ans=="1": 
      print("\n Student Added") 
    elif ans=="2":
      print("\n Student Deleted") 
    elif ans=="3":
      print("\n Student Record Found") 
    elif ans=="4":
      print("\n Goodbye") 
    elif ans !="":
      print("\n Not Valid Choice Try again") 

I have changed the four quotes to three (this is the number required for multiline quotes), added a closing bracket after "What would you like to do? " and changed input to raw_input.

How to set password for Redis?

How to set redis password ?

step 1. stop redis server using below command /etc/init.d/redis-server stop

step 2.enter command : sudo nano /etc/redis/redis.conf

step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD

ex. requirepass root

How to get the month name in C#?

string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)

git ignore exception

This is how I do it, with a README.md file in each directory:

/data/*
!/data/README.md

!/data/input/
/data/input/*
!/data/input/README.md

!/data/output/
/data/output/*
!/data/output/README.md

How to Query Database Name in Oracle SQL Developer?

You can use the following command to know just the name of the database without the extra columns shown.

select name  from v$database;

If you need any other information about the db then first know which are the columns names available using

describe v$database;

and select the columns that you want to see;

jquery/javascript convert date string to date

I would grab date.js or else you will need to roll your own formatting function.

How to get current time and date in Android

For the current date and time with format, Use

In Java

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date","DATE : " + strDate)

In Kotlin

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
    var myDate: String =  current.format(formatter)
    Log.d("Date","DATE : " + myDate)
} else {
    var date = Date()
    val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
    val myDate: String = formatter.format(date)
    Log.d("Date","DATE : " + myDate)
}

Date Formater patterns

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

Username and password in command for git push

It is possible but, before git 2.9.3 (august 2016), a git push would print the full url used when pushing back to the cloned repo.
That would include your username and password!

But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 71076e1, 08 Aug 2016)

push: anonymize URL in status output

Commit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.

The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.

Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.

But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.

Distinct pair of values SQL

What you mean is either

SELECT DISTINCT a, b FROM pairs;

or

SELECT a, b FROM pairs GROUP BY a, b;

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

What is Func, how and when is it used

Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.

For example, consider the Enumerable.Select extension method.

  • The pattern is: for every item in a sequence, select some value from that item (e.g., a property) and create a new sequence consisting of these values.
  • The placeholder is: some selector function that actually gets the values for the sequence described above.

This method takes a Func<T, TResult> instead of any concrete function. This allows it to be used in any context where the above pattern applies.

So for example, say I have a List<Person> and I want just the name of every person in the list. I can do this:

var names = people.Select(p => p.Name);

Or say I want the age of every person:

var ages = people.Select(p => p.Age);

Right away, you can see how I was able to leverage the same code representing a pattern (with Select) with two different functions (p => p.Name and p => p.Age).

The alternative would be to write a different version of Select every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:

// Presumably, the code inside these two methods would look almost identical;
// the only difference would be the part that actually selects a value
// based on a Person.
var names = GetPersonNames(people);
var ages = GetPersonAges(people);

With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.

what exactly is device pixel ratio?

Device Pixel Ratio == CSS Pixel Ratio

In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.

A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:

formula

For example:

Apple iPhone 6s

  • Actual Resolution: 750 x 1334
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.

Some other examples:

Samsung Galaxy S4

  • Actual Resolution: 1080 x 1920
  • CSS Pixel Ratio: 3
  • Logical Resolution:

formula

iPhone 5s

  • Actual Resolution: 640 x 1136
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

Why does the Device Pixel Ratio exist?

The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.

A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.

So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.

Here is a tool that also tells you your current device's pixel density:

http://bjango.com/articles/min-device-pixel-ratio/

How can I include css files using node, express, and ejs?

The custom style sheets that we have are static pages in our local file system. In order for server to serve static files, we have to use,

app.use(express.static("public"));

where,

public is a folder we have to create inside our root directory and it must have other folders like css, images.. etc

The directory structure would look like :

enter image description here

Then in your html file, refer to the style.css as

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

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

How do I vertically center text with CSS?

Try the transform property:

_x000D_
_x000D_
 #box {_x000D_
  height: 90px;_x000D_
  width: 270px;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
 <div Id="box">_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</div>
_x000D_
_x000D_
_x000D_

Transpose list of lists

    #Import functions from library
    from numpy import size, array
    #Transpose a 2D list
    def transpose_list_2d(list_in_mat):
        list_out_mat = []
        array_in_mat = array(list_in_mat)
        array_out_mat = array_in_mat.T
        nb_lines = size(array_out_mat, 0)
        for i_line_out in range(0, nb_lines):
            array_out_line = array_out_mat[i_line_out]
            list_out_line = list(array_out_line)
            list_out_mat.append(list_out_line)
        return list_out_mat

Why is this HTTP request not working on AWS Lambda?

I had the very same problem and then I realized that programming in NodeJS is actually different than Python or Java as its based on JavaScript. I'll try to use simple concepts as there may be a few new folks that would be interested or may come to this question.

Let's look at the following code :

var http = require('http'); // (1)
exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url,  // (2)
  function(res) {  //(3)
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url); //(4)
}

Whenever you make a call to a method in http package (1) , it is created as event and this event gets it separate event. The 'get' function (2) is actually the starting point of this separate event.

Now, the function at (3) will be executing in a separate event, and your code will continue it executing path and will straight jump to (4) and finish it off, because there is nothing more to do.

But the event fired at (2) is still executing somewhere and it will take its own sweet time to finish. Pretty bizarre, right ?. Well, No it is not. This is how NodeJS works and its pretty important you wrap your head around this concept. This is the place where JavaScript Promises come to help.

You can read more about JavaScript Promises here. In a nutshell, you would need a JavaScript Promise to keep the execution of code inline and will not spawn new / extra threads.

Most of the common NodeJS packages have a Promised version of their API available, but there are other approaches like BlueBirdJS that address the similar problem.

The code that you had written above can be loosely re-written as follows.

'use strict';
console.log('Loading function');
var rp = require('request-promise');
exports.handler = (event, context, callback) => {    

    var options = {
    uri: 'https://httpbin.org/ip',
    method: 'POST',
    body: {

    },
    json: true 
};


    rp(options).then(function (parsedBody) {
            console.log(parsedBody);
        })
        .catch(function (err) {
            // POST failed... 
            console.log(err);
        });

    context.done(null);
};

Please note that the above code will not work directly if you will import it in AWS Lambda. For Lambda, you will need to package the modules with the code base too.

Build query string for System.Net.HttpClient get

For those who do not want to include System.Web in projects that don't already use it, you can use FormUrlEncodedContent from System.Net.Http and do something like the following:

keyvaluepair version

string query;
using(var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
    new KeyValuePair<string, string>("ham", "Glazed?"),
    new KeyValuePair<string, string>("x-men", "Wolverine + Logan"),
    new KeyValuePair<string, string>("Time", DateTime.UtcNow.ToString()),
})) {
    query = content.ReadAsStringAsync().Result;
}

dictionary version

string query;
using(var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
    { "ham", "Glaced?"},
    { "x-men", "Wolverine + Logan"},
    { "Time", DateTime.UtcNow.ToString() },
})) {
    query = content.ReadAsStringAsync().Result;
}

How can I get the sha1 hash of a string in node.js?

Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.

jQuery - Get Width of Element when Not Visible (Display: None)

jQuery(".megamenu li.level0 .dropdown-container .sub-column ul .level1").on("mouseover", function () {
    var sum = 0;
    jQuery(this).find('ul li.level2').each(function(){
    sum -= jQuery(this).height();
    jQuery(this).parent('ul').css('margin-top', sum / 1.8);
    console.log(sum);
    });
});

On hover we can calculate the list item height.

Java multiline string

It may seem a little crazy, but since heredocs are syntactic sugar over one-line declarations with linebreaks escaped, one could write pre-processor for Java files that would change heredocs into single-liners during preprocessing.

It would require writing proper plugins for preprocessing files before compilation phase (for ant/maven build) and a plugin to IDE.

From an ideological point of view, it differs nothing from f.g. "generics", that is also a kind of pre-processed syntactic sugar over casting.

It's, however, a lot of work, so I would at your place just use .properties files.

Android - default value in editText

 public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText et = (EditText) findViewById(R.id.et);
        EditText et_city = (EditText) findViewById(R.id.et_city);
        // Set the default text of second EditText widget
        et_city.setText("USA");
 }
}

How to fix .pch file missing on build?

I know this topic is very old, but I was dealing with this in VS2015 recently and what helped was to deleted the build folders and re-build it. This may have happen due to trying to close the program or a program halting/freezing VS while building.

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

What is the difference between syntax and semantics in programming languages?

Syntax is the structure or form of expressions, statements, and program units but Semantics is the meaning of those expressions, statements, and program units. Semantics follow directly from syntax. Syntax refers to the structure/form of the code that a specific programming language specifies but Semantics deal with the meaning assigned to the symbols, characters and words.

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

I faced the same issue while creating the connection on SQLDeveloper "ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist"

Solution:

1.Update the listene.ora file to include the SID.

  SID_LIST_LISTENER =
    (SID_LIST =
      (SID_DESC =
        (SID_NAME = PLSExtProc)
        (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
        (PROGRAM = extproc)
      )
      (SID_DESC =
        (SID_NAME = CLRExtProc)
        (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
        (PROGRAM = extproc)
      )
      (SID_DESC =
        ((GLOBAL_DBNAME = XE.DB)
        ((ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
        ((SID_NAME = XE)
      )
    )

  LISTENER =
    (DESCRIPTION_LIST =
      (DESCRIPTION =
        (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
        (ADDRESS = (PROTOCOL = TCP)(HOST = USMUMTBALAKDAS2.us.deloitte.com)(PORT = 1521))
      )
    )

  DEFAULT_SERVICE_LISTENER = (XE)

The Oraclexe directory may have the permission set to "ReadOnly", Change the directory/sub-directory permission to read/write and restart the listener services. Problem is solved.

How to get the full path of running process?

You can use pInvoke and a native call such as the following. This doesn't seem to have the 32 / 64 bit limitation (at least in my testing)

Here is the code

using System.Runtime.InteropServices;

    [DllImport("Kernel32.dll")]
    static extern uint QueryFullProcessImageName(IntPtr hProcess, uint flags, StringBuilder text, out uint size);

    //Get the path to a process
    //proc = the process desired
    private string GetPathToApp (Process proc)
    {
        string pathToExe = string.Empty;

        if (null != proc)
        {
            uint nChars = 256;
            StringBuilder Buff = new StringBuilder((int)nChars);

            uint success = QueryFullProcessImageName(proc.Handle, 0, Buff, out nChars);

            if (0 != success)
            {
                pathToExe = Buff.ToString();
            }
            else
            {
                int error = Marshal.GetLastWin32Error();
                pathToExe = ("Error = " + error + " when calling GetProcessImageFileName");
            }
        }

        return pathToExe;
    }

Adding click event for a button created dynamically using jQuery

Question 1: Use .delegate on the div to bind a click handler to the button.

Question 2: Use $(this).val() or this.value (the latter would be faster) inside of the click handler. this will refer to the button.

$("#pg_menu_content").on('click', '#btn_a', function () {
  alert($(this).val());
});

$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

Error: Can't set headers after they are sent to the client

Some of the answers in this Q&A are wrong. The accepted answer is also not very "practical", so I want to post an answer that explains things in simpler terms. My answer will cover 99% of the errors I see posted over and over again. For the actual reasons behind the error take a look at the accepted answer.


HTTP uses a cycle that requires one response per request. When the client sends a request (e.g. POST or GET) the server should only send one response back to it.

This error message:

Error: Can't set headers after they are sent.

usually happens when you send several responses for one request. Make sure the following functions are called only once per request:

  • res.json()
  • res.send()
  • res.redirect()
  • res.render()

(and a few more that are rarely used, check the accepted answer)

The route callback will not return when these res functions are called. It will continue running until it hits the end of the function or a return statement. If you want to return when sending a response you can do it like so: return res.send().


Take for instance this code:

app.post('/api/route1', function(req, res) {
  console.log('this ran');
  res.status(200).json({ message: 'ok' });
  console.log('this ran too');
  res.status(200).json({ message: 'ok' });
}

When a POST request is sent to /api/route1 it will run every line in the callback. A Can't set headers after they are sent error message will be thrown because res.json() is called twice, meaning two responses are sent.

Only one response can be sent per request!


The error in the code sample above was obvious. A more typical problem is when you have several branches:

app.get('/api/company/:companyId', function(req, res) {
  const { companyId } = req.params;
  Company.findById(companyId).exec((err, company) => {
      if (err) {
        res.status(500).json(err);
      } else if (!company) {
        res.status(404).json();      // This runs.
      }
      res.status(200).json(company); // This runs as well.
    });
}

This route with attached callback finds a company in a database. When doing a query for a company that doesn't exist we will get inside the else if branch and send a 404 response. After that, we will continue on to the next statement which also sends a response. Now we have sent two responses and the error message will occur. We can fix this code by making sure we only send one response:

.exec((err, company) => {
  if (err) {
    res.status(500).json(err);
  } else if (!company) {
    res.status(404).json();         // Only this runs.
  } else {
    res.status(200).json(company);
  }
});

or by returning when the response is sent:

.exec((err, company) => {
  if (err) {
    return res.status(500).json(err);
  } else if (!company) {
    return res.status(404).json();  // Only this runs.
  }
  return res.status(200).json(company);
});

A big sinner is asynchronous functions. Take the function from this question, for example:

article.save(function(err, doc1) {
  if (err) {
    res.send(err);
  } else {
    User.findOneAndUpdate({ _id: req.user._id }, { $push: { article: doc._id } })
    .exec(function(err, doc2) {
      if (err) res.send(err);
      else     res.json(doc2);  // Will be called second.
    })

    res.json(doc1);             // Will be called first.
  }
});

Here we have an asynchronous function (findOneAndUpdate()) in the code sample. If there are no errors (err) findOneAndUpdate() will be called. Because this function is asynchronous the res.json(doc1) will be called immediately. Assume there are no errors in findOneAndUpdate(). The res.json(doc2) in the else will then be called. Two responses have now been sent and the Can't set headers error message occurs.

The fix, in this case, would be to remove the res.json(doc1). To send both docs back to the client the res.json() in the else could be written as res.json({ article: doc1, user: doc2 }).

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:

^\d{1,45}$

where \d is the same like [0-9].

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

How can I convert a string to boolean in JavaScript?

Boolean.parse = function (str) {
  switch (str.toLowerCase ()) {
    case "true":
      return true;
    case "false":
      return false;
    default:
      throw new Error ("Boolean.parse: Cannot convert string to boolean.");
  }
};

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

CSS set li indent

li{
    margin-left:50px;
}

or replace 50px with whatever you want.

How to show x and y axes in a MATLAB graph?

This should work in Matlab:

set(gca, 'XAxisLocation', 'origin')

Options are: bottom, top, origin.

For Y.axis:

YAxisLocation; left, right, origin

How to produce an csv output file from stored procedure in SQL Server

This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -

DECLARE 
      @TableName SYSNAME
    , @ObjectID INT

DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR 
    SELECT 
          '[' + s.name + '].[' + t.name + ']'
        , t.[object_id]
    FROM (
        SELECT DISTINCT
              t.[schema_id]
            , t.[object_id]
            , t.name
        FROM sys.objects t WITH (NOWAIT)
        JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
        WHERE p.[rows] > 0
            AND t.[type] = 'U'
    ) t
    JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
    WHERE t.name IN ('<your table name>')

OPEN [tables]

FETCH NEXT FROM [tables] INTO 
      @TableName
    , @ObjectID

DECLARE 
      @SQLInsert NVARCHAR(MAX)
    , @SQLColumns NVARCHAR(MAX)
    , @SQLTinyColumns NVARCHAR(MAX)

WHILE @@FETCH_STATUS = 0 BEGIN

    SELECT 
          @SQLInsert = ''
        , @SQLColumns = ''
        , @SQLTinyColumns = ''

    ;WITH cols AS 
    (
        SELECT 
              c.name
            , datetype = t.name
            , c.column_id
        FROM sys.columns c WITH (NOWAIT)
        JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
        WHERE c.[object_id] = @ObjectID
            AND c.is_computed = 0
            AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
    )
    SELECT 
          @SQLTinyColumns = STUFF((
            SELECT ', [' + c.name + ']'
            FROM cols c
            ORDER BY c.column_id
            FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
        , @SQLColumns = STUFF((SELECT CHAR(13) +
            CASE 
                WHEN c.datetype = 'uniqueidentifier' 
                    THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')' 
                WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary') 
                    THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')' 
                WHEN c.datetype = 'datetime'
                    THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')' 
                ELSE 
                ' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
            END
            FROM cols c
            ORDER BY c.column_id
            FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')

    DECLARE @SQL NVARCHAR(MAX) = '    
    SET NOCOUNT ON;
    DECLARE 
          @SQL NVARCHAR(MAX) = ''''
        , @x INT = 1
        , @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')

    IF EXISTS(
        SELECT 1
        FROM tempdb.dbo.sysobjects
        WHERE ID = OBJECT_ID(''tempdb..#import'')
    )
        DROP TABLE #import;

    SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
    INTO #import
    FROM ' + @TableName + ' 

    WHILE @x < @count BEGIN

        SELECT @SQL = STUFF((
        SELECT ' + @SQLColumns + ' + ''''' + '
        FROM #import 
        WHERE RowNumber BETWEEN @x AND @x + 9
        FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')

        PRINT(@SQL)

        SELECT @x = @x + 10

    END'

    EXEC sys.sp_executesql @SQL

    FETCH NEXT FROM [tables] INTO 
          @TableName
        , @ObjectID

END

CLOSE [tables]
DEALLOCATE [tables]

In the output window you'll get something like this (AdventureWorks.Person.Person):

1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Bitwise AND your integer with the mask having exactly those bits set that you want to extract. Then shift the result right to reposition the extracted bits if desired.

unsigned int lowest_17_bits = myuint32 & 0x1FFFF;
unsigned int highest_17_bits = (myuint32 & (0x1FFFF << (32 - 17))) >> (32 - 17);

Edit: The latter repositions the highest 17 bits as the lowest 17; this can be useful if you need to extract an integer from “within” a larger one. You can omit the right shift (>>) if this is not desired.

Select top 1 result using JPA

Use a native SQL query by specifying a @NamedNativeQuery annotation on the entity class, or by using the EntityManager.createNativeQuery method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull to DDL by default (thanks to hibernate.validator.apply_to_ddl property defaults to true). But there is no guarantee that other JPA providers do or even have the ability to do that.

You should use bean validation annotations like @NotNull to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).

You should additionally use the JPA annotation like @Column(nullable = false) to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.

how to set background image in submit button?

The way I usually do it, is with the following css:

div#submitForm input {
  background: url("../images/buttonbg.png") no-repeat scroll 0 0 transparent;
  color: #000000;
  cursor: pointer;
  font-weight: bold;
  height: 20px;
  padding-bottom: 2px;
  width: 75px;
}

and the markup:

<div id="submitForm">
    <input type="submit" value="Submit" name="submit">
</div>

If things look different in the various browsers I implore you to use a reset style sheet which sets all margins, padding and maybe even borders to zero.

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

adding child nodes in treeview

Guys use this code for adding nodes and childnodes for TreeView from C# code. *

KISS (Keep It Simple & Stupid :)*

protected void Button1_Click(object sender, EventArgs e)

{

        TreeNode a1 = new TreeNode("Apple");

        TreeNode b1 = new TreeNode("Banana");
        TreeNode a2 = new TreeNode("gree apple");
        TreeView2.Nodes.Add(a1);
        TreeView2.Nodes.Add(b1);
        a1.ChildNodes.Add(a2);

}

Incorrect syntax near ''

The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.

To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.

Xcode 4 - "Archive" is greyed out?

see the picture. but I have to type enough chars to post the picture.:)

enter image description here

How do I create variable variables?

The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:

  • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.
  • there's either no locality or globality for variable variables, it depends on the globality of the dictionary
  • if you want to rename a variable name, you'll have to do it manually
  • however, you are much more flexible, e.g.
    • you can decide to overwrite existing variables or ...
    • ... choose to implement const variables
    • to raise an exception on overwriting for different types
    • etc.

That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.

You'd use the class like this:

from variableVariablesManager import VariableVariablesManager

myVars = VariableVariablesManager()
myVars['test'] = 25
print(myVars['test'])

# define a const variable
myVars.defineConstVariable('myconst', 13)
try:
    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
    print("not allowed")
except AttributeError as e:
    pass

# rename a variable
myVars.renameVariable('myconst', 'myconstOther')

# preserve locality
def testLocalVar():
    myVars = VariableVariablesManager()
    myVars['test'] = 13
    print("inside function myVars['test']:", myVars['test'])
testLocalVar()
print("outside function myVars['test']:", myVars['test'])

# define a global variable
myVars.defineGlobalVariable('globalVar', 12)
def testGlobalVar():
    myVars = VariableVariablesManager()
    print("inside function myVars['globalVar']:", myVars['globalVar'])
    myVars['globalVar'] = 13
    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
testGlobalVar()
print("outside function myVars['globalVar']:", myVars['globalVar'])

If you wish to allow overwriting of variables with the same type only:

myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
myVars['test'] = 25
myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)

Check if event exists on element

This work for me it is showing the objects and type of event which has occurred.

    var foo = $._data( $('body').get(0), 'events' );
    $.each( foo, function(i,o) {
    console.log(i); // guide of the event
    console.log(o); // the function definition of the event handler
    });

Pandas - Plotting a stacked Bar Chart

That should help

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

How to print Unicode character in C++?

If you use Windows (note, we are using printf(), not cout):

//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
    SetConsoleOutputCP(65001); 
    printf("?\n");
}

Not Unicode but working - 1251 instead of UTF8:

//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
    SetConsoleOutputCP(1251); 
    cout << "?" << endl;
}

Replace tabs with spaces in vim

IIRC, something like:

set tabstop=2 shiftwidth=2 expandtab

should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.

If you already have tabs you want to replace,

:retab

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

How to find the length of a string in R

The keepNA = TRUE option prevents problems with NA

nchar(NA)
## [1] 2
nchar(NA, keepNA=TRUE)
## [1] NA

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

Print time in a batch file (milliseconds)

You have to be careful with what you want to do, because it is not just about to get the time.

The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.

%Date%:

  • dd.MM.yyyy
  • dd.MM.yy
  • d.M.yy
  • dd/MM/yy
  • yyyy-MM-dd

%TIME%:

  • H:mm:ss,msec
  • HH:mm:ss,msec

Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.

The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.

I am using the wmic windows builtin utility to request such things (put it in a script file):

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j

or type it in the cmd.exe console:

for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j

The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.

If you want to continue use this then you can write something like this (get_datetime.bat):

@echo off

rem Description:
rem   Independent to Windows locale date/time request.

rem Drop last error level
cd .

rem drop return value
set "RETURN_VALUE="

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"

if not "%RETURN_VALUE%" == "" (
  set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
  exit /b 0
)

exit /b 1

Now, you can parse %RETURN_VALUE% somethere in your script:

call get_datetime.bat
set "FILE_SUFFIX=%RETURN_VALUE:.=_%"
set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"
echo.%FILE_SUFFIX%

How to find encoding of a file via script on Linux?

file -bi <file name>

If you like to do this for a bunch of files

for f in `find | egrep -v Eliminate`; do echo "$f" ' -- ' `file -bi "$f"` ; done

How to change the background color of the options menu?

The style attribute for the menu background is android:panelFullBackground.

Despite what the documentation says, it needs to be a resource (e.g. @android:color/black or @drawable/my_drawable), it will crash if you use a color value directly.

This will also get rid of the item borders that I was unable to change or remove using primalpop's solution.

As for the text color, I haven't found any way to set it through styles in 2.2 and I'm sure I've tried everything (which is how I discovered the menu background attribute). You would need to use primalpop's solution for that.

Subtract 1 day with PHP

Not sure why your current code isn't working but if you don't specifically need a date object this will work:

$first_date = strtotime($date_raw);
$second_date = strtotime('-1 day', $first_date);

print 'First Date ' . date('Y-m-d', $first_date);
print 'Next Date ' . date('Y-m-d', $second_date);

How to import Angular Material in project?

Import all Angular Material modules in Angular 9.

Create material.module.ts file in your_project/src/app/ directory and paste this code.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';


@NgModule( {
    imports: [
        CommonModule,
        BrowserAnimationsModule,
        MatCheckboxModule,
        MatCheckboxModule,
        MatButtonModule,
        MatInputModule,
        MatAutocompleteModule,
        MatDatepickerModule,
        MatFormFieldModule,
        MatRadioModule,
        MatSelectModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatMenuModule,
        MatSidenavModule,
        MatBadgeModule,
        MatToolbarModule,
        MatListModule,
        MatGridListModule,
        MatCardModule,
        MatStepperModule,
        MatTabsModule,
        MatExpansionModule,
        MatButtonToggleModule,
        MatChipsModule,
        MatIconModule,
        MatProgressSpinnerModule,
        MatProgressBarModule,
        MatDialogModule,
        MatTooltipModule,
        MatSnackBarModule,
        MatTableModule,
        MatSortModule,
        MatPaginatorModule

    ],
    exports: [
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
        MatSidenavModule,
        MatBadgeModule,
        MatListModule,
        MatGridListModule,
        MatInputModule,
        MatFormFieldModule,
        MatSelectModule,
        MatRadioModule,
        MatDatepickerModule,
        MatChipsModule,
        MatTooltipModule,
        MatTableModule,
        MatPaginatorModule
    ],
    providers: [
        MatDatepickerModule,
    ]
} )

export class AngularMaterialModule { }

What is the correct way to read a serial port using .NET framework?

I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

private string buffer { get; set; }
private SerialPort _port { get; set; }

public Port() 
{
    _port = new SerialPort();
    _port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
    buffer = string.Empty;
}

private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{    
    buffer += _port.ReadExisting();

    //test for termination character in buffer
    if (buffer.Contains("\r\n"))
    {
        //run code on data received from serial port
    }
}

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

Repository access denied. access via a deployment key is read-only

Recently I faced the same issue. I got the following error:

repository access denied. access via a deployment key is read-only.

You can have two kinds of SSH keys:

  1. For your entire account which will work for all repositories
  2. Per repository SSH key which can only be used for that specific repository.

I simply removed my repository SSH key and added a new SSH key to my account and it worked well.

I hope it helps someone. Cheers

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:

def book_author(self):
  return self.book.author

Then the admin part works nicely.

Best way to pretty print a hash

Use the answers above if you're printing to users.

If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)

gem install pry

And check this railscast:

http://railscasts.com/episodes/280-pry-with-rails

Watermark / hint text / placeholder TextBox

namespace PlaceholderForRichTexxBoxInWPF
{
public MainWindow()
        {
            InitializeComponent();
            Application.Current.MainWindow.WindowState = WindowState.Maximized;// maximize window on load

            richTextBox1.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_GotKeyboardFocus);
            richTextBox1.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_LostKeyboardFocus);
            richTextBox1.AppendText("Place Holder");
            richTextBox1.Foreground = Brushes.Gray;
        }
 private void rtb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (sender is RichTextBox)
            {
                TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); 

                if (textRange.Text.Trim().Equals("Place Holder"))
                {
                    ((RichTextBox)sender).Foreground = Brushes.Black;
                    richTextBox1.Document.Blocks.Clear();
                }
            }
        }


        private void rtb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //Make sure sender is the correct Control.
            if (sender is RichTextBox)
            {
                //If nothing was entered, reset default text.
                TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); 

                if (textRange.Text.Trim().Equals(""))
                {
                    ((RichTextBox)sender).Foreground = Brushes.Gray;
                    ((RichTextBox)sender).AppendText("Place Holder");
                }
            }
        }
}

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Eclipse change project files location

This link shows how to edit the eclipse workspace metadata to update the project's location manually, useful if the location has already changed or you have a lot of projects to move and don't want to do several clicks and waits for each one: https://web.archive.org/web/20160421171614/http://www.joeflash.ca/blog/2008/11/moving-a-fb-workspace-update.html

Iterating through a range of dates in Python

Slightly different approach to reversible steps by storing range args in a tuple.

def date_range(start, stop, step=1, inclusive=False):
    day_count = (stop - start).days
    if inclusive:
        day_count += 1

    if step > 0:
        range_args = (0, day_count, step)
    elif step < 0:
        range_args = (day_count - 1, -1, step)
    else:
        raise ValueError("date_range(): step arg must be non-zero")

    for i in range(*range_args):
        yield start + timedelta(days=i)

In-memory size of a Python structure

Also you can use guppy module.

>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0  11731  45   929072  28    929072  28 str
     1   5832  23   469760  14   1398832  42 tuple
     2    324   1   277728   8   1676560  50 dict (no owner)
     3     70   0   216976   7   1893536  57 dict of module
     4    199   1   210856   6   2104392  63 dict of type
     5   1627   6   208256   6   2312648  70 types.CodeType
     6   1592   6   191040   6   2503688  75 function
     7    199   1   177008   5   2680696  81 type
     8    124   0   135328   4   2816024  85 dict of class
     9   1045   4    83600   3   2899624  87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>

And:

>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0      1  17      280  50       280  50 dict (no owner)
     1      1  17      136  24       416  74 list
     2      1  17       64  11       480  86 tuple
     3      1  17       40   7       520  93 str
     4      1  17       24   4       544  97 int
     5      1  17       16   3       560 100 types.NoneType

Unable to create Genymotion Virtual Device

Deleting the Genymotion cached .ova file, deleting the corrupted deployed image, redownloading the image, and reinstalling it addressed the issue for me.

Note that the deployed images are under: ~/.Genymobile/Genymotion/deployed

the cached ova files are under: ~/.Genymobile/Genymotion/ova

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

Tkinter understanding mainloop

tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:

while 1:
    ball.draw()
    tk.mainloop()
    print("hello")   #NEW CODE
    time.sleep(0.01)

You will never see the output from the print statement. Because there is no loop, the ball doesn't move.

On the other hand, the methods update_idletasks() and update() here:

while True:
    ball.draw()
    tk.update_idletasks()
    tk.update()

...do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.

An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop(). Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.

However, tk.mainloop() is not a substitute for just the lines:

tk.update_idletasks()
tk.update()

Rather, tk.mainloop() is a substitute for the whole while loop:

while True:
    tk.update_idletasks()
    tk.update()

Response to comment:

Here is what the tcl docs say:

Update idletasks

This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)

APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:

So update_idletasks() causes some subset of events to be processed that update() causes to be processed.

From the update docs:

update ?idletasks?

The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.

The commonest purposes for which I've seen [update] recommended are:

  1. Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.

What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.

.....

Is there any chance I can make my program work without the while loop?

Yes, but things get a little tricky. You might think something like the following would work:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        while True:
           self.canvas.move(self.id, 0, -1)

ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()

The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.

So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after() method:

from Tkinter import *
import random
import time

tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(1, self.draw)  #(time_delay, method_to_execute)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment
tk.mainloop()

The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:

from Tkinter import *
import random
import time

root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas.bind("<Button-1>", self.canvas_onclick)
        self.text_id = self.canvas.create_text(300, 200, anchor='se')
        self.canvas.itemconfig(self.text_id, text='hello')

    def canvas_onclick(self, event):
        self.canvas.itemconfig(
            self.text_id, 
            text="You clicked at ({}, {})".format(event.x, event.y)
        )

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(50, self.draw)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

How to hide soft keyboard on android after clicking outside EditText?

Instead of iterating through all the views or overriding dispatchTouchEvent.

Why Not just override the onUserInteraction() of the Activity this will make sure keyboard dismisses whenever the user taps outside of EditText.

Will work even when EditText is inside the scrollView.

@Override
public void onUserInteraction() {
    if (getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

Get current domain

Try $_SERVER['SERVER_NAME'].

Tips: Create a PHP file that calls the function phpinfo() and see the "PHP Variables" section. There are a bunch of useful variables we never think of there.

Visual Studio 2012 Web Publish doesn't copy files

First:

  • Build in release Configuration.
  • In Project Properties-> page select All files and folders under Package/Publish Web.
  • Rebuild solution (after Clean solution).
  • now publish.

While publishing recheck what u have opted.
this should do it. It did for me!:)

When do you use Java's @Override annotation and why?

Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.

Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How to recover corrupted Eclipse workspace?

You should be able to start your workspace after deleting the following file: .metadata.plugins\org.eclipse.e4.workbench\workbench.xmi as shown here :

Chrome says my extension's manifest file is missing or unreadable

Some permissions issue for default sample.

I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.

Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip

which can be found at
https://developer.chrome.com/extensions/samples

this worked great, hope it helps

How to get URL parameter using jQuery or plain JavaScript?

May be its too late. But this method is very easy and simple

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990 -->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')      // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')       // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});

UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

CSS: How can I set image size relative to parent height?

If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.

.img-fill > img {
  min-height: 100%;
  min-width: 100%;  
}

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

Find a private field with Reflection?

Use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

How to implement drop down list in flutter?

The error you are getting is due to ask for a property of a null object. Your item must be null so when asking for its value to be compared you are getting that error. Check that you are getting data or your list is a list of objects and not simple strings.

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

"Please provide a valid cache path" error in laravel

I solved the problem when I created framework folder inside storage folder and its subfolders sessions, views and cache.

Go to your cmd or terminal then type your project root path and after that type the following:

cd storage
mkdir framework
cd framework
mkdir sessions
mkdir views
mkdir cache

Go to your project root path back again and run composer update

After that artisan works perfectly.