Programs & Examples On #Cross platform

An attribute conferred to computer software or computing methods and concepts that are implemented and inter-operate on multiple computer platforms.

How to get current time and date in C++?

you could use C++ 11 time class:

    #include <iostream>
    #include <iomanip>
    using namespace std;

    int main() {

       time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
       cout << put_time(localtime(&now), "%F %T") <<  endl;
      return 0;
     }

out put:

2017-08-25 12:30:08

Cross-platform way of getting temp directory in Python

This should do what you want:

print tempfile.gettempdir()

For me on my Windows box, I get:

c:\temp

and on my Linux box I get:

/tmp

How do I monitor the computer's CPU, memory, and disk usage in Java?

The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:

Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010

My recommendation is to use https://github.com/oshi/oshi

Or the answer mentioned above.

A Simple, 2d cross-platform graphics library for c or c++?

I would recommend DISLIN. It's cross platform, has support for many languages, and has very intuitive naming of routines.

Also, just noticed that nobody mentioned PLPLOT, also cross platform, multi lingual ...

What's the best way to check if a file exists in C?

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) == 0 ) {
    // file exists
} else {
    // file doesn't exist
}

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

iOS / Android cross platform development

There is also BatteryTech which we've been using for the past 18 months and have released several games off of it. http://www.batterypoweredgames.com/batterytech

All C++, Android and iOS support, all users get full source. The new v2 includes lua bindings.

How do you run a Python script as a service in Windows?

Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?

I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.

I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

How do I get a platform-dependent new line character?

If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Try setting the core.autocrlf configuration option to true. Also have a look at the core.safecrlf option.

Actually it sounds like core.safecrlf might already be set in your repository, because (emphasis mine):

If this is not the case for the current setting of core.autocrlf, git will reject the file.

If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.

Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.

How to get the home directory in Python?

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

How to check if running in Cygwin, Mac or Linux?

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

All the info you'll ever need. Google is your friend.

Use uname -s to query the system name.

  • Mac: Darwin
  • Cygwin: CYGWIN_...
  • Linux: various, LINUX for most

Difference between "\n" and Environment.NewLine

Exact implementation of Environment.NewLine from the source code:

The implementation in .NET 4.6.1:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return "\r\n";
    }
}

source


The implementation in .NET Core:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
**        given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
        return "\r\n";
#else
        return "\n";
#endif // !PLATFORM_UNIX
    }
}

source (in System.Private.CoreLib)

public static string NewLine => "\r\n";

source (in System.Runtime.Extensions)

Generate list of all possible permutations of a string

Many of the previous answers used backtracking. This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting

class Permutation {

    /* runtime -O(n) for generating nextPermutaion
     * and O(n*n!) for generating all n! permutations with increasing sorted array as start
     * return true, if there exists next lexicographical sequence
     * e.g [a,b,c],3-> true, modifies array to [a,c,b]
     * e.g [c,b,a],3-> false, as it is largest lexicographic possible */
    public static boolean nextPermutation(char[] seq, int len) {
        // 1
        if (len <= 1)
            return false;// no more perm
        // 2: Find last j such that seq[j] <= seq[j+1]. Terminate if no such j exists
        int j = len - 2;
        while (j >= 0 && seq[j] >= seq[j + 1]) {
            --j;
        }
        if (j == -1)
            return false;// no more perm
        // 3: Find last l such that seq[j] <= seq[l], then exchange elements j and l
        int l = len - 1;
        while (seq[j] >= seq[l]) {
            --l;
        }
        swap(seq, j, l);
        // 4: Reverse elements j+1 ... count-1:
        reverseSubArray(seq, j + 1, len - 1);
        // return seq, add store next perm

        return true;
    }
    private static void swap(char[] a, int i, int j) {
        char temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    private static void reverseSubArray(char[] a, int lo, int hi) {
        while (lo < hi) {
            swap(a, lo, hi);
            ++lo;
            --hi;
        }
    }
    public static void main(String[] args) {
        String str = "abcdefg";
        char[] array = str.toCharArray();
        Arrays.sort(array);
        int cnt=0;
        do {
            System.out.println(new String(array));
            cnt++;
        }while(nextPermutation(array, array.length));
        System.out.println(cnt);//5040=7!
    }
    //if we use "bab"-> "abb", "bab", "bba", 3(#permutations)
}

Using CMake to generate Visual Studio C++ project files

We moved our department's build chain to CMake, and we had a few internal roadbumps since other departments where using our project files and where accustomed to just importing them into their solutions. We also had some complaints about CMake not being fully integrated into the Visual Studio project/solution manager, so files had to be added manually to CMakeLists.txt; this was a major break in the workflow people were used to.

But in general, it was a quite smooth transition. We're very happy since we don't have to deal with project files anymore.

The concrete workflow for adding a new file to a project is really simple:

  1. Create the file, make sure it is in the correct place.
  2. Add the file to CMakeLists.txt.
  3. Build.

CMake 2.6 automatically reruns itself if any CMakeLists.txt files have changed (and (semi-)automatically reloads the solution/projects).

Remember that if you're doing out-of-source builds, you need to be careful not to create the source file in the build directory (since Visual Studio only knows about the build directory).

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

How can one grab a stack trace in C?

Solaris has the pstack command, which was also copied into Linux.

How to execute XPath one-liners from shell?

Here's one xmlstarlet use case to extract data from nested elements elem1, elem2 to one line of text from this type of XML (also showing how to handle namespaces):

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<mydoctype xmlns="http://xml-namespace-uri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml-namespace-uri http://xsd-uri" format="20171221A" date="2018-05-15">

  <elem1 time="0.586" length="10.586">
      <elem2 value="cue-in" type="outro" />
  </elem1>

</mydoctype>

The output will be

0.586 10.586 cue-in outro

In this snippet, -m matches the nested elem2, -v outputs attribute values (with expressions and relative addressing), -o literal text, -n adds a newline:

xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2' \
 -v ../@time -o " " -v '../@time + ../@length' -o " " -v @value -o " " -v @type -n file.xml

If more attributes are needed from elem1, one can do it like this (also showing the concat() function):

xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2/..' \
 -v 'concat(@time, " ", @time + @length, " ", ns:elem2/@value, " ", ns:elem2/@type)' -n file.xml

Note the (IMO unnecessary) complication with namespaces (ns, declared with -N), that had me almost giving up on xpath and xmlstarlet, and writing a quick ad-hoc converter.

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

Python: What OS am I running on?

You can look at the code in pyOSinfo which is part of the pip-date package, to get the most relevant OS information, as seen from your Python distribution.

One of the most common reasons people want to check their OS is for terminal compatibility and if certain system commands are available. Unfortunately, the success of this checking is somewhat dependent on your python installation and OS. For example, uname is not available on most Windows python packages. The above python program will show you the output of the most commonly used built-in functions, already provided by os, sys, platform, site.

enter image description here

So the best way to get only the essential code is looking at that as an example. (I guess I could have just pasted it here, but that would not have been politically correct.)

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

Automatically add all files in a folder to a target using CMake?

As of CMake 3.1+ the developers strongly discourage users from using file(GLOB or file(GLOB_RECURSE to collect lists of source files.

Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.

See the documentation here.

There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.


It is possible. E.g. with file(GLOB:

cmake_minimum_required(VERSION 2.8)

file(GLOB helloworld_SRC
     "*.h"
     "*.cpp"
)

add_executable(helloworld ${helloworld_SRC})

Note that this requires manual re-running of cmake if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.

As of CMake 3.12, you can pass the CONFIGURE_DEPENDS flag to file(GLOB to automatically check and reset the file lists any time the build is invoked. You would write:

cmake_minimum_required(VERSION 3.12)

file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")

This at least lets you avoid manually re-running CMake every time a file is added.

How is Java platform-independent when it needs a JVM to run?

It means the Java programmer does not (in theory) need to know machine or OS details. These details do exist and the JVM and class libraries handle them. Further, in sharp contrast to C, Java binaries (bytecode) can often be moved to entirely different systems without modifying or recompiling.

Compiling C++ on remote Linux machine - "clock skew detected" warning

Install the Network Time Protocol

This also happened to me when running make on a Samba SMB CIFS share on a server. A durable solution consists in installing the ntp daemon on both the server and the client. (Please, note that this problem is not solved by running ntpdate. This would resolve the time difference only temporarily, but not in the future.)

For Ubuntu and Debian-derived systems, simply type the following line at the command line:

$ sudo apt install ntp

Moreover, one will still need to issue the command touch * once (and only once) in the affected directory to correct the file modification times once and for all.

$ touch *

For more information about the differences between ntp and ntpdate, please refer to:

Reading and displaying data from a .txt file

In Java 8, you can read a whole file, simply with:

public String read(String file) throws IOException {
  return new String(Files.readAllBytes(Paths.get(file)));
}

or if its a Resource:

public String read(String file) throws IOException {
  URL url = Resources.getResource(file);
  return Resources.toString(url, Charsets.UTF_8);
}

Get PHP class property by string

In case anyone else wants to find a deep property of unknown depth, I came up with the below without needing to loop through all known properties of all children.

For example, to find $Foo->Bar->baz, or $Foo->baz, or $Foo->Bar->Baz->dave, where $path is a string like 'foo/bar/baz'.

public function callModule($pathString, $delimiter = '/'){

    //split the string into an array
    $pathArray = explode($delimiter, $pathString);

    //get the first and last of the array
    $module = array_shift($pathArray);
    $property = array_pop($pathArray);

    //if the array is now empty, we can access simply without a loop
    if(count($pathArray) == 0){
        return $this->{$module}->{$property};
    }

    //we need to go deeper
    //$tmp = $this->Foo
    $tmp = $this->{$module};

    foreach($pathArray as $deeper){
        //re-assign $tmp to be the next level of the object
        // $tmp = $Foo->Bar --- then $tmp = $Bar->baz
        $tmp = $tmp->{$deeper};
    }

    //now we are at the level we need to be and can access the property
    return $tmp->{$property};

}

And then call with something like:

$propertyString = getXMLAttribute('string'); // '@Foo/Bar/baz'
$propertyString = substr($propertyString, 1);
$moduleCaller = new ModuleCaller();
echo $moduleCaller->callModule($propertyString);

Replace a character at a specific index in a string?

String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

How to add users to Docker container?

Everyone has their personal favorite, and this is mine:

RUN useradd --user-group --system --create-home --no-log-init app
USER app

Reference: man useradd

The RUN line will add the user and group app:

root@ef3e54b60048:/# id app
uid=999(app) gid=999(app) groups=999(app)

Use a more specific name than app if the image is to be reused as a base image. As an aside, include --shell /bin/bash if you really need.


Partial credit: answer by Ryan M

How to get element-wise matrix multiplication (Hadamard product) in numpy?

just do this:

import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

a * b

AFNetworking Post Request

Here is a simple AFNetworking POST I'm using. To get up and running after reading the AFNetworking doc, wkiki, ref, etc, I learned a lot by following http://nsscreencast.com/episodes/6-afnetworking and understanding the associated code sample on github.

 // Add this to the class you're working with - (id)init {}
    _netInst = [MyApiClient sharedAFNetworkInstance];

  // build the dictionary that AFNetworkng converts to a json object on the next line
  //  params = {"user":{"email":emailAddress,"password":password}};
  NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
                             userName, @"email", password, @"password", nil];
  NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
                         parameters, @"user", nil];

   [_netInst postPath: @"users/login.json" parameters:params
      success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
        NSLog (@"SUCCESS");

        // jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
        _accessId = [jsonResponse valueForKeyPath:@"user.accessid"];
        _securityKey = [jsonResponse valueForKeyPath:@"user.securitykey"];

        return SUCCESS;
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"FAILED");

        // handle failure

        return error;
      }
   ];  

How to install and use "make" in Windows?

One solution that may helpful if you want to use the command line emulator cmder. You can install the package installer chocately. First we install chocately in windows command prompt using the following line:

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
refreshenv

After chocolatey is installed the choco command can be used to install make. Once installed, you will need add an alias to /cmder/config/user_aliases.cmd. The following line should be added:

make="path_to_chocolatey\chocolatey\bin\make.exe" $*

Make will then operate in the cmder environment.

How do I move a redis database from one server to another?

Nowadays you can also use MIGRATE, available since 2.6.

I had to use this since I only wanted to move the data in one database and not all of them. The two Redis instances live on two different machines.

If you can't connect directly to Redis-2 from Redis-1, use ssh port binding:

 ssh [email protected] -L 1234:127.0.0.1:6379

A small script to loop all the keys using KEYS and MIGRATE each key. This is Perl, but hopefully you get the idea:

 foreach ( $redis_from->keys('*') ) {

    $redis_from->migrate(
        $destination{host},    # localhost in my example
        $destination{port},    # 1234
        $_,                    # The key
        $destination{db},
        $destination{timeout} 
    );
 }

See http://redis.io/commands/migrate for more info.

Angular: conditional class with *ngClass

You can use ngClass to apply the class name both conditionally and not in Angular

For Example

[ngClass]="'someClass'">

Conditional

[ngClass]="{'someClass': property1.isValid}">

Multiple Condition

 [ngClass]="{'someClass': property1.isValid && property2.isValid}">

Method expression

[ngClass]="getSomeClass()"

This method will inside of your component

 getSomeClass(){
        const isValid=this.property1 && this.property2;
        return {someClass1:isValid , someClass2:isValid};
    }

How can I connect to a Tor hidden service using cURL in PHP?

I use Privoxy and cURL to scrape Tor pages:

<?php
    $ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_exec($ch);
    curl_close($ch);
?>

After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config). Note the space and '.' a the end of line.

forward-socks4a / localhost:9050 .

Then restart Privoxy.

/etc/init.d/privoxy restart

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

What special characters must be escaped in regular expressions?

POSIX recognizes multiple variations on regular expressions - basic regular expressions (BRE) and extended regular expressions (ERE). And even then, there are quirks because of the historical implementations of the utilities standardized by POSIX.

There isn't a simple rule for when to use which notation, or even which notation a given command uses.

Check out Jeff Friedl's Mastering Regular Expressions book.

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

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

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

How do I convert datetime.timedelta to minutes, hours in Python?

I don't think it's a good idea to caculate yourself.

If you just want a pretty output, just covert it into str with str() function or directly print() it.

And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()

git command to move a folder inside another

 git mv common include

should work.

From the git mv man page:

git mv [-f] [-n] [-k] <source> ... <destination directory>

In the second form, the last argument has to be an existing directory; the given sources will be moved into this directory.
The index is updated after successful completion, but the change must still be committed.

No "git add" should be done before the move.


Note: "git mv A B/", when B does not exist as a directory, should error out, but it didn't.

See commit c57f628 by Matthieu Moy (moy) for Git 1.9/2.0 (Q1 2014):

Git used to trim the trailing slash, and make the command equivalent to 'git mv file no-such-dir', which created the file no-such-dir (while the trailing slash explicitly stated that it could only be a directory).

This patch skips the trailing slash removal for the destination path.
The path with its trailing slash is passed to rename(2), which errors out with the appropriate message:

$ git mv file no-such-dir/
fatal: renaming 'file' failed: Not a directory

What's the difference between Sender, From and Return-Path?

So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.

The Sender header is used to identify in the message who submitted it. This is usually the same as the From header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.

The Return-Path header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.

For example, take a server that allows users to send mail from a web page. So, [email protected] types in a message and submits it. The server then sends the message to its recipient with From set to [email protected]. The actual SMTP submission uses different credentials, something like [email protected]. So, the sender header is set to [email protected], to indicate the From header doesn't indicate who actually submitted the message.

In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path would also be set to [email protected] so that any delivery reports go to it instead of the sender.

If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.

Restore LogCat window within Android Studio

Try going to Tools->Android->Enable ADB Integration

In my case it got automagically disabled

grant remote access of MySQL database from any IP address

  • START MYSQL using admin user
    • mysql -u admin-user -p (ENTER PASSWORD ON PROMPT)
  • Create a new user:
    • CREATE USER 'newuser'@'%' IDENTIFIED BY 'password'; (% -> anyhost)
  • Grant Privileges:
    • GRANT SELECT,DELETE,INSERT,UPDATE ON db_name.* TO 'newuser'@'%';
    • FLUSH PRIVILEGES;

If you are running EC2 instance don't forget to add the inbound rules in security group with MYSQL/Aurura.

Using the last-child selector

The :last-child pseudoclass still cannot be reliably used across browsers. In particular, Internet Explorer versions < 9, and Safari < 3.2 definitely don't support it, although Internet Explorer 7 and Safari 3.2 do support :first-child, curiously.

Your best bet is to explicitly add a last-child (or similar) class to that item, and apply li.last-child instead.

How to get Chrome to allow mixed content?

running the following command helps me running https web-page, with iframe which has ws (unsecured) connection

chrome.exe --user-data-dir=c:\temp-chrome --disable-web-security --allow-running-insecure-content

How to iterate over a std::map full of strings in C++

Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

How to do the equivalent of pass by reference for primitives in Java

Java is not call by reference it is call by value only

But all variables of object type are actually pointers.

So if you use a Mutable Object you will see the behavior you want

public class XYZ {

    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }

    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}

Output of this code:

run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)

You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.

    List<Integer> mutableList = new ArrayList<Integer>();

    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);

    System.out.println(mutableList);

    Collections.shuffle(mutableList);

    System.out.println(mutableList);

    Collections.sort(mutableList);

    System.out.println(mutableList);

Output of this code:

run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)

gdb fails with "Unable to find Mach task port for process-id" error

These instructions work for OSX High Sierra and avoid running gdb as root (yuck!). I recently updated from OSX 10.13.2 to 10.3.3. I think this is when gdb 8.0.1 (installed w/ homebrew) started failing for me.

I had difficulty with other people's instructions. After different instructions, everything was a mess. So I started a fresh. I more or less followed these instructions.

Clean the mess :

  1. brew uninstall --force gdb # This deletes _all_ versions of gdb on the machine
  2. In Applications -> Utilities -> Keychain Access, I deleted all previous gdb certificates and keys (be sure you know what you're doing here!). It's unclear if this is necessary, but since I'd buggered up trying to create those certificates and keys using other instructions I eliminated them anyways. I had keys and certificates in both login and system.

Now reinstall gdb.

  1. brew install gdb
  2. Within Keychain Access, go to menu Keychain Access-> Certificate Assistant -> Create a Certificate
  3. Check "Let me override defaults" and set
Name : gdb-cert
Identity Type: Self Signed Root
Certificate Type : Code Signing

[X] Let me override defaults
  1. On 1st Certificate Information page:
Serial Number : 1
Validity Period (days): 3650
  1. On 2nd Certificate Information page, I left all fields blank except those already filled in.

  2. On Key Pair Information page, I left the defaults

Key Size : 2048
Algorithm : RSA
  1. On Key Usage Extension page, I left the defaults checked.
[X] Include Key Usage Extension
[X] This extension is critical
Capabilities:
[X] Signature
  1. On Extended Key Usage Extension page, I left the defaults checked.
[X] Include Extended Key Usage Extension
[X] This extension is critical
Capabilities:
[X] Code Signing
  1. On Basic Constraints Extension Page, nothing was checked (default).

  2. On Subject Alternate Name Extension page, I left the default checked and didn't add anything else.

[X] Include Subject Alternate Name Extension
  1. On Specify a Location for the certificate page, I set
Keychain: System
  1. I clicked Create and was prompted for my password.

  2. Back in the Keychain Access app, I went to System and right clicked on gdb-cert and under dropdown menu Trust, I changed all the fields to Always Trust.

  3. Rebooted computer.

  4. At the Terminal, I ran codesign -s gdb-cert /usr/local/bin/gdb. I entered my password when prompted.

  5. At the Terminal, I ran echo "set startup-with-shell off" >> ~/.gdbinit

  6. I ran gdb myprogram and then start within the gdb console. Here, I believe, it prompted for me for my password. After that, all subsequent runs, it did not prompt for my password.

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to see query history in SQL Server Management Studio

If the queries you are interested in are dynamic queries that fail intermittently, you could log the SQL and the datetime and user in a table at the time the dynamic statement is created. It would be done on a case-by case basis though as it requires specific programming to happen and it takes a littel extra processing time, so do it only for those few queries you are most concerned about. But having a log of the specific statements executed can really help when you are trying to find out why it fails once a month only. Dynamic queries are hard to thoroughly test and sometimes you get one specific input value that just won't work and doing this logging at the time the SQL is created is often the best way to see what specifically wasn in the sql that was built.

Force page scroll position to top at page refresh in HTML

You can do it using the scrollTop method on DOM ready:

$(document).ready(function(){
    $(this).scrollTop(0);
});

Is there a way to cache GitHub credentials for pushing commits?

TLDR; Use an encrypted netrc file with Git 1.8.3+.

Saving a password for a Git repository HTTPS URL is possible with a ~/.netrc (Unix) or %HOME%/_netrc (note the _) on Windows.

But: That file would store your password in plain text.

Solution: Encrypt that file with GPG (GNU Privacy Guard), and make Git decrypt it each time it needs a password (for push/pull/fetch/clone operation).


Note: with Git 2.18 (Q2 2018), you now can customize the GPG used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'


Step-by-Step instructions for Windows

With Windows:

(Git has a gpg.exe in its distribution, but using a full GPG installation includes a gpg-agent.exe, which will memorize your passphrase associated to your GPG key.)

  • Install gpg4Win Lite, the minimum gnupg command-line interface (take the most recent gpg4win-vanilla-2.X.Y-betaZZ.exe), and complete your PATH with the GPG installation directory:

    set PATH=%PATH%:C:\path\to\gpg
    copy C:\path\to\gpg\gpg2.exe C:\path\to\gpg\gpg.exe
    

(Note the 'copy' command: Git will need a Bash script to execute the command 'gpg'. Since gpg4win-vanilla-2 comes with gpg2.exe, you need to duplicate it.)

  • Create or import a GPG key, and trust it:

    gpgp --import aKey
    # or
    gpg --gen-key
    

(Make sure to put a passphrase to that key.)

  • Trust that key

  • Install the credential helper script in a directory within your %PATH%:

    cd c:\a\fodler\in\your\path
    curl -o c:\prgs\bin\git-credential-netrc https://raw.githubusercontent.com/git/git/master/contrib/credential/netrc/git-credential-netrc.perl
    

(Beware: the script is renamed in Git 2.25.x/2.26, see below)

(Yes, this is a Bash script, but it will work on Windows since it will be called by Git.)

  • Make a _netrc file in clear text

    machine a_server.corp.com
    login a_login
    password a_password
    protocol https
    
    machine a_server2.corp.com
    login a_login2
    password a_password2
    protocol https
    

(Don't forget the 'protocol' part: 'http' or 'https' depending on the URL you will use.)

  • Encrypt that file:

    gpg -e -r a_recipient _netrc
    

(You now can delete the _netrc file, keeping only the _netrc.gpg encrypted one.)

  • Use that encrypted file:

    git config --local credential.helper "netrc -f C:/path/to/_netrc.gpg -v"
    

(Note the '/': C:\path\to... wouldn't work at all.) (You can use at first -v -d to see what is going on.)

From now on, any Git command using an HTTP(S) URL which requires authentication will decrypt that _netrc.gpg file and use the login/password associated to the server you are contacting. The first time, GPG will ask you for the passphrase of your GPG key, to decrypt the file. The other times, the gpg-agent launched automatically by the first GPG call will provide that passphrase for you.

That way, you can memorize several URLs/logins/passwords in one file, and have it stored on your disk encrypted.
I find it more convenient than a "cache" helper", where you need to remember and type (once per session) a different password for each of your remote services, for said password to be cached in memory.


With Git 2.26 (Q1 2020), the sample credential helper for using .netrc has been updated to work out of the box. See patch/discussion.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: make PERL_PATH configurable

Signed-off-by: Denton Liu

The shebang path for the Perl interpreter in git-credential-netrc was hardcoded.
However, some users may have it located at a different location and thus, would have had to manually edit the script.

Add a .perl prefix to the script to denote it as a template and ignore the generated version.
Augment the Makefile so that it generates git-credential-netrc from git-credential-netrc.perl, just like other Perl scripts.

The Makefile recipes were shamelessly stolen from contrib/mw-to-git/Makefile.

And:

With 2.26 (Q1 2020), Sample credential helper for using .netrc has been updated to work out of the box.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: work outside a repo

Signed-off-by: Denton Liu

Currently, git-credential-netrc does not work outside of a git repository. It fails with the following error:

fatal: Not a git repository: . at /usr/share/perl5/Git.pm line 214.

There is no real reason why need to be within a repository, though. Credential helpers should be able to work just fine outside the repository as well.

Call the non-self version of config() so that git-credential-netrc no longer needs to be run within a repository.

Jeff King (peff) adds:

I assume you're using a gpg-encrypted netrc (if not, you should probably just use credential-store).
For "read-only" password access, I find the combination of pass with config like this is a bit nicer:

[credential "https://github.com"]
  username = peff
  helper = "!f() { test $1 = get && echo password=`pass github/oauth`; }; f"

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

ASP.NET MVC on IIS 7.5

We had a MVC application moved to a new server. .NET 4 and MVC 3 was installed, but we still got “Error 403.14". In this case, this meant that IIS did not understand that it was dealing with a MVC application, it was looking for the default page.

The solution was simple: HTTP Redirection was not installed on the server.

Server Manager – Roles – Web Server (IIS) – Roles Services – HTTP Redirection: Not installed. Installed it, problem solved.

How to validate date with format "mm/dd/yyyy" in JavaScript?

It's ok if you want to check validate dd/MM/yyyy

_x000D_
_x000D_
function isValidDate(date) {_x000D_
    var temp = date.split('/');_x000D_
    var d = new Date(temp[1] + '/' + temp[0] + '/' + temp[2]);_x000D_
     return (d && (d.getMonth() + 1) == temp[1] && d.getDate() == Number(temp[0]) && d.getFullYear() == Number(temp[2]));_x000D_
}_x000D_
_x000D_
alert(isValidDate('29/02/2015')); // it not exist ---> false_x000D_
            
_x000D_
_x000D_
_x000D_

Override and reset CSS style: auto or none don't work

Set min-width: inherit /* Reset the min-width */

Try this. It will work.

What does the term "canonical form" or "canonical representation" in Java mean?

A canonical form means a naturally unique representation of the element

Xcode : Adding a project as a build dependency

To add it as a dependency do the following:

  • Highlight the added project in your file explorer within xcode. In the directory browser window to the right it should show a file with a .a extension. There is a checkbox under the target column (target icon), check it.
  • Right-Click on your Target (under the targets item in the file explorer) and choose Get Info
  • On the general tab is a Direct Dependencies section. Hit the plus button
  • Choose the project and click Add Target

How to access a value defined in the application.properties file in Spring Boot

Currently, I know about the following three ways:

1. The @Value annotation

    @Value("${<property.name>}")
    private static final <datatype> PROPERTY_NAME;
  • In my experience there are some situations when you are not able to get the value or it is set to null. For instance, when you try to set it in a preConstruct() method or an init() method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the 3'rd option.

2. The @PropertySource annotation

<pre>@PropertySource("classpath:application.properties")

//env is an Environment variable
env.getProperty(configKey);</pre>
  • PropertySouce sets values from the property source file in an Environment variable (in your class) when the class is loaded. So you able to fetch easily afterword.
    • Accessible through System Environment variable.

3. The @ConfigurationProperties annotation.

  • This is mostly used in Spring projects to load configuration properties.
  • It initializes an entity based on property data.

    • @ConfigurationProperties identifies the property file to load.
    • @Configuration creates a bean based on configuration file variables.
    @ConfigurationProperties(prefix = "user")
    @Configuration("UserData")
    class user {
      //Property & their getter / setter
    }
    
    @Autowired
    private UserData userData;
    
    userData.getPropertyName();

Vertical Tabs with JQuery?

Another options is Matteo Bicocchi's jQuery mb.extruder tabs plug-in: http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-extruder/

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

How do I access command line arguments in Python?

Some additional things that I can think of.

As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.

Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

Add alternating row color to SQL Server Reporting services report

One thing I noticed is that neither of the top two methods have any notion of what color the first row should be in a group; the group will just start with the opposite color from the last line of the previous group. I wanted my groups to always start with the same color...the first row of each group should always be white, and the next row colored.

The basic concept was to reset the toggle when each group starts, so I added a bit of code:

Private bOddRow As Boolean
'*************************************************************************
' -- Display green-bar type color banding in detail rows
' -- Call from BackGroundColor property of all detail row textboxes
' -- Set Toggle True for first item, False for others.
'*************************************************************************
Function AlternateColor(ByVal OddColor As String, _
         ByVal EvenColor As String, ByVal Toggle As Boolean) As String
    If Toggle Then bOddRow = Not bOddRow
    If bOddRow Then
        Return OddColor
    Else
        Return EvenColor
    End If
End Function
'
Function RestartColor(ByVal OddColor As String) As String
    bOddRow = True
    Return OddColor
End Function

So I have three different kinds of cell backgrounds now:

  1. First column of data row has =Code.AlternateColor("AliceBlue", "White", True) (This is the same as the previous answer.)
  2. Remaining columns of data row have =Code.AlternateColor("AliceBlue", "White", False) (This, also, is the same as the previous answer.)
  3. First column of grouping row has =Code.RestartColor("AliceBlue") (This is new.)
  4. Remaining columns of grouping row have =Code.AlternateColor("AliceBlue", "White", False) (This was used before, but no mention of it for grouping row.)

This works for me. If you want the grouping row to be non-colored, or a different color, it should be fairly obvious from this how to change it around.

Please feel free to add comments about what could be done to improve this code: I'm brand new to both SSRS and VB, so I strongly suspect that there's plenty of room for improvement, but the basic idea seems sound (and it was useful for me) so I wanted to throw it out here.

PowerShell to remove text from a string

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

returns

keep this

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Firefox 'Cross-Origin Request Blocked' despite headers

Just add

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

to the .htaccess file in the root of the website you are trying to connect with.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

Removing some unnecessary SQL and then COUNT(*) will be faster than SQL_CALC_FOUND_ROWS. Example:

SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name

Then count without unnecessary part:

SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

navigate to C:\wamp64\alias\phpmyadmin.conf and change from:

php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M

to

php_admin_value upload_max_filesize 2048M
php_admin_value post_max_size 2048M

or more :)

What should be in my .gitignore for an Android Studio project?

Updated 7/2015:

Here is the definitive source from JetBrains


Directory based project format (.idea directory)

This format is used by all the recent IDE versions by default. Here is what you need to share:

  • All the files under .idea directory in the project root except the workspace.xml and tasks.xml files which store user specific settings
  • All the .iml module files that can be located in different module directories (applies to IntelliJ IDEA)

Be careful about sharing the following:

  • Android artifacts that produce a signed build (will contain keystore passwords)
  • In IDEA 13 and earlier dataSources.ids, datasources.xml can contain database passwords. IDEA 14 solves this problem.

You may consider not to share the following:

  • gradle.xml file, see this discussion
  • user dictionaries folder (to avoid conflicts if other developer has the same name)
  • XML files under .idea/libraries in case they are generated from Gradle project

Legacy project format (.ipr/.iml/.iws files)

  • Share the project .ipr file and all the .iml module files, don't share the .iws file as it stores user specific settings

While these instructions are for IntelliJ IDEA, they hold true 100% for Android Studio.


Here is a .gitignore snippet that incorporates all of the above rules:

# Android Studio / IntelliJ IDEA 
*.iws
.idea/libraries
.idea/tasks.xml
.idea/vcs.xml
.idea/workspace.xml

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.

Model Binding to a List MVC 4

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

Action:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

Convert pandas dataframe to NumPy array

Try this:

np.array(df) 

array([['ID', nan, nan, nan],
   ['1', nan, 0.2, nan],
   ['2', nan, nan, 0.5],
   ['3', nan, 0.2, 0.5],
   ['4', 0.1, 0.2, nan],
   ['5', 0.1, 0.2, 0.5],
   ['6', 0.1, nan, 0.5],
   ['7', 0.1, nan, nan]], dtype=object)

Some more information at: [https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html] Valid for numpy 1.16.5 and pandas 0.25.2.

Reactjs: Unexpected token '<' Error

in my case, i had failed to include the type attribute on my script tag.

<script type="text/jsx">

How to remove a character at the end of each line in unix

Try doing this :

awk '{print substr($0, 1, length($0)-1)}' file.txt

This is more generic than just removing the final comma but any last character

If you'd want to only remove the last comma with awk :

awk '{gsub(/,$/,""); print}' file.txt

Change GridView row color based on condition

Create GridView1_RowDataBound event for your GridView.

//Check if it is not header or footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
    //Check your condition here
    If(Condition True)
    {
        e.Row.BackColor = Drawing.Color.Red // This will make row back color red
    }
}

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

Under what conditions is a JSESSIONID created?

For links generated in a JSP with custom tags, I had to use

<%@ page session="false" %>

in the JSP

AND

request.getSession().invalidate();

in the Struts action

How to overwrite the output directory in spark

From the pyspark.sql.DataFrame.save documentation (currently at 1.3.1), you can specify mode='overwrite' when saving a DataFrame:

myDataFrame.save(path='myPath', source='parquet', mode='overwrite')

I've verified that this will even remove left over partition files. So if you had say 10 partitions/files originally, but then overwrote the folder with a DataFrame that only had 6 partitions, the resulting folder will have the 6 partitions/files.

See the Spark SQL documentation for more information about the mode options.

HTML-encoding lost when attribute read from input field

You shouldn't have to escape/encode values in order to shuttle them from one input field to another.

<form>
 <input id="button" type="button" value="Click me">
 <input type="hidden" id="hiddenId" name="hiddenId" value="I like cheese">
 <input type="text" id="output" name="output">
</form>
<script>
    $(document).ready(function(e) {
        $('#button').click(function(e) {
            $('#output').val($('#hiddenId').val());
        });
    });
</script>

JS doesn't go inserting raw HTML or anything; it just tells the DOM to set the value property (or attribute; not sure). Either way, the DOM handles any encoding issues for you. Unless you're doing something odd like using document.write or eval, HTML-encoding will be effectively transparent.

If you're talking about generating a new textbox to hold the result...it's still as easy. Just pass the static part of the HTML to jQuery, and then set the rest of the properties/attributes on the object it returns to you.

$box = $('<input type="text" name="whatever">').val($('#hiddenId').val());

How to persist a property of type List<String> in JPA?

According to Java Persistence with Hibernate

mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard

If you were using Hibernate, you could do something like:

@org.hibernate.annotations.CollectionOfElements(
    targetElement = java.lang.String.class
)
@JoinTable(
    name = "foo",
    joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
    name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();

Update: Note, this is now available in JPA2.

How can I check that JButton is pressed? If the isEnable() is not work?

Seems you need to use JToggleButton :

JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        JToggleButton btn =  (JToggleButton) e.getSource();
        btn.setText(btn.isSelected() ? "pushed" : "push me");
    }
});

Return list of items in list greater than some value

There is another way,

j3 = j2 > 4; print(j2[j3])

tested in 3.x

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(). My example is taken from the docs http://junit.org/junit5/docs/current/user-guide/

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

....

@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("a message");
    });
    assertEquals("a message", exception.getMessage());
}

If "0" then leave the cell blank

An accrual ledger should note zeroes, even if that is the hyphen displayed with an Accounting style number format. However, if you want to leave the line blank when there are no values to calculate use a formula like the following,

 =IF(COUNT(F16:G16), SUM(G16, INDEX(H$1:H15, MATCH(1e99, H$1:H15)), -F16), "")

That formula is a little tricky because you seem to have provided your sample formula from somewhere down into the entries of the ledger's item rows without showing any layout or sample data. The formula I provided should be able to be put into H16 and then copied or filled to other locations in column H but I offer no guarantees without seeing the layout.

If you post some sample data or a publicly available link to a screenshot showing your data layout more specific assistance could be offered. http://imgur.com/ is a good place to host a screenshot and it is likely that someone with more reputation will insert the image into your question for you.

How do I enable C++11 in gcc?

As previously mentioned - in case of a project, Makefile or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.

But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out?

Well, I would much like to have some #pragma to turn in on at source level, or maybe a default extension - say .cxx or .C11 or whatever, trigger it by default. But as of today, there is no such feature.

But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc (or whatever):

alias g++11="g++ -std=c++0x"

or, for newer G++ (and when you want to feel "real C++11")

alias g++11="g++ -std=c++11"

You can even alias to g++ itself, if you hate C++03 that much ;)

Python error: "IndexError: string index out of range"

It looks like you indented so_far = new too much. Try this:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

How to stop event propagation with inline onclick attribute?

The best solution would be handle with the event through a javascript function, but in order to use a simple and quick solution using the html element directly, and once that the "event" and "window.event" are deprecated and not universally supported (https://developer.mozilla.org/en-US/docs/Web/API/Window/event), I suggest the following "hard code":

<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>

C/C++ Struct vs Class

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

Remove duplicates from an array of objects in JavaScript

Here is a solution for ES6 where you only want to keep the last item. This solution is functional and Airbnb style compliant.

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

MongoDB what are the default user and password?

In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth switch). In order to do that, you need to have localhost access to the server and then run:

mongo
use admin
db.createUser(
 {
     user: "user_name",
     pwd: "user_pass",
     roles: [
           { role: "userAdminAnyDatabase", db: "admin" },
           { role: "readWriteAnyDatabase", db: "admin" },
           { role: "dbAdminAnyDatabase", db: "admin" }
        ]
 })

As stated in MongoDB documentation:

The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.

Here is the link to that section of the docs.

Cannot find the declaration of element 'beans'

Add this code ..It helped me

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:context="http://www.springframework.org/schema/context" 
         xmlns:aop="http://www.springframework.org/schema/aop" 
         xsi:schemaLocation="
         http://www.springframework.org/schema/beans 
           classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd 
         http://www.springframework.org/schema/context 
         classpath:/org/springframework/context/config/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop 
        classpath:/org/springframework/aop/config/spring-aop-3.0.xsd
         ">      
     </beans>

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

Retrieve the maximum length of a VARCHAR column in SQL Server

for mysql its length not len

SELECT MAX(LENGTH(Desc)) FROM table_name

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

XML parsing of a variable string in JavaScript

Please take a look at XML DOM Parser (W3Schools). It's a tutorial on XML DOM parsing. The actual DOM parser differs from browser to browser but the DOM API is standardised and remains the same (more or less).

Alternatively use E4X if you can restrict yourself to Firefox. It's relatively easier to use and it's part of JavaScript since version 1.6. Here is a small sample usage...

//Using E4X
var xmlDoc=new XML();
xmlDoc.load("note.xml");
document.write(xmlDoc.body); //Note: 'body' is actually a tag in note.xml,
//but it can be accessed as if it were a regular property of xmlDoc.

How to install php-curl in Ubuntu 16.04

In Ubuntu 16.04 default PHP version is 7.0, if you want to use different version then you need to install PHP package according to PHP version:

  • PHP 7.4: sudo apt-get install php7.4-curl
  • PHP 7.3: sudo apt-get install php7.3-curl
  • PHP 7.2: sudo apt-get install php7.2-curl
  • PHP 7.1: sudo apt-get install php7.1-curl
  • PHP 7.0: sudo apt-get install php7.0-curl
  • PHP 5.6: sudo apt-get install php5.6-curl
  • PHP 5.5: sudo apt-get install php5.5-curl

How to create id with AUTO_INCREMENT on Oracle?

Trigger and Sequence can be used when you want serialized number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like emp_id) by this way, and value of this column is not much considerable, you can use SYS_GUID() at Table Creation to get Auto Increment like this.

CREATE TABLE <table_name> 
(emp_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));

Now your emp_id column will accept "globally unique identifier value". you can insert value in table by ignoring emp_id column like this.

INSERT INTO <table_name> (name) VALUES ('name value');

So, it will insert unique value to your emp_id Column.

T-SQL: Opposite to string concatenation - how to split string into multiple records

I wrote this awhile back. It assumes the delimiter is a comma and that the individual values aren't bigger than 127 characters. It could be modified pretty easily.

It has the benefit of not being limited to 4,000 characters.

Good luck!

ALTER Function [dbo].[SplitStr] ( 
        @txt text 
) 
Returns @tmp Table 
        ( 
                value varchar(127)
        ) 
as 
BEGIN 
        declare @str varchar(8000) 
                , @Beg int 
                , @last int 
                , @size int 

        set @size=datalength(@txt) 
        set @Beg=1 


        set @str=substring(@txt,@Beg,8000) 
        IF len(@str)<8000 set @Beg=@size 
        ELSE BEGIN 
                set @last=charindex(',', reverse(@str)) 
                set @str=substring(@txt,@Beg,8000-@last) 
                set @Beg=@Beg+8000-@last+1 
        END 

        declare @workingString varchar(25) 
                , @stringindex int 



        while @Beg<=@size Begin 
                WHILE LEN(@str) > 0 BEGIN 
                        SELECT @StringIndex = CHARINDEX(',', @str) 

                        SELECT 
                                @workingString = CASE 
                                        WHEN @StringIndex > 0 THEN SUBSTRING(@str, 1, @StringIndex-1) 
                                        ELSE @str 
                                END 

                        INSERT INTO 
                                @tmp(value)
                        VALUES 
                                (cast(rtrim(ltrim(@workingString)) as varchar(127)))
                        SELECT @str = CASE 
                                WHEN CHARINDEX(',', @str) > 0 THEN SUBSTRING(@str, @StringIndex+1, LEN(@str)) 
                                ELSE '' 
                        END 
                END 
                set @str=substring(@txt,@Beg,8000) 

                if @Beg=@size set @Beg=@Beg+1 
                else IF len(@str)<8000 set @Beg=@size 
                ELSE BEGIN 
                        set @last=charindex(',', reverse(@str)) 
                        set @str=substring(@txt,@Beg,8000-@last) 
                        set @Beg=@Beg+8000-@last+1 

                END 
        END     

        return
END 

Remove an onclick listener

Setting setOnClickListener(null) is a good idea to remove click listener at runtime.

And also someone commented that calling View.hasOnClickListeners() after this will return true, NO my friend.

Here is the implementation of hasOnClickListeners() taken from android.view.View class

 public boolean hasOnClickListeners() {
        ListenerInfo li = mListenerInfo;
        return (li != null && li.mOnClickListener != null);
    }

Thank GOD. It checks for null.

So everything is safe. Enjoy :-)

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

How to get the background color of an HTML element?

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

How do you round a number to two decimal places in C#?

You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)

You can read more here.

How do I define and use an ENUM in Objective-C?

I recommend using NS_OPTIONS or NS_ENUM. You can read more about it here: http://nshipster.com/ns_enum-ns_options/

Here's an example from my own code using NS_OPTIONS, I have an utility that sets a sublayer (CALayer) on a UIView's layer to create a border.

The h. file:

typedef NS_OPTIONS(NSUInteger, BSTCMBorder) {
    BSTCMBOrderNoBorder     = 0,
    BSTCMBorderTop          = 1 << 0,
    BSTCMBorderRight        = 1 << 1,
    BSTCMBorderBottom       = 1 << 2,
    BSTCMBOrderLeft         = 1 << 3
};

@interface BSTCMBorderUtility : NSObject

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color;

@end

The .m file:

@implementation BSTCMBorderUtility

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color
{

    // Make a left border on the view
    if (border & BSTCMBOrderLeft) {

    }

    // Make a right border on the view
    if (border & BSTCMBorderRight) {

    }

    // Etc

}

@end

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

net use \\<host> /delete should work, but many times it does not.

net stop workstation as @DaveInCaz offered works in such cases.

I have some why and hows I couldn't fit into a comment.

  • It's not enough to restart the Workstation service (e.g. from services.msc console)
    The service probably needs to be disabled for some short period of time. If you do this restart from a script, might be better to add a 1 second delay.

  • In cases when net use \\<host> /delete does not work because another program is still using that share, you can identify such program and remove the blocking handle without closing it. Use Sysinternals Process Explorer, press Ctrl+F for search and enter the name of host machine owning such share. Click on each result, program window behind search dialog jumps to found program's handle. Right click that handle and select Close Handle. (or just close such program if you can) This works only in regular cases where there really is a program blocking the share disconnect. Not in those weird cases when it's blocked for no reason.

  • elevated account has it's own environment. This brings some unexpected behavior.
    If you do net use command in an elevated cmd/PS console, it will not affect which user will Windows Explorer use to access the share.
    And also other way around, if you run a program from the share and the program will ask and get elevated access, that program will loose connection to that share and any files it might need to run. You need to run net use from elevated cmd/PS to create an elevated share connection to that share.

  • Removing Recent folders from Quick Access in Windows Explorer (top of left panel) might help in certain cases.
    If the Host you are connecting to offers different access levels based on user, and/or has a Guest user (anonymous) share access, this is a situation you might often run into.
    When you access a share using your username, folder inside such share might get assigned to Quick Access panel as a Recent item. When you open Windows Explorer after restart, Recent items inside Quick Access will be checked and a connection will be made to the Host machine and will stay open in form of a MUP. If your share accepts both authorized and anonymous connections, just opening Windows Explorer will create anonymous connection and when you click on a share which needs authorization, you will not get credential dialog but an error.

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

How to concatenate two numbers in javascript?

Use "" + 5 + 6 to force it to strings. This works with numerical variables too:

_x000D_
_x000D_
var a = 5;_x000D_
var b = 6;_x000D_
console.log("" + a + b);
_x000D_
_x000D_
_x000D_

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Avoid Adding duplicate elements to a List C#

Your this check:

if (!lines2.Contains(lines3.ToString()))

is invalid. You are checking if your lines2 contains System.String[] since lines3.ToString() will give you that. You need to check if item from lines3 exists in lines2 or not.

You can iterate each item in lines3 check if it exists in the lines2 and then add it. Something like.

foreach (string str in lines3)
{
    if (!lines2.Contains(str))
        lines2.Add(str);
}

Or if your lines2 is any empty list, then you can simply add the lines3 distinct values to the list like:

lines2.AddRange(lines3.Distinct());

then your lines2 will contain distinct values.

SFTP in Python? (platform independent)

With RSA Key then refer here

Snippet:

import pysftp
import paramiko
from base64 import decodebytes

keydata = b"""AAAAB3NzaC1yc2EAAAADAQABAAABAQDl""" 
key = paramiko.RSAKey(data=decodebytes(keydata)) 
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add(host, 'ssh-rsa', key)


with pysftp.Connection(host=host, username=username, password=password, cnopts=cnopts) as sftp:   
  with sftp.cd(directory):
    sftp.put(file_to_sent_to_ftp)

How to initialize/instantiate a custom UIView class with a XIB file in Swift

override func draw(_ rect: CGRect) 
{
    AlertView.layer.cornerRadius = 4
    AlertView.clipsToBounds = true

    btnOk.layer.cornerRadius = 4
    btnOk.clipsToBounds = true   
}

class func instanceFromNib() -> LAAlertView {
    return UINib(nibName: "LAAlertView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! LAAlertView
}

@IBAction func okBtnDidClicked(_ sender: Any) {

    removeAlertViewFromWindow()

    UIView.animate(withDuration: 0.4, delay: 0.0, options: .allowAnimatedContent, animations: {() -> Void in
        self.AlertView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)

    }, completion: {(finished: Bool) -> Void in
        self.AlertView.transform = CGAffineTransform.identity
        self.AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        self.AlertView.isHidden = true
        self.AlertView.alpha = 0.0

        self.alpha = 0.5
    })
}


func removeAlertViewFromWindow()
{
    for subview  in (appDel.window?.subviews)! {
        if subview.tag == 500500{
            subview.removeFromSuperview()
        }
    }
}


public func openAlertView(title:String , string : String ){

    lblTital.text  = title
    txtView.text  = string

    self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
    appDel.window!.addSubview(self)


    AlertView.alpha = 1.0
    AlertView.isHidden = false

    UIView.animate(withDuration: 0.2, animations: {() -> Void in
        self.alpha = 1.0
    })
    AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)

    UIView.animate(withDuration: 0.3, delay: 0.2, options: .allowAnimatedContent, animations: {() -> Void in
        self.AlertView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)

    }, completion: {(finished: Bool) -> Void in
        UIView.animate(withDuration: 0.2, animations: {() -> Void in
            self.AlertView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)

        })
    })


}

PHP write file from input to txt

Your form should look like this :

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

and the PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

I wrote to /tmp/mydata.txt because this way I know exactly where it is. using data.txt writes to that file in the current working directory which I know nothing of in your example.

file_put_contents opens, writes and closes files for you. Don't mess with it.

Further reading: file_put_contents

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

SQL Error: 0, SQLState: 08S01 Communications link failure

I'm answering on specific to this error code(08s01).

usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".

1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.

2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days

3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.

In Linux, how to tell how much memory processes are using?

Use top or htop and pay attention to the "RES" (resident memory size) column.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

Why dict.get(key) instead of dict[key]?

Based on usage should use this get method.

Example1

In [14]: user_dict = {'type': False}

In [15]: user_dict.get('type', '')

Out[15]: False

In [16]: user_dict.get('type') or ''

Out[16]: ''

Example2

In [17]: user_dict = {'type': "lead"}

In [18]: user_dict.get('type') or ''

Out[18]: 'lead'

In [19]: user_dict.get('type', '')

Out[19]: 'lead'

What is Ad Hoc Query?

An Ad-Hoc query is:

  1. Pre-planned question.
  2. Pre-scheduled question.
  3. spur of the moment question.
  4. Question that will not return any results.

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

Put text at bottom of div

Thanks @Harry the following code works for me:

.your-div{
   vertical-align: bottom;
   display: table-cell;
}

Swift double to string

let double = 1.5 
let string = double.description

update Xcode 7.1 • Swift 2.1:

Now Double is also convertible to String so you can simply use it as you wish:

let double = 1.5
let doubleString = String(double)   // "1.5"

Swift 3 or later we can extend LosslessStringConvertible and make it generic

Xcode 11.3 • Swift 5.1 or later

extension LosslessStringConvertible { 
    var string: String { .init(self) } 
}

let double = 1.5 
let string = double.string  //  "1.5"

For a fixed number of fraction digits we can extend FloatingPoint protocol:

extension FloatingPoint where Self: CVarArg {
    func fixedFraction(digits: Int) -> String {
        .init(format: "%.*f", digits, self)
    }
}

If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter:

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.minimumFractionDigits = min
        Formatter.number.maximumFractionDigits = max
        Formatter.number.roundingMode = roundingMode
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

2.12345.fractionDigits()                                    // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up)   // "2.124"

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How to specify an element after which to wrap in css flexbox?

You can accomplish this by setting this on the container:

ul {
    display: flex;
    flex-wrap: wrap;
}

And on the child you set this:

li:nth-child(2n) {
    flex-basis: 100%;
}

_x000D_
_x000D_
ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}

li:nth-child(4n) {
  flex-basis: 100%;
}
_x000D_
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
_x000D_
_x000D_
_x000D_

This causes the child to make up 100% of the container width before any other calculation. Since the container is set to break in case there is not enough space it does so before and after this child. So you could use an empty div element to force the wrap between the element before and after it.

How to parse JSON using Node.js?

Use JSON.parse(str);. Read more about it here.

Here are some examples:

var jsonStr = '{"result":true, "count":42}';

obj = JSON.parse(jsonStr);

console.log(obj.count);    // expected output: 42
console.log(obj.result);   // expected output: true

dplyr change many data types

From the bottom of the ?mutate_each (at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if, mutate_all, and mutate_at. The one most similar to what @hadley mentions in his comment is probably using mutate_at. Note the order of the arguments is reversed, compared to mutate_each, and vars() uses select() like semantics, which I interpret to mean the ?select_helpers functions.

dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%   
  mutate_at(vars(starts_with("dbl")),funs(as.numeric))

But mutate_at can take column numbers instead of a vars() argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at but with grep to capture many different kinds of column names at once (unless you always have such obvious column names!)

dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
  mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))

I was pretty excited about figuring out mutate_at + grep, because now one line can work on lots of columns.

EDIT - now I see matches() in among the select_helpers, which handles regex, so now I like this.

dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
  mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))

Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.

  mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))

Get div's offsetTop positions in React

I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

Example code:

import { useRef } from 'react'

function Component() {
  const inputRef = useRef()

  return (
    <input ref={inputRef} />
    <div
      onScroll={() => {
        const { offsetTop } = inputRef.current
        ...
      }}
    >
  )
}

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

Display all items in array using jquery

Use any examples that don't insert each element one at a time, one insertion is most efficient

 $('.element').html( '<span>' + array.join('</span><span>')+'</span>');

Adding a newline character within a cell (CSV)

I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.

I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"

When I import it to excel(google), excel understand it as string. It still not break new line.

We need to trigger excel to treat it as formula by: Format -> Number | Scientific.

This is not the good way but it resolve my issue.

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

Java: Add elements to arraylist with FOR loop where element name has increasing number

Put the answers into an array and iterate over it:

List<Answer> answers = new ArrayList<Answer>(3);

for (Answer answer : new Answer[] {answer1, answer2, answer3}) {
    list.add(answer);
}

EDIT

See João's answer for a much better solution. I'm still leaving my answer here as another option.

String replace method is not replacing characters

You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

sentence = sentence.replace("and", " ");

A String is immutable in java. Methods like replace return a new String.

Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

Angular 2 - NgFor using numbers instead collections

you can also use like that

export class SampleComponent {
   numbers:Array<any> = [];
   constructor() {
      this.numbers = Array.from({length:10},(v,k)=>k+1);
   }
}

HTML

<p *ngFor="let i of numbers">
   {{i}}
</p>

css rotate a pseudo :after or :before content:""

.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.

Android studio Gradle build speed up

It often happens when you enabled multidex in you project. This can potentially slow your development process!! According doc:

multidex configuration requires significantly increased build processing time because the build system must make complex decisions about which classes must be included in the primary DEX file and which classes can be included in secondary DEX files. This means that incremental builds using multidex typically take longer and can potentially slow your development process.

but you can optimize this:

To mitigate longer incremental build times, you should use pre-dexing to reuse multidex output between builds.

If you're using Android Studio 2.3 and higher, the IDE automatically uses this feature when deploying your app to a device running Android 5.0 (API level 21) or higher.

So you need to set the minSdkVersion to 21 or higher!

But if you production version need to support minSdkVersion lower than 21, for example 19

you can use productFlavors to set minSdkVersion 21 for you dev version:

    android {
    defaultConfig {
        ...
        multiDexEnabled true
        // The default minimum API level you want to support.
        minSdkVersion 15
    }
    productFlavors {
        // Includes settings you want to keep only while developing your app.
        dev{
            //the IDE automatically uses  pre-dexing feature to mitigate longer incremental when deploying your app to a device running Android 5.0 !
            minSdkVersion 21
        }
        prod {

        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                                                 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile 'com.android.support:multidex:1.0.3'
}

Set style for TextView programmatically

Dynamically changing styles is not supported (yet). You have to set the style before the view gets created, via XML.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to style readonly attribute with CSS?

input[readonly], input:read-only {
    /* styling info here */
}

Shoud cover all the cases for a readonly input field...

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

How to install SQL Server Management Studio 2012 (SSMS) Express?

Good evening,

The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.

Cheers.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

For my Android Studio workout. I found that this happen when I change Compile SDK Version from API23 (Android 6) to be API17 (Android 4.2) manually in Project Structure setting, and trying to change some code in layout files.

I miss-understood that I have to change it manually, even on New Project I have selected the "Minimum SdK" to be 4.2 already.

Solve by just change it back to API23, and it still can run on Android 4.2. ^^

Converting a string to a date in JavaScript

Pass it as an argument to Date():

var st = "date in some format"
var dt = new Date(st);

You can access the date, month, year using, for example: dt.getMonth().

How to open a PDF file in an <iframe>?

Do it like this: Remember to close iframe tag.

<iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe>

Reverse of JSON.stringify?

Recommended is to use JSON.parse

There is an alternative you can do :

 var myObject = eval('(' + myJSONtext + ')');

Json in javascript

Why is using the JavaScript eval function a bad idea?

Transfer data from one database to another database

There are several ways to do this, below are two options:

Option 1 - Right click on the database you want to copy

  • Choose 'Tasks' > 'Generate scripts'

  • 'Select specific database objects'

  • Check 'Tables'

  • Mark 'Save to new query window'

  • Click 'Advanced'

  • Set 'Types of data to script' to 'Schema and data'

  • Next, Next

You can now run the generated query on the new database.

Option 2

  • Right click on the database you want to copy

  • 'Tasks' > 'Export Data'

  • Next, Next

  • Choose the database to copy the tables to

  • Mark 'Copy data from one or more tables or views'

  • Choose the tables you want to copy

  • Finish

Generating UML from C++ code?

UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.

Methods vs Constructors in Java

In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class like so:

public class Apple {
    //instance variables
    String type; // macintosh, green, red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // in here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * this is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

Hopefully I explained everything in the comments of the code, but here is a summary: Constructors 'construct' an object of type of the class. The constructor must be named the same thing as the class. They are mostly used for initializing instance varibales Methods are functionality of the objects.

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

How do I get a UTC Timestamp in JavaScript?

  1. Dates constructed that way use the local timezone, making the constructed date incorrect. To set the timezone of a certain date object is to construct it from a date string that includes the timezone. (I had problems getting that to work in an older Android browser.)

  2. Note that getTime() returns milliseconds, not plain seconds.

For a UTC/Unix timestamp, the following should suffice:

Math.floor((new Date()).getTime() / 1000)

It will factor the current timezone offset into the result. For a string representation, David Ellis' answer works.

To clarify:

new Date(Y, M, D, h, m, s)

That input is treated as local time. If UTC time is passed in, the results will differ. Observe (I'm in GMT +02:00 right now, and it's 07:50):

> var d1 = new Date();
> d1.toUTCString();
"Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time
> Math.floor(d1.getTime()/ 1000)
1332049834 

> var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() );
> d2.toUTCString();
"Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!
> Math.floor(d2.getTime()/ 1000)
1332042634

Also note that getUTCDate() cannot be substituted for getUTCDay(). This is because getUTCDate() returns the day of the month; whereas, getUTCDay() returns the day of the week.

Execute a PHP script from another PHP script

You can invoke a PHP script manually from the command line

hello.php
<?php
 echo 'hello world!';
?>

Command line:
php hello.php

Output:
hello world!

See the documentation: http://php.net/manual/en/features.commandline.php


EDIT OP edited the question to add a critical detail: the script is to be executed by another script.

There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include (docs) and/or require (docs) (note: include_once and require_once are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:

 include('hello.php');
 /* output
 hello world!
 */

Second and slightly more complex is to use shell_exec (docs). With shell_exec, you will call the php binary and pass the desired script as the argument. Your code would look like this:

$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/

Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)

$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/

Documentation for functions used

Text size and different android screen sizes

@forcelain I think you need to check this Google IO Pdf for Design. In that pdf go to Page No:77 in which you will find how there suggesting for using dimens.xml for different devices of android for Example see Below structure :

res/values/dimens.xml

res/values-small/dimens.xml

res/values-normal/dimens.xml

res/values-large/dimens.xml

res/values-xlarge/dimens.xml

for Example you have used below dimens.xml in values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <dimen name="text_size">18sp</dimen>
</resources>

In other values folder you need to change values for your text size .

Note: As indicated by @espinchi the small, normal, large and xlarge have been deprecated since Android 3.2 in favor of the following:

Declaring Tablet Layouts for Android 3.2

For the first generation of tablets running Android 3.0, the proper way to declare tablet layouts was to put them in a directory with the xlarge configuration qualifier (for example, res/layout-xlarge/). In order to accommodate other types of tablets and screen sizes—in particular, 7" tablets—Android 3.2 introduces a new way to specify resources for more discrete screen sizes. The new technique is based on the amount of space your layout needs (such as 600dp of width), rather than trying to make your layout fit the generalized size groups (such as large or xlarge).

The reason designing for 7" tablets is tricky when using the generalized size groups is that a 7" tablet is technically in the same group as a 5" handset (the large group). While these two devices are seemingly close to each other in size, the amount of space for an application's UI is significantly different, as is the style of user interaction. Thus, a 7" and 5" screen should not always use the same layout. To make it possible for you to provide different layouts for these two kinds of screens, Android now allows you to specify your layout resources based on the width and/or height that's actually available for your application's layout, specified in dp units.

For example, after you've designed the layout you want to use for tablet-style devices, you might determine that the layout stops working well when the screen is less than 600dp wide. This threshold thus becomes the minimum size that you require for your tablet layout. As such, you can now specify that these layout resources should be used only when there is at least 600dp of width available for your application's UI.

You should either pick a width and design to it as your minimum size, or test what is the smallest width your layout supports once it's complete.

Note: Remember that all the figures used with these new size APIs are density-independent pixel (dp) values and your layout dimensions should also always be defined using dp units, because what you care about is the amount of screen space available after the system accounts for screen density (as opposed to using raw pixel resolution). For more information about density-independent pixels, read Terms and concepts, earlier in this document. Using new size qualifiers

The different resource configurations that you can specify based on the space available for your layout are summarized in table 2. These new qualifiers offer you more control over the specific screen sizes your application supports, compared to the traditional screen size groups (small, normal, large, and xlarge).

Note: The sizes that you specify using these qualifiers are not the actual screen sizes. Rather, the sizes are for the width or height in dp units that are available to your activity's window. The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout. Thus, the sizes you declare should be specifically about the sizes needed by your activity—the system accounts for any space used by system UI when declaring how much space it provides for your layout. Also beware that the Action Bar is considered a part of your application's window space, although your layout does not declare it, so it reduces the space available for your layout and you must account for it in your design.

Table 2. New configuration qualifiers for screen size (introduced in Android 3.2). Screen configuration Qualifier values Description smallestWidth swdp

Examples: sw600dp sw720dp

The fundamental size of a screen, as indicated by the shortest dimension of the available screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your application's has at least dps of width available for its UI.

For example, if your layout requires that its smallest dimension of screen area be at least 600 dp at all times, then you can use this qualifier to create the layout resources, res/layout-sw600dp/. The system will use these resources only when the smallest dimension of available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived height or width. The smallestWidth is a fixed screen size characteristic of the device; the device's smallestWidth does not change when the screen's orientation changes.

The smallestWidth of a device takes into account screen decorations and system UI. For example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI.

This is an alternative to the generalized screen size qualifiers (small, normal, large, xlarge) that allows you to define a discrete number for the effective size available for your UI. Using smallestWidth to determine the general screen size is useful because width is often the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally. The available width is also the key factor in determining whether to use a one-pane layout for handsets or multi-pane layout for tablets. Thus, you likely care most about what the smallest possible width will be on each device. Available screen width wdp

Examples: w720dp w1024dp

Specifies a minimum available width in dp units at which the resources should be used—defined by the value. The system's corresponding value for the width changes when the screen's orientation switches between landscape and portrait to reflect the current actual width that's available for your UI.

This is often useful to determine whether to use a multi-pane layout, because even on a tablet device, you often won't want the same multi-pane layout for portrait orientation as you do for landscape. Thus, you can use this to specify the minimum width required for the layout, instead of using both the screen size and orientation qualifiers together. Available screen height hdp

Examples: h720dp h1024dp etc.

Specifies a minimum screen height in dp units at which the resources should be used—defined by the value. The system's corresponding value for the height changes when the screen's orientation switches between landscape and portrait to reflect the current actual height that's available for your UI.

Using this to define the height required by your layout is useful in the same way as wdp is for defining the required width, instead of using both the screen size and orientation qualifiers. However, most apps won't need this qualifier, considering that UIs often scroll vertically and are thus more flexible with how much height is available, whereas the width is more rigid.

While using these qualifiers might seem more complicated than using screen size groups, it should actually be simpler once you determine the requirements for your UI. When you design your UI, the main thing you probably care about is the actual size at which your application switches between a handset-style UI and a tablet-style UI that uses multiple panes. The exact point of this switch will depend on your particular design—maybe you need a 720dp width for your tablet layout, maybe 600dp is enough, or 480dp, or some number between these. Using these qualifiers in table 2, you are in control of the precise size at which your layout changes.

For more discussion about these size configuration qualifiers, see the Providing Resources document. Configuration examples

To help you target some of your designs for different types of devices, here are some numbers for typical screen widths:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Using the size qualifiers from table 2, your application can switch between your different layout resources for handsets and tablets using any number you want for width and/or height. For example, if 600dp is the smallest available width supported by your tablet layout, you can provide these two sets of layouts:

res/layout/main_activity.xml # For handsets res/layout-sw600dp/main_activity.xml # For tablets

In this case, the smallest width of the available screen space must be 600dp in order for the tablet layout to be applied.

For other cases in which you want to further customize your UI to differentiate between sizes such as 7” and 10” tablets, you can define additional smallest width layouts:

res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) res/layout-sw720dp/main_activity.xml

For 10” tablets (720dp wide and bigger)

Notice that the previous two sets of example resources use the "smallest width" qualifier, swdp, which specifies the smallest of the screen's two sides, regardless of the device's current orientation. Thus, using swdp is a simple way to specify the overall screen size available for your layout by ignoring the screen's orientation.

However, in some cases, what might be important for your layout is exactly how much width or height is currently available. For example, if you have a two-pane layout with two fragments side by side, you might want to use it whenever the screen provides at least 600dp of width, whether the device is in landscape or portrait orientation. In this case, your resources might look like this:

res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width or more)

Notice that the second set is using the "available width" qualifier, wdp. This way, one device may actually use both layouts, depending on the orientation of the screen (if the available width is at least 600dp in one orientation and less than 600dp in the other orientation).

If the available height is a concern for you, then you can do the same using the hdp qualifier. Or, even combine the wdp and hdp qualifiers if you need to be really specific.

How do I count occurrence of duplicate items in array

If you have a multi-dimensional array you can use on PHP 5.5+ this:

array_count_values(array_column($array, 'key'))

which returns e.g.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

How to remove non-alphanumeric characters?

here's a really simple regex for that:

\W|_

and used as you need it (with a forward / slash delimiter).

preg_replace("/\W|_/", '', $string);

Test it here with this great tool that explains what the regex is doing:

http://www.regexr.com/

Java Runtime.getRuntime(): getting output from executing a command line program

Try reading the InputStream of the runtime:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
    new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
    System.out.println(line);

You might also need to read the error stream (proc.getErrorStream()) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder.

Pandas: sum DataFrame rows for given columns

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can't find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

SQL-Server: The backup set holds a backup of a database other than the existing

USE [master];
GO

CREATE DATABASE db;
GO

CREATE DATABASE db2;
GO

BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO

RESTORE DATABASE db2
  FROM DISK = 'c:\temp\db.bak'
  WITH REPLACE,
  MOVE 'db' TO 'c:\temp\db2.mdf',
  MOVE 'db_log' TO 'c:\temp\db2.ldf';

C++ delete vector, objects, free memory

If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Prevent BODY from scrolling when a modal is opened

I found a working solution after doing some 8-10 hours research on StackOverflow itself.

The breakthrough

$('.modal').is(':visible');

So I have built a function to check if any modal is open which will periodically add class *modal-open** to the

 setInterval(function()
     {
         if($('.modal').is(':visible')===true)
         {
             $("body").addClass("modal-open");
         }
         else
         {
             $("body").removeClass("modal-open");
         }

     },200);

The reason to use $(".modal") here is because all modals (in Bootstrap) use class modal (fade/show is as per the state)

So my modals are now running perfectly without the body getting scrolled.

This is a bug/unheard issue in GitHub as well but nobody's bothered.

how to change the default positioning of modal in bootstrap?

Add the following css to your html and try changing the top, right, bottom, left values.

.modal {
   position: absolute;
   top: 10px;
   right: 100px;
   bottom: 0;
   left: 0;
   z-index: 10040;
   overflow: auto;
   overflow-y: auto;
}

How do you connect to multiple MySQL databases on a single webpage?

Try below code:

    $conn = mysql_connect("hostname","username","password");
    mysql_select_db("db1",$conn);
    mysql_select_db("db2",$conn);

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;
}

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;
}

print_r($data1);
print_r($data2);

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

Visual Studio 2012 Web Publish doesn't copy files

FIXED - various solutions offered didn't work for me. What did work for me with VS Community 2017, Windows Server 2012 R2 was to change the TEMP and TMP environmental variables for the user and then restart the system and deploy again (restarting VS was not enough). These temp variables are where VS does the temp publish.

enter image description here

enter image description here

enter image description here

Restarting visual studio after changing temp variables didn't do the trick, had to reboot system.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

np.isnan can be applied to NumPy arrays of native dtype (such as np.float64):

In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)

but raises TypeError when applied to object arrays:

In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Since you have Pandas, you could use pd.isnull instead -- it can accept NumPy arrays of object or native dtypes:

In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)

In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)

Note that None is also considered a null value in object arrays.

Connect to Amazon EC2 file directory using Filezilla and SFTP

I've created a video tutorial for this. Just check:

Connect to Amazon EC2 file directory using FileZilla and SFTP, Video Tutorial

Summary of above video tutorial:

  1. Edit (Preferences) > Settings > Connection > SFTP, Click "Add key file”
  2. Browse to the location of your .pem file and select it.
  3. A message box will appear asking your permission to convert the file into ppk format. Click Yes, then give the file a name and store it somewhere.
  4. If the new file is shown in the list of Keyfiles, then continue to the next step. If not, then click "Add keyfile..." and select the converted file.
  5. File > Site Manager Add a new site with the following parameters:

    Host: Your public DNS name of your EC2 instance, or the public IP address of the server.

    Protocol: SFTP

    Logon Type: Normal

    User: From the docs: "For Amazon Linux, the default user name is ec2-user. For RHEL5, the user name is often root but might be ec2-user. For Ubuntu, the user name is ubuntu. For SUSE Linux, the user name is root. For Debian, the user name is admin. Otherwise, check with your AMI provider."

    Press Connect Button - If saving of passwords has been disabled, you will be prompted that the logon type will be changed to 'Ask for password'. Say 'OK' and when connecting, at the password prompt push 'OK' without entering a password to proceed past the dialog.

    Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

If you use Cyberduck follow this.

Check this post if you have any permission issues.

Converting a Java Keystore into PEM Format

Converting a Java Keystore into PEM Format

The most precise answer of all must be that this is NOT possible.

A Java keystore is merely a storage facility for cryptographic keys and certificates while PEM is a file format for X.509 certificates only.

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

Python Remove last char from string and return it

Yes, python strings are immutable and any modification will result in creating a new string. This is how it's mostly done.

So, go ahead with it.

How can I find the OWNER of an object in Oracle?

To find the name of the current user within an Oracle session, use the USER function.

Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:

select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
  and Constraint_Type = 'R' and Owner = User;

AngularJS ng-class if-else expression

you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
     else
         return "ClassC";
    }

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/

How to lose margin/padding in UITextView?

I have found one more approach, getting view with text from UITextView's subviews and setting it up in layoutSubview method of a subclass:

- (void)layoutSubviews {
    [super layoutSubviews];

    const int textViewIndex = 1;
    UIView *textView = [self.subviews objectAtIndex:textViewIndex];
    textView.frame = CGRectMake(
                                 kStatusViewContentOffset,
                                 0.0f,
                                 self.bounds.size.width - (2.0f * kStatusViewContentOffset),
                                 self.bounds.size.height - kStatusViewContentOffset);
}

Turn a number into star rating display using jQuery and CSS

Here's my take using JSX and font awesome, limited on only .5 accuracy, though:

       <span>
          {Array(Math.floor(rating)).fill(<i className="fa fa-star"></i>)}
          {(rating) - Math.floor(rating)==0 ? ('') : (<i className="fa fa-star-half"></i>)}
       </span>

First row is for whole star and second row is for half star (if any)

Node.js Error: connect ECONNREFUSED

Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:

process.on('uncaughtException', function (err) {
    console.log(err);
}); 

This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

Changing website favicon dynamically

Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different demo of code that works in IE11 too. The following example might not work in Safari or Internet Explorer.

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'dynamic-favicon';
 link.rel = 'shortcut icon';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}

You would then use it as follows:

var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
 changeFavicon('http://www.google.com/favicon.ico');
};

Fork away or view a demo.

How can I INSERT data into two tables simultaneously in SQL Server?

BEGIN TRANSACTION;

DECLARE @tblMapping table(sourceid int, destid int)

INSERT INTO [table1] ([data]) 
OUTPUT source.id, new.id
Select [data] from [external_table] source;

INSERT INTO [table2] ([table1_id], [data])
Select map.destid, source.[more data] 
from [external_table] source
    inner join @tblMapping map on source.id=map.sourceid;

COMMIT TRANSACTION;

How do I skip a header from CSV files in Spark?

Alternatively, you can use the spark-csv package (or in Spark 2.0 this is more or less available natively as CSV). Note that this expects the header on each file (as you desire):

schema = StructType([
        StructField('lat',DoubleType(),True),
        StructField('lng',DoubleType(),True)])

df = sqlContext.read.format('com.databricks.spark.csv'). \
     options(header='true',
             delimiter="\t",
             treatEmptyValuesAsNulls=True,
             mode="DROPMALFORMED").load(input_file,schema=schema)

Check if number is prime number

var number;

Console.WriteLine("Accept number:");
number = Convert.ToInt32(Console.ReadLine());

if (IsPrime(number))
{
    Console.WriteLine("It is prime");
}
else
{
    Console.WriteLine("It is not prime");
}       

public static bool IsPrime(int number)
{
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;

    var boundary = (int)Math.Floor(Math.Sqrt(number));
          
    for (int i = 3; i <= boundary; i += 2)
        if (number % i == 0)
            return false;
    
    return true;        
}

I changed number / 2 to Math.Sqrt(number) because from in wikipedia, they said:

This routine consists of dividing n by each integer m that is greater than 1 and less than or equal to the square root of n. If the result of any of these divisions is an integer, then n is not a prime, otherwise it is a prime. Indeed, if n = a*b is composite (with a and b ?

  1. then one of the factors a or b is necessarily at most square root of n

"Sub or Function not defined" when trying to run a VBA script in Outlook

I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

Xcode 8 shows error that provisioning profile doesn't include signing certificate

Because I haven't seen this specific answer:

My issue was I needed manual signing. So my mistake was that In Build Settings -> Code Signing -> Code Signing Identity

I had my debug (Automatic signing style, and Apple Development Certificate), Staging and Release (Manual and Apple Distribution (adHoc) variants set correctly.

What I DIDNT have set correctly (due to some flawed logic in my understanding) was the "ANY IOS SDK" value. Once I set it to the same manual Apple Distribution cert, the error went away.

Initially i had it set to an Automatic value "iOS Distribution" because I figured it would better handled automatically since I didnt know what it meant. still dont. oh well hope it helps

How to install bcmath module?

This worked for me install php72-php-bcmath.x86_64 Then,

systemctl restart php72-php-fpm.service

What exactly is RESTful programming?

I would say that an important building block in understanding REST lies in the endpoints or mappings, such as /customers/{id}/balance.

You can imagine such an endpoint as being the connecting pipeline from the website (front-end) to your database/server (back-end). Using them, the front-end can perform back-end operations which are defined in the corresponding methods of any REST mapping in your application.

Setting log level of message at runtime in slf4j

It is not possible with slf4j API to dynamically change log level but you can configure logback (if you use this) by your own. In that case create factory class for your logger and implement root logger with configuration that you need.

LoggerContext loggerContext = new LoggerContext();
ch.qos.logback.classic.Logger root = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

// Configure appender
final TTLLLayout layout = new TTLLLayout();
layout.start(); // default layout of logging messages (the form that message displays 
// e.g. 10:26:49.113 [main] INFO com.yourpackage.YourClazz - log message

final LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<>();
encoder.setCharset(StandardCharsets.UTF_8);
encoder.setLayout(layout);

final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
appender.setContext(loggerContext);
appender.setEncoder(encoder);
appender.setName("console");
appender.start();

root.addAppender(appender);

After you configure root logger (only once is enough) you can delegate getting new logger by

final ch.qos.logback.classic.Logger logger = loggerContext.getLogger(clazz);

Remember to use the same loggerContext.

Changing log level is easy to do with root logger given from loggerContext.

root.setLevel(Level.DEBUG);

How can I load storyboard programmatically from class?

The extension below will allow you to load a Storyboard and it's associated UIViewController. Example: If you have a UIViewController named ModalAlertViewController and a storyboard named "ModalAlert" e.g.

let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")

Will load both the Storyboard and UIViewController and vc will be of type ModalAlertViewController. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.

extension UIViewController {
    /// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
    /// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
    static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
            vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
            return vc
        }
        return nil
    }
}

What is the difference between "expose" and "publish" in Docker?

Short answer:

  • EXPOSE is a way of documenting
  • --publish (or -p) is a way of mapping a host port to a running container port

Notice below that:

  • EXPOSE is related to Dockerfiles ( documenting )
  • --publish is related to docker run ... ( execution / run-time )

Exposing and publishing ports

In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.

  • You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

  • You publish ports using the --publish or --publish-all flag to docker run. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than 30000) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.

from: Docker container networking

Update October 2019: the above piece of text is no longer in the docs but an archived version is here: docs.docker.com/v17.09/engine/userguide/networking/#exposing-and-publishing-ports

Maybe the current documentation is the below:

Published ports

By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host.

and can be found here: docs.docker.com/config/containers/container-networking/#published-ports

Also,

EXPOSE

...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.

from: Dockerfile reference






Service access when EXPOSE / --publish are not defined:

At @Golo Roden's answer it is stated that::

"If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."

Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE or --publish, the host and other containers of the same network will be able to access a service you may start inside that container.

How to test this:

I've used the following Dockerfile. Basically, I start with ubuntu and install a tiny web-server:

FROM ubuntu
RUN apt-get update && apt-get install -y mini-httpd

I build the image as "testexpose" and run a new container with:

docker run --rm -it testexpose bash

Inside the container, I launch a few instances of mini-httpd:

root@fb8f7dd1322d:/# mini_httpd -p 80
root@fb8f7dd1322d:/# mini_httpd -p 8080
root@fb8f7dd1322d:/# mini_httpd -p 8090

I am then able to use curl from the host or other containers to fetch the home page of mini-httpd.


Further reading

Very detailed articles on the subject by Ivan Pepelnjak:

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

$(form).ajaxSubmit is not a function

Try:

$(document).ready(function() {
    $('#contact-form').validate({submitHandler: function(form) {
         var data = $('#contact-form').serialize();   
         $.post(
              'url_request',
               {data: data},
               function(response){
                  console.log(response);
               }
          );
         }
    });
});

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Sub CopyValueWithFormatting()
    Sheet1.Range("A1").Copy
    With Sheet2.Range("B1")
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteValues
    End With
End Sub

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

Converting from IEnumerable to List

I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.

Here is a very contrived example:

IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));

Here is the extension method:

public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
    return obj == null ? new List<T>() : obj.ToList();
}

How do I check if file exists in Makefile so I can delete it?

Missing a semicolon

if [ -a myApp ];
then
  rm myApp
fi

However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use rm -f myApp which "forces" delete, i.e. doesn't error out if the file didn't exist.

Calculating percentile of dataset column

You can also use the hmisc package that will give you the following percentiles:

0.05, 0.1, 0.25, 0.5, 0.75, 0.9 , 0.95

Just use the describe(table_ages)

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

Is JavaScript a pass-by-reference or pass-by-value language?

JavaScript is always pass-by-value; everything is of value type.

Objects are values, and member functions of objects are values themselves (remember that functions are first-class objects in JavaScript). Also, regarding the concept that everything in JavaScript is an object; this is wrong. Strings, symbols, numbers, booleans, nulls, and undefineds are primitives.

On occasion they can leverage some member functions and properties inherited from their base prototypes, but this is only for convenience. It does not mean that they are objects themselves. Try the following for reference:

x = "test";
alert(x.foo);
x.foo = 12;
alert(x.foo);

In both alerts you will find the value to be undefined.

What is the difference between Sessions and Cookies in PHP?

A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)

Flutter.io Android License Status Unknown

For those of you who are on Linux and keep getting errors during flutter doctor --android-licenses.

I kept getting the could not create settings warning when trying to accept licenses, which I fixed by specifying SDK location:

sdkmanager --sdk_root=/home/adel/bin/android-sdk --licenses

Sdkmanager then printed: all SDK package licenses accepted.

However Flutter kept giving the android license status unknown error. And attempting to call flutter doctor --android-licenses would give me the same could not create settings error I used to get.

To fix this I edited the sdkmanager script located in ${your android tools location}/tools/bin/ and changed the last line from:

exec "$JAVACMD" "$@"

To:

exec "$JAVACMD" "$@" --sdk_root=/home/adel/bin/android-sdk

This would make Flutter call sdkmanager while passing the needed sdk_root argument, a final call to flutter doctor --android-licenses fixed the issue.

I did not have to use Java 8.

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

Django needs your application-specific settings. Since it is already inside your manage.py, just use that. The faster, but perhaps temporary, solution is:

python manage.py shell

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

Way to ng-repeat defined number of times instead of repeating over array?

$scope.number = 5;

<div ng-repeat="n in [] | range:$scope.number">
      <span>{{$index}}</span>
</div>

How to open CSV file in R when R says "no such file or directory"?

  1. Save as in excel will keep the file open and lock it so you can't open it. Close the excel file or you won't be able to use it in R.
  2. Give the full path and escape backslashes read.csv("c:\\users\\JoeUser\\Desktop\\JoesData.csv")

Echo off but messages are displayed

@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
   //
   echo 222;
)

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Either remove the below code from the pom.xml or correct your java version to make it work.

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

For SQL Server 2012 and up , with leading zeroes:

 SELECT FORMAT(GETDATE(),'MM') 

without:

SELECT    MONTH(GETDATE())

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

How to unzip files programmatically in Android?

Had peno's version optimised a bit. The increase in performance is perceptible.

private boolean unpackZip(String path, String zipname)
{       
     InputStream is;
     ZipInputStream zis;
     try 
     {
         String filename;
         is = new FileInputStream(path + zipname);
         zis = new ZipInputStream(new BufferedInputStream(is));          
         ZipEntry ze;
         byte[] buffer = new byte[1024];
         int count;

         while ((ze = zis.getNextEntry()) != null) 
         {
             filename = ze.getName();

             // Need to create directories if not exists, or
             // it will generate an Exception...
             if (ze.isDirectory()) {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
             }

             FileOutputStream fout = new FileOutputStream(path + filename);

             while ((count = zis.read(buffer)) != -1) 
             {
                 fout.write(buffer, 0, count);             
             }

             fout.close();               
             zis.closeEntry();
         }

         zis.close();
     } 
     catch(IOException e)
     {
         e.printStackTrace();
         return false;
     }

    return true;
}

Uploading Laravel Project onto Web Server

If you are trying to host your Laravel app on a shared hosting, this may help you.

Hosting Laravel on shared hosting #1

Hosting Laravel on shared hosting #2

If you want PHP 5.4 add this line to your .htaccess file or call your hosting provider.

AddType application/x-httpd-php54 .php

Pass a data.frame column name to a function

Personally I think that passing the column as a string is pretty ugly. I like to do something like:

get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:

> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:

> get.max(1/mpg,mtcars)
[1] 0.09615385

Change Input to Upper Case

Javascript string objects have a toLocaleUpperCase() function that makes the conversion itself easy.

Here's an example of live capitalisation:

$(function() {
    $('input').keyup(function() {
        this.value = this.value.toLocaleUpperCase();
    });
});

Unfortunately, this resets the textbox contents completely, so the user's caret position (if not "the end of the textbox") is lost.

You can hack this back in, though, with some browser-switching magic:

// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition(ctrl) {
    var CaretPos = 0;    // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        CaretPos = ctrl.selectionStart;
    }

    return CaretPos;
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


// The real work

$(function() {
    $('input').keyup(function() {
        // Remember original caret position
        var caretPosition = getCaretPosition(this);

        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();

        // Reset caret position
        // (we ignore selection length, as typing deselects anyway)
        setCaretPosition(this, caretPosition);
    });
});

Ultimately, it might be easiest to fake it. Set the style text-transform: uppercase on the textbox so that it appears uppercase to the user, then in your Javascript apply the text transformation once whenever the user's caret focus leaves the textbox entirely:

HTML:

<input type="text" name="keywords" class="uppercase" />

CSS:

input.uppercase { text-transform: uppercase; }

Javascript:

$(function() {
    $('input').focusout(function() {
        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();
    });
});

Hope this helps.

to call onChange event after pressing Enter key

You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().

<input
    type="text"
    placeholder="Search..."
    onChange={event => {this.setState({query: event.target.value})}}
    onKeyPress={event => {
                if (event.key === 'Enter') {
                  this.search()
                }
              }}
/>