Programs & Examples On #Ddlutils

DdlUtils is an apache utility which generates database schemas (tables, fields) for multiple databases using a common XML format.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

As Sven mentioned, x[[[0],[2]],[1,3]] will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]] will return the values x[0,1] and x[2,3] in an array.

There is a helpful function for doing the first example I gave, numpy.ix_. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]. This can save you from having to enter in all of those extra brackets.

Windows-1252 to UTF-8 encoding

Use the iconv command.

To make sure the file is in Windows-1252, open it in Notepad (under Windows), then click Save As. Notepad suggests current encoding as the default; if it's Windows-1252 (or any 1-byte codepage, for that matter), it would say "ANSI".

Iterating through struct fieldnames in MATLAB

Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.

fns{i}
teststruct.(fns{i})

Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.

name_as_char = 'a'
name_as_cellstr = {'a'}

S3 limit to objects in a bucket

While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.

Update Multiple Rows in Entity Framework from a list of ids

something like below

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

UPDATE:

you can update multiple fields as below

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });

Java Array Sort descending?

For discussions above, here is an easy example to sort the primitive arrays in descending order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

Output:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0

What port is used by Java RMI connection?

The port is available here: java.rmi.registry.Registry.REGISTRY_PORT (1099)

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Convert datatable to JSON in C#

To access the convert datatable value in Json method follow the below steps:

$.ajax({
        type: "POST",
        url: "/Services.asmx/YourMethodName",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var parsed = $.parseJSON(data.d);
            $.each(parsed, function (i, jsondata) {
            $("#dividtodisplay").append("Title: " + jsondata.title + "<br/>" + "Latitude: " + jsondata.lat);
            });
        },
        error: function (XHR, errStatus, errorThrown) {
            var err = JSON.parse(XHR.responseText);
            errorMessage = err.Message;
            alert(errorMessage);
        }
    });

How to run python script in webpage

Well, OP didn't say server or client side, so i will just leave this here in case someone like me is looking for client side:

http://skulpt.org/using.html

Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just a simple JS.

Format JavaScript date as yyyy-mm-dd

We run constantly into problems like this. Every solution looks so individual. But looking at php, we have a way dealing with different formats. And there is a port of php's strtotime function at https://locutus.io/php/datetime/strtotime/. A small open source npm package from me as an alternative way:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

See datebob.js

How to use the addr2line command in Linux?

That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.

For example:

$ cat t.c
#include <stdio.h>
int main()
{
    printf("hello\n");
    return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0

0x400534 is the address of main in my case. 0x400408 is also a valid function address in a.out, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init. You can see the layout of your executable with readelf -a your_exe.)

Other times when addr2line will fail is if you're including a library that has no debug information.

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Location of the mongodb database on mac

The default data directory for MongoDB is /data/db.

This can be overridden by a dbpath option specified on the command line or in a configuration file.

If you install MongoDB via a package manager such as Homebrew or MacPorts these installs typically create a default data directory other than /data/db and set the dbpath in a configuration file.

If a dbpath was provided to mongod on startup you can check the value in the mongo shell:

db.serverCmdLineOpts()

You would see a value like:

"parsed" : {
    "dbpath" : "/usr/local/data"
},

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

How to create CSV Excel file C#?

Please forgive me

But I think a public open-source repository is a better way to share code and make contributions, and corrections, and additions like "I fixed this, I fixed that"

So I made a simple git-repository out of the topic-starter's code and all the additions:

https://github.com/jitbit/CsvExport

I also added a couple of useful fixes myself. Everyone could add suggestions, fork it to contribute etc. etc. etc. Send me your forks so I merge them back into the repo.

PS. I posted all copyright notices for Chris. @Chris if you're against this idea - let me know, I'll kill it.

How to center images on a web page for all screen sizes

Try something like this...

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>

Swift: Reload a View Controller

Swift 5.2

The only method I found to work and refresh a view dynamically where the visibility of buttons had changed was:-

viewWillAppear(true)

This may be a bad practice but hopefully somebody will leave a comment.

Get last record of a table in Postgres

If under "last record" you mean the record which has the latest timestamp value, then try this:

my_query = client.query("
  SELECT TIMESTAMP,
    value,
    card
  FROM my_table
  ORDER BY TIMESTAMP DESC
  LIMIT 1
");

How do I use CMake?

Yes, cmake and make are different programs. cmake is (on Linux) a Makefile generator (and Makefile-s are the files driving the make utility). There are other Makefile generators (in particular configure and autoconf etc...). And you can find other build automation programs (e.g. ninja).

HTML Code for text checkbox '?'

This is the code for the character you posted in your question: &#xf0fe;

But that's not a checkbox character...

Simplest way to read json from a URL in java

I am not sure if this is efficient, but this is one of the possible ways:

Read json from url use url.openStream() and read contents into a string.

construct a JSON object with this string (more at json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

Where is the list of predefined Maven properties

This link shows how to list all the active properties: http://skillshared.blogspot.co.uk/2012/11/how-to-list-down-all-maven-available.html

In summary, add the following plugin definition to your POM, then run mvn install:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <phase>install</phase>
            <configuration>
                <target>
                    <echoproperties />
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>

What is the best way to implement constants in Java?

Based on the comments above I think this is a good approach to change the old-fashioned global constant class (having public static final variables) to its enum-like equivalent in a way like this:

public class Constants {

    private Constants() {
        throw new AssertionError();
    }

    public interface ConstantType {}

    public enum StringConstant implements ConstantType {
        DB_HOST("localhost");
        // other String constants come here

        private String value;
        private StringConstant(String value) {
            this.value = value;
        }
        public String value() {
            return value;
        }
    }

    public enum IntConstant implements ConstantType {
        DB_PORT(3128), 
        MAX_PAGE_SIZE(100);
        // other int constants come here

        private int value;
        private IntConstant(int value) {
            this.value = value;
        }
        public int value() {
            return value;
        }
    }

    public enum SimpleConstant implements ConstantType {
        STATE_INIT,
        STATE_START,
        STATE_END;
    }

}

So then I can refer them to like:

Constants.StringConstant.DB_HOST

I keep getting "Uncaught SyntaxError: Unexpected token o"

Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:

[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]

Correct modification of state arrays in React.js

This worked for me to add an array within an array

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

macOS on VMware doesn't recognize iOS device

I have 2 computers with VMWare Workstation and Mac OS Sierra installed as the guest OS. First machine could recognize my iOS device whereas my second machine could not recognize it. The second machine was exhibiting the same behavior as others reported where it would reconnect and disconnect with the iPhone endlessly.

Thankfully, my second machine had network connectivity problems with my VM. So I stumbled upon the solution when I reset my network settings for the VM.

You can try the following steps and see if it works for you. It worked for me.

  1. Go to Start Menu.
  2. Open VMWare folder.
  3. Start VMWare Network Editor.
  4. Click Change Settings button to assign Administrator privileges.
  5. Click Restore Defaults button.
  6. Open Virtual Machine.
  7. Verify internet connectivity on Mac OS.
  8. Connect iOS device. If iTunes launches on Mac, this means that the Mac has correctly identified your iOS device.

Convert a byte array to integer in Java and vice versa

Someone with a requirement where they have to read from bits, lets say you have to read from only 3 bits but you need signed integer then use following:

data is of type: java.util.BitSet

new BigInteger(data.toByteArray).intValue() << 32 - 3 >> 32 - 3

The magic number 3 can be replaced with the number of bits (not bytes) you are using.

What in the world are Spring beans?

Spring beans are classes. Instead of instantiating a class (using new), you get an instance as a bean cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.

Git: How to find a deleted file in the project commit history?

If you do not know the exact path you may use

git log --all --full-history -- "**/thefile.*"

If you know the path the file was at, you can do this:

git log --all --full-history -- <path-to-file>

This should show a list of commits in all branches which touched that file. Then, you can find the version of the file you want, and display it with...

git show <SHA> -- <path-to-file>

Or restore it into your working copy with:

git checkout <SHA>^ -- <path-to-file>

Note the caret symbol (^), which gets the checkout prior to the one identified, because at the moment of <SHA> commit the file is deleted, we need to look at the previous commit to get the deleted file's contents

What is the difference between g++ and gcc?

GCC: GNU Compiler Collection

  • Referrers to all the different languages that are supported by the GNU compiler.

gcc: GNU C      Compiler
g++: GNU C++ Compiler

The main differences:

  1. gcc will compile: *.c\*.cpp files as C and C++ respectively.
  2. g++ will compile: *.c\*.cpp files but they will all be treated as C++ files.
  3. Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this).
  4. gcc compiling C files has fewer predefined macros.
  5. gcc compiling *.cpp and g++ compiling *.c\*.cpp files has a few extra macros.

Extra Macros when compiling *.cpp files:

#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern

Quantile-Quantile Plot using SciPy

Using qqplot of statsmodels.api is another option:

Very basic example:

import numpy as np
import statsmodels.api as sm
import pylab

test = np.random.normal(0,1, 1000)

sm.qqplot(test, line='45')
pylab.show()

Result:

enter image description here

Documentation and more example are here

Where is body in a nodejs http.get response?

http.request docs contains example how to receive body of the response through handling data event:

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

http.get does the same thing as http.request except it calls req.end() automatically.

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Math.random() versus Random.nextInt(int)

Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() * n" from the Sun forums post that Gili linked to:

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

C++/CLI Converting from System::String^ to std::string

Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.

For example:

#include <msclr\marshal_cppstd.h>

System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

Why am I seeing "TypeError: string indices must be integers"?

I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
    print('{} {}'.format(item["gravatar_id"], item["position"]))

note that you need to handle the index in the dataset that is also returned by the function.

Why do I get "MismatchSenderId" from GCM server side?

This happens when the Server key and Sender ID parameters HTTP request do not match each other. Basically both server ID and Server key must belong to the same firebase project. Please refer to the below image. In case of mixing these parameters from deferent Firebase projects will cause error MismatchSenderId enter image description here

What is the proper way to test if a parameter is empty in a batch file?

Empty string is a pair of double-quotes/"", we can just test the length:

set ARG=%1
if not defined ARG goto nomore

set CHAR=%ARG:~2,1%
if defined CHAR goto goon

then test it's 2 characters against double-quotes:

if ^%ARG:~1,1% == ^" if ^%ARG:~0,1% == ^" goto blank
::else
goto goon

Here's a batch script you can play with. I think it properly catches the empty string.

This is just an example, you just need to customize 2 (or 3?) steps above according to your script.

@echo off
if not "%OS%"=="Windows_NT" goto EOF
:: I guess we need enableExtensions, CMIIW
setLocal enableExtensions
set i=0
set script=%0

:LOOP
set /a i=%i%+1

set A1=%1
if not defined A1 goto nomore

:: Assumption:
:: Empty string is (exactly) a pair of double-quotes ("")

:: Step out if str length is more than 2
set C3=%A1:~2,1%
if defined C3 goto goon

:: Check the first and second char for double-quotes
:: Any characters will do fine since we test it *literally*
if ^%A1:~1,1% == ^" if ^%A1:~0,1% == ^" goto blank
goto goon

:goon
echo.args[%i%]: [%1]
shift
goto LOOP

:blank
echo.args[%i%]: [%1] is empty string
shift
goto LOOP

:nomore
echo.
echo.command line:
echo.%script% %*

:EOF

This torture test result:

.test.bat :: ""  ">"""bl" " "< "">"  (")(") "" :: ""-"  " "( )"">\>" ""
args[1]: [::]
args[2]: [""] is empty string
args[3]: [">"""bl" "]
args[4]: ["< "">"]
args[5]: [(")(")]
args[6]: [""] is empty string
args[7]: [::]
args[8]: [""-"  "]
args[9]: ["( )"">\>"]
args[10]: [""] is empty string

command line:
.test.bat :: ""  ">"""bl" " "< "">"  (")(") "" :: ""-"  " "( )"">\>" ""

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

proper hibernate annotation for byte[]

What is the portable way to annotate a byte[] property?

It depends on what you want. JPA can persist a non annotated byte[]. From the JPA 2.0 spec:

11.1.6 Basic Annotation

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive, types, wrappers of the primitive types, java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable. As described in Section 2.8, the use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

And Hibernate will map a it "by default" to a SQL VARBINARY (or a SQL LONGVARBINARY depending on the Column size?) that PostgreSQL handles with a bytea.

But if you want the byte[] to be stored in a Large Object, you should use a @Lob. From the spec:

11.1.24 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation or with the ElementCollection annotation when the element collection value is of basic type. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property and, except for string and character types, defaults to Blob.

And Hibernate will map it to a SQL BLOB that PostgreSQL handles with a oid .

Is this fixed in some recent version of hibernate?

Well, the problem is that I don't know what the problem is exactly. But I can at least say that nothing has changed since 3.5.0-Beta-2 (which is where a changed has been introduced)in the 3.5.x branch.

But my understanding of issues like HHH-4876, HHH-4617 and of PostgreSQL and BLOBs (mentioned in the javadoc of the PostgreSQLDialect) is that you are supposed to set the following property

hibernate.jdbc.use_streams_for_binary=false

if you want to use oid i.e. byte[] with @Lob (which is my understanding since VARBINARY is not what you want with Oracle). Did you try this?

As an alternative, HHH-4876 suggests using the deprecated PrimitiveByteArrayBlobType to get the old behavior (pre Hibernate 3.5).

References

  • JPA 2.0 Specification
    • Section 2.8 "Mapping Defaults for Non-Relationship Fields or Properties"
    • Section 11.1.6 "Basic Annotation"
    • Section 11.1.24 "Lob Annotation"

Resources

How to remove unused C/C++ symbols with GCC and ld?

It seems to me that the answer provided by Nemo is the correct one. If those instructions do not work, the issue may be related to the version of gcc/ld you're using, as an exercise I compiled an example program using instructions detailed here

#include <stdio.h>
void deadcode() { printf("This is d dead codez\n"); }
int main(void) { printf("This is main\n"); return 0 ; }

Then I compiled the code using progressively more aggressive dead-code removal switches:

gcc -Os test.c -o test.elf
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections -Wl,--strip-all

These compilation and linking parameters produced executables of size 8457, 8164 and 6160 bytes, respectively, the most substantial contribution coming from the 'strip-all' declaration. If you cannot produce similar reductions on your platform,then maybe your version of gcc does not support this functionality. I'm using gcc(4.5.2-8ubuntu4), ld(2.21.0.20110327) on Linux Mint 2.6.38-8-generic x86_64

DevTools failed to load SourceMap: Could not load content for chrome-extension

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

SQLite error 'attempt to write a readonly database' during insert?

This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db

Errors: Data path ".builders['app-shell']" should have required property 'class'

Everyone here is focusing on downgrading @angular-devkit/build-angular to @angular 7.x versions for compatibility, but what they should be doing is to upgrade @angular/cli to angular 8 versions.

The problem is that the system cli is still stuck at an old version and isn't automatically updated by ng update (because it is outside the angular controlled project), so it is being left at an incompatible version when trying to access the angular libraries.

Downgrading @angular-devkit/build-angular just causes more incompatibilities.

npm i --global @angular/cli@latest

will fix the problem without breaking things elsewhere.

How to generate a random alpha-numeric string

static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SecureRandom rnd = new SecureRandom();

String randomString(int len){
   StringBuilder sb = new StringBuilder(len);
   for(int i = 0; i < len; i++)
      sb.append(AB.charAt(rnd.nextInt(AB.length())));
   return sb.toString();
}

How to align linearlayout to vertical center?

Change orientation and gravity in

<LinearLayout
    android:id="@+id/groupNumbers"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_weight="0.7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

to

android:orientation="vertical"
android:layout_gravity="center_vertical"

You are adding orientation: horizontal, so the layout will contain all elements in single horizontal line. Which won't allow you to get the element in center.

Hope this helps.

SQL injection that gets around mysql_real_escape_string()

TL;DR

mysql_real_escape_string() will provide no protection whatsoever (and could furthermore munge your data) if:

  • MySQL's NO_BACKSLASH_ESCAPES SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); and

  • your SQL string literals are quoted using double-quote " characters.

This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).

This is another, (perhaps less?) obscure EDGE CASE!!!

In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:

The Attack

Starting off with a demonstration...

mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

This will return all records from the test table. A dissection:

  1. Selecting an SQL Mode

    mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
    

    As documented under String Literals:

    There are several ways to include quote characters within a string:

    • A “'” inside a string quoted with “'” may be written as “''”.

    • A “"” inside a string quoted with “"” may be written as “""”.

    • Precede the quote character by an escape character (“\”).

    • A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.

    If the server's SQL mode includes NO_BACKSLASH_ESCAPES, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.

  2. The Payload

    " OR 1=1 -- 
    

    The payload initiates this injection quite literally with the " character. No particular encoding. No special characters. No weird bytes.

  3. mysql_real_escape_string()

    $var = mysql_real_escape_string('" OR 1=1 -- ');
    

    Fortunately, mysql_real_escape_string() does check the SQL mode and adjust its behaviour accordingly. See libmysql.c:

    ulong STDCALL
    mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
                 ulong length)
    {
      if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
        return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
      return escape_string_for_mysql(mysql->charset, to, 0, from, length);
    }
    

    Thus a different underlying function, escape_quotes_for_mysql(), is invoked if the NO_BACKSLASH_ESCAPES SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.

    However, this function arbitrarily assumes that the string will be quoted using the single-quote ' character. See charset.c:

    /*
      Escape apostrophes by doubling them up
    
    // [ deletia 839-845 ]
    
      DESCRIPTION
        This escapes the contents of a string by doubling up any apostrophes that
        it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
        effect on the server.
    
    // [ deletia 852-858 ]
    */
    
    size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
                                   char *to, size_t to_length,
                                   const char *from, size_t length)
    {
    // [ deletia 865-892 ]
    
        if (*from == '\'')
        {
          if (to + 2 > to_end)
          {
            overflow= TRUE;
            break;
          }
          *to++= '\'';
          *to++= '\'';
        }
    

    So, it leaves double-quote " characters untouched (and doubles all single-quote ' characters) irrespective of the actual character that is used to quote the literal! In our case $var remains exactly the same as the argument that was provided to mysql_real_escape_string()—it's as though no escaping has taken place at all.

  4. The Query

    mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
    

    Something of a formality, the rendered query is:

    SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
    

As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

mysql_set_charset() cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string(), since that's just a different wrapper around this same function.

The problem, if not already obvious, is that the call to mysql_real_escape_string() cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).

The Ugly

It gets worse. NO_BACKSLASH_ESCAPES may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote> grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes().

Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.

The Saving Grace

So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql() will not be used, or its assumption about which quote characters require repeating will be correct.

For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES also enables ANSI_QUOTES mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).

In PDO, both its equivalent function PDO::quote() and its prepared statement emulator call upon mysql_handle_quoter()—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.

As of MySQL v5.7.6, this bug has been fixed. See change log:

Functionality Added or Changed

Safe Examples

Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):

mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES.

mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

...because we're quoting our string literal with single-quotes.

$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);

...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).

$var  = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

...because PDO's quote() function not only escapes the literal, but also quotes it (in single-quote ' characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.

$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

...because MySQLi prepared statements are safe.

Wrapping Up

Thus, if you:

  • use native prepared statements

OR

  • use MySQL v5.7.6 or later

OR

  • in addition to employing one of the solutions in ircmaxell's summary, use at least one of:

    • PDO;
    • single-quoted string literals; or
    • an explicitly set SQL mode that does not include NO_BACKSLASH_ESCAPES

...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).

Editable text to string

This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string

EditText dob=(EditText)findviewbyid(R.id.edit_id);
String  str=dob.getText().toString();

c# open a new form then close the current form?

Steve's solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().

private void OnButton1Click(object sender, EventArgs e)
{
    this.Hide();
    var form2 = new Form2();
    form2.Closed += (s, args) => this.Close(); 
    form2.Show();
}

Is there a 'box-shadow-color' property?

Yes there is a way

box-shadow 0 0 17px 13px rgba(30,140,255,0.80) inset

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

colleagues.

I have faced with this trouble during a development of automation tests for our REST API. JDK 7_80 was installed at my machine only. Before I installed JDK 8, everything worked just fine and I had a possibility to obtain OAuth 2.0 tokens with a JMeter. After I installed JDK 8, the nightmare with Certificates does not conform to algorithm constraints began.

Both JMeter and Serenity did not have a possibility to obtain a token. JMeter uses the JDK library to make the request. The library just raises an exception when the library call is made to connect to endpoints that use it, ignoring the request.

The next thing was to comment all the lines dedicated to disabledAlgorithms in ALL java.security files.

C:\Java\jre7\lib\security\java.security
C:\Java\jre8\lib\security\java.security
C:\Java\jdk8\jre\lib\security\java.security
C:\Java\jdk7\jre\lib\security\java.security

Then it started to work at last. I know, that's a brute force approach, but it was the most simple way to fix it.

# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
# jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024

How to show matplotlib plots in python

In case anyone else ends up here using Jupyter Notebooks, you just need

%matplotlib inline

Purpose of "%matplotlib inline"

Is it possible to view RabbitMQ message contents directly from the command line?

If you want multiple messages from a queue, say 10 messages, the command to use is:

rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10

If you don't want the messages requeued, just change ackmode to ack_requeue_false.

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

How to repeat last command in python interpreter shell?

Ctrl+p is the normal alternative to the up arrow. Make sure you have gnu readline enabled in your Python build.

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Getting rid of all the rounded corners in Twitter Bootstrap

Download the source .less files and make the .border-radius() mixin blank.

MySQL Cannot drop index needed in a foreign key constraint

A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:

  • When creating a foreign key, the database checks if an index exists. If not an index will be created. By default, it will have the same name as the constraint.
  • When there is only one index that can be used for the foreign key, it can't be dropped. If you really wan't to drop it, you either have to drop the foreign key constraint or to create another index for it first.

Best way to split string into lines

You could use Regex.Split:

string[] tokens = Regex.Split(input, @"\r?\n|\r");

Edit: added |\r to account for (older) Mac line terminators.

Jquery get input array field

You need to use the starts with selector

var elems = $( "[name^='pages_title']" );

But a better solution is to add a class to the elements and reference the class. The reason it is a faster look up.

PHP: check if any posted vars are empty - form: all fields required

Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)

How to get value from form field in django framework?

To retrieve data from form which send post request you can do it like this

def login_view(request):
    if(request.POST):
        login_data = request.POST.dict()
        username = login_data.get("username")
        password = login_data.get("password")
        user_type = login_data.get("user_type")
        print(user_type, username, password)
        return HttpResponse("This is a post request")
    else:
        return render(request, "base.html")

Fitting empirical distribution to theoretical ones with Scipy (Python)?

fit() method mentioned by @Saullo Castro provides maximum likelihood estimates (MLE). The best distribution for your data is the one give you the highest can be determined by several different ways: such as

1, the one that gives you the highest log likelihood.

2, the one that gives you the smallest AIC, BIC or BICc values (see wiki: http://en.wikipedia.org/wiki/Akaike_information_criterion, basically can be viewed as log likelihood adjusted for number of parameters, as distribution with more parameters are expected to fit better)

3, the one that maximize the Bayesian posterior probability. (see wiki: http://en.wikipedia.org/wiki/Posterior_probability)

Of course, if you already have a distribution that should describe you data (based on the theories in your particular field) and want to stick to that, you will skip the step of identifying the best fit distribution.

scipy does not come with a function to calculate log likelihood (although MLE method is provided), but hard code one is easy: see Is the build-in probability density functions of `scipy.stat.distributions` slower than a user provided one?

how to create virtual host on XAMPP

I fixed it using following configuration.

 Listen 85
 <VirtualHost *:85>
           DocumentRoot "C:/xampp/htdocs/LaraBlog/public"
           <Directory "C:/xampp/htdocs/CommunicationApp/public">
           DirectoryIndex index.php
           AllowOverride All
           Order allow,deny
           Allow from all
           </Directory>
 </VirtualHost>

How can you print a variable name in python?

Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

Convert data.frame column format from character to factor

Another short way you could use is a pipe (%<>%) from the magrittr package. It converts the character column mycolumn to a factor.

library(magrittr)

mydf$mycolumn %<>% factor

Constants in Kotlin -- what's a recommended way to create them?

Like val, variables defined with the const keyword are immutable. The difference here is that const is used for variables that are known at compile-time.

Declaring a variable const is much like using the static keyword in Java.

Let's see how to declare a const variable in Kotlin:

const val COMMUNITY_NAME = "wiki"

And the analogous code written in Java would be:

final static String COMMUNITY_NAME = "wiki";

Adding to the answers above -

@JvmField an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.

 @JvmField
 val COMMUNITY_NAME: "Wiki"

Static fields

Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.

Usually these fields are private but they can be exposed in one of the following ways:

  • @JvmField annotation;
  • lateinit modifier;
  • const modifier.

More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields

How to reset a timer in C#?

i do this

//Restart the timer
queueTimer.Enabled = true;

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

We can use the below its very simple.

Date.ToString("yyyy-MM-dd");

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It IS possible, using something like the below example that I put together with the help of work from (https://gist.github.com/bitinn/1700068a276fb29740a7) that didn't quite work on iOS 11:

Here's the modified code that works on iOS 11.03, please comment if it worked for you.

The key is adding some size to BODY so the browser can scroll, ex: height: calc(100% + 40px);

Full sample below & link to view in your browser (please test!)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeHots iOS WebApp Minimal UI via Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }
        html {
            background-color: red;
        }
        body {
            background-color: blue;
            /* important to allow page to scroll */
            height: calc(100% + 40px);
            margin: 0;
        }
        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }
        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }
        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }
        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }
            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        function interceptTouchMove(){
            // and disable the touchmove features 
            window.addEventListener("touchmove", (event)=>{
                if (!event.target.classList.contains('scrollable')) {
                    // no more scrolling
                    event.preventDefault();
                }
            }, false); 
        }

        function scrollDetect(event){
            // wait for the result to settle
            if( timeout ) clearTimeout(timeout);

            timeout = setTimeout(function() {
                console.log( 'scrolled up detected..' );
                if (window.scrollY > 35) {
                    console.log( ' .. moved up enough to go into minimal UI mode. cover off and locking touchmove!');
                    // hide the fixed scroll-cover
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';

                    // push back down to designated start-point. (as it sometimes overscrolls (this is jQuery implementation I used))
                    window.scrollY = 40;

                    // and disable the touchmove features 
                    interceptTouchMove();

                    // turn off scroll checker
                    window.removeEventListener('scroll', scrollDetect );                
                }
            }, 200);            
        }

        // listen to scroll to know when in minimal-ui mode.
        window.addEventListener('scroll', scrollDetect, false );
    </script>
</head>
<body>

    <div class="header">
        <p>header zone</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>

Full example link here: https://repos.codehot.tech/misc/ios-webapp-example2.html

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

HTML-Tooltip position relative to mouse pointer

You can use jQuery UI plugin, following are reference URLs

Set track to TRUE for Tooltip position relative to mouse pointer eg.

_x000D_
_x000D_
$('.tooltip').tooltip({ track: true });
_x000D_
_x000D_
_x000D_

How to reduce a huge excel file

I have worked extensively in Excel and have found the following 3 points very useful

Find if there are cells which apparently do not hold any data but Excel considers them to have data

You can find this by using the following property on a sheet

ActiveSheet.UsedRange.Rows.Count
ActiveSheet.UsedRange.Columns.Count

If this range is more than the cells on which you have data, delete the rest of the rows/columns

You will be surprised to see the amount of space it can free

Convert files to .xlsb format

XLSM format is to make Excel compliant with Open XML, but there are very few instances when we actually use the XML format of Excel. This reduces size by almost 50% if not more

Optimum way of storing information

For example if you have to save the stock price for around 10 years, and you need to save Open, High, Low, Close for a stock, this would result in (252*10) * (4) cells being used

Instead, of using separate columns for Open,High,Low,Close save them in a single column with a field separator Open:High:Low:Close

You can easily write a function to extract info from the single column whenever you want to, but it will free up almost 2/3rd space that you are currently taking up

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

How to get a value inside an ArrayList java

If you want to get the price of all cars you have to iterate through the array list:

public static void processCars(ArrayList<Cars> cars) {
   for (Car c : cars) {
       System.out.println (c.getPrice());
   }
}

How to unzip files programmatically in Android?

Minimal example I used to unzip a specific file from my zipfile into my applications cache folder. I then read the manifest file using a different method.

private void unzipUpdateToCache() {
    ZipInputStream zipIs = new ZipInputStream(context.getResources().openRawResource(R.raw.update));
    ZipEntry ze = null;

    try {

        while ((ze = zipIs.getNextEntry()) != null) {
            if (ze.getName().equals("update/manifest.json")) {
                FileOutputStream fout = new FileOutputStream(context.getCacheDir().getAbsolutePath() + "/manifest.json");

                byte[] buffer = new byte[1024];
                int length = 0;

                while ((length = zipIs.read(buffer))>0) {
                    fout.write(buffer, 0, length);
                }
                zipIs .closeEntry();
                fout.close();
            }
        }
        zipIs .close();

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

}

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

Creating folders inside a GitHub repository without using Git

You can also just enter the website and:

  1. Choose a repository you have write access to (example URL)
  2. Click "Upload files"
  3. Drag and drop a folder with files into the "Drag files here to add them to your repository" area.

The same limitation applies here: the folder must contain at least one file inside it.

How to install a package inside virtualenv?

From documentation https://docs.python.org/3/library/venv.html:

The pyvenv script has been deprecated as of Python 3.6 in favor of using python3 -m venv to help prevent any potential confusion as to which Python interpreter a virtual environment will be based on.

In order to create a virtual environment for particular project, create a file /home/user/path/to/create_venv.sh:

#!/usr/bin/env bash

# define path to your project's directory
PROJECT_DIR=/home/user/path/to/Project1

# a directory with virtual environment
# will be created in your Project1 directory
# it recommended to add this path into your .gitignore
VENV_DIR="${PROJECT_DIR}"/venv

# https://docs.python.org/3/library/venv.html
python3 -m venv "${VENV_DIR}"

# activates the newly created virtual environment
. "${VENV_DIR}"/bin/activate

# prints activated version of Python
python3 -V

pip3 install --upgrade pip

# Write here all Python libraries which you want to install over pip
# An example or requirements.txt see here:
# https://docs.python.org/3/tutorial/venv.html#managing-packages-with-pip
pip3 install -r "${PROJECT_DIR}"/requirements.txt

echo "Virtual environment ${VENV_DIR} has been created"

deactivate

Then run this script in the console:

$ bash /home/user/path/to/create_venv.sh

Select top 2 rows in Hive

Yes, here you can use LIMIT.

You can try it by the below query:

SELECT * FROM employee_list SORT BY salary DESC LIMIT 2

Difference between float and decimal data type

MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.

The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.

By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)

The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.

As 18 8-bit chars: 144 bits

As 18 4-bit nybbles: 72 bits

As 2 32-bit integers: 64 bits

Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.

So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.

With an 7-bit int: 0 - 99

With a 15-bit int: 0 - 9,999

With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)

1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.

This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.

Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.

In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.

The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.

As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.

What's the best way to get the last element of an array without deleting it?

One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:

// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));

// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));

// PHP Strict standards:  Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));

// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));

Converting a view to Bitmap without displaying it in Android?

I know this may be a stale issue, but I was having problems getting any of these solutions to work for me. Specifically, I found that if any changes were made to the view after it was inflated that those changes would not get incorporated into the rendered bitmap.

Here's the method which ended up working for my case. With one caveat, however. prior to calling getViewBitmap(View) I inflated my view and asked it to layout with known dimensions. This was needed since my view layout would make it zero height/width until content was placed inside.

View view = LayoutInflater.from(context).inflate(layoutID, null);
//Do some stuff to the view, like add an ImageView, etc.
view.layout(0, 0, width, height);

Bitmap getViewBitmap(View view)
{
    //Get the dimensions of the view so we can re-layout the view at its current size
    //and create a bitmap of the same size 
    int width = view.getWidth();
    int height = view.getHeight();

    int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
    int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);

    //Cause the view to re-layout
    view.measure(measuredWidth, measuredHeight);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    //Create a bitmap backed Canvas to draw the view into
    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);

    //Now that the view is laid out and we have a canvas, ask the view to draw itself into the canvas
    view.draw(c);

    return b;
}

The "magic sauce" for me was found here: https://groups.google.com/forum/#!topic/android-developers/BxIBAOeTA1Q

Cheers,

Levi

ssh: The authenticity of host 'hostname' can't be established

Old question that deserves a better answer.

You can prevent interactive prompt without disabling StrictHostKeyChecking (which is insecure).

Incorporate the following logic into your script:

if [ -z "$(ssh-keygen -F $IP)" ]; then
  ssh-keyscan -H $IP >> ~/.ssh/known_hosts
fi

It checks if public key of the server is in known_hosts. If not, it requests public key from the server and adds it to known_hosts.

In this way you are exposed to Man-In-The-Middle attack only once, which may be mitigated by:

  • ensuring that the script connects first time over a secure channel
  • inspecting logs or known_hosts to check fingerprints manually (to be done only once)

Bootstrap col-md-offset-* not working

Where's the problem

In your HTML all h2s have the same off-set of 4 columns, so they won't make a diagonal.

How to fix it

A row has 12 columns, so we should put every h2 in it's own row. You should have something like this:

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-4 col-md-offset-1">Browse.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-2">create.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

An alternative is to make every h2 width plus offset sum 12 columns, so each one automatically wraps in a new line.

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-11 col-md-offset-1">Browse.</h2>
                <h2 class="col-md-10 col-md-offset-2">create.</h2>
                <h2 class="col-md-9 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

Any way to Invoke a private method?

One more variant is using very powerfull JOOR library https://github.com/jOOQ/jOOR

MyObject myObject = new MyObject()
on(myObject).get("privateField");  

It allows to modify any fields like final static constants and call yne protected methods without specifying concrete class in the inheritance hierarhy

<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
     <groupId>org.jooq</groupId>
     <artifactId>joor-java-8</artifactId>
     <version>0.9.7</version>
</dependency>

jQuery - hashchange event

A different approach to your problem...

There are 3 ways to bind the hashchange event to a method:

<script>
    window.onhashchange = doThisWhenTheHashChanges;
</script>

Or

<script>
    window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
</script>

Or

<body onhashchange="doThisWhenTheHashChanges();">

These all work with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

Cannot connect to SQL Server named instance from another SQL Server

You've tried alot. And I feel for you. Here is an idea. I kinda followed everything you tried. The mental note I have in my head goes like this: "When Sql Server won't connect when you've tried everything, wire up your firewall rules by the program, not the port"

I know you said you disabled the firewall. But something is telling me to give this a try anyways.

I think you have to open the firewall "by program", and not by port.

http://technet.microsoft.com/en-us/library/cc646023.aspx

To add a program exception to the firewall using the Windows Firewall item in Control Panel.


On the Exceptions tab of the Windows Firewall item in Control Panel, click Add a program.


Browse to the location of the instance of SQL Server that you want to allow through the firewall, for example C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn, select sqlservr.exe, and then click Open.


 Click OK.

EDIT..........

http://msdn.microsoft.com/en-us/library/ms190479.aspx

I'm a little cloudy on which "program" you're trying to use on SQLB?

Is it SSMS on SQLB? Or a client program on SQLB ?

EDIT...........

No idea if this will help. But I use this to ping "ports" ... and something that is outside of the SSMS world.

http://www.microsoft.com/en-us/download/details.aspx?id=24009

Simple way to transpose columns and rows in SQL?

Based on this solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

You can test it with the table provided with this command:

exec SQLTranspose 'yourTable', 'color'

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Get the correct week number of a given date

This is the way:

public int GetWeekNumber()
{
    CultureInfo ciCurr = CultureInfo.CurrentCulture;
    int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    return weekNum;
}

Most important for is the CalendarWeekRule parameter.

See here: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework

How to input a string from user into environment variable from batch file

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"

Two values from one input in python?

The Python way to map

printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)

would be

var1, var2 = raw_input("Enter two numbers here: ").split()

Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,

Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line

var1, var2 = [int(var1), int(var2)]

Or you could use list comprehension

var1, var2 = [int(x) for x in [var1, var2]]

To sum it up, you could have done the whole thing with this one-liner:

# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]

# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]

How can I debug a HTTP POST in Chrome?

The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.

Working with it is queit easy.

  1. Using your Firefox, navigate to the website which you want to get your post request to it.

  2. In your Firefox menu Tools->Live Http Headers

  3. A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.

  4. In the website, do an activity(log in, submit a form, etc.)

  5. Look at your plug in window. It is all recorded.

Just remember you need to check the Capture.

enter image description here

Autoplay audio files on an iPad with HTML5

It seems to me that the answer to this question is (at least now) clearly documented on the Safari HTML5 docs:

User Control of Downloads Over Cellular Networks

In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.

This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">

This does nothing on iOS: <body onLoad="document.myMovie.play()">

XML Parser for C

You can try ezxml -- it's a lightweight parser written entirely in C.

For C++ you can check out TinyXML++

How to use NULL or empty string in SQL

--setup
IF OBJECT_ID('tempdb..#T') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T(ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, NAME VARCHAR(10))
INSERT INTO #T (Name) VALUES('JOHN'),(''),(NULL);
SELECT * FROM #T
 1  JOHN
 2  -- is empty string
 3  NULL

You can examine '' as NULL by converting it to NULL using NULLIF

--here you set '' to null
UPDATE #T SET NAME = NULLIF(NAME,'')
SELECT * FROM #T 
 1  JOHN
 2  NULL
 3  NULL

or you can examine NULL as '' using SELECT ISNULL(NULL,'')

-- here you set NULL to ''
UPDATE #T SET NAME = ISNULL(NULL,'') WHERE NAME IS NULL
SELECT * FROM #T
1   JOHN
2   -- is empty string
3   -- is empty string

--clean up
DROP TABLE #T

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

Read from file in eclipse

Have you tried using an absolute path:

File file = new File(System.getProperty("user.dir") + "/file.txt");

Entity Framework is Too Slow. What are my options?

The Entity Framework should not cause major bottlenecks itself. Chances are that there are other causes. You could try to switch EF to Linq2SQL, both have comparing features and the code should be easy to convert but in many cases Linq2SQL is faster than EF.

Byte Array to Image object

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

How to set 24-hours format for date on java?

This will give you the date in 24 hour format.

    Date date = new Date();
    date.setHours(date.getHours() + 8);
    System.out.println(date);
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.format(date));

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

Just remember, if the field you want to make nullable is part of a primary key, you can't. Primary Keys cannot have null fields.

Find an item in List by LINQ?

If you want the index of the element, this will do it:

int index = list.Select((item, i) => new { Item = item, Index = i })
                .First(x => x.Item == search).Index;

// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
            where pair.Item == search
            select pair.Index).First();

You can't get rid of the lambda in the first pass.

Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:

var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
            where pair.Item == search
            select pair.Index).FirstOrDefault();

If you want the item:

// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).First();

// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).FirstOrDefault();

If you want to count the number of items that match:

int count = list.Count(item => item == search);
// or
int count = (from item in list
            where item == search
            select item).Count();

If you want all the items that match:

var items = list.Where(item => item == search);
// or
var items = from item in list
            where item == search
            select item;

And don't forget to check the list for null in any of these cases.

Or use (list ?? Enumerable.Empty<string>()) instead of list.

Thanks to Pavel for helping out in the comments.

Explain ExtJS 4 event handling

Let's start by describing DOM elements' event handling.

DOM node event handling

First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element interface. For the purpose of assigning event handlers, Element.addListener and Element.on (these are equivalent) were created. So, for example, if we have html:

<div id="test_node"></div>

and we want add click event handler.
Let's retrieve Element:

var el = Ext.get('test_node');

Now let's check docs for click event. It's handler may have three parameters:

click( Ext.EventObject e, HTMLElement t, Object eOpts )

Knowing all this stuff we can assign handler:

//       event name      event handler
el.on(    'click'        , function(e, t, eOpts){
  // handling event here
});

Widgets event handling

Widgets event handling is pretty much similar to DOM nodes event handling.

First of all, widgets event handling is realized by utilizing Ext.util.Observable mixin. In order to handle events properly your widget must containg Ext.util.Observable as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable as a mixin by default.

For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener). Let's for example create Button widget and assign click event to it. First of all you should check event's docs for handler's arguments:

click( Ext.button.Button this, Event e, Object eOpts )

Now let's use on:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
  // event handling here
  console.log(btn, e, eOpts);
});

The second way is to use widget's listeners config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  listeners : {
    click: function(btn, e, eOpts) {
      // event handling here
      console.log(btn, e, eOpts);
    }
  }
});

Notice that Button widget is a special kind of widgets. Click event can be assigned to this widget by using handler config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  handler : function(btn, e, eOpts) {
    // event handling here
    console.log(btn, e, eOpts);
  }
});

Custom events firing

First of all you need to register an event using addEvents method:

myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);

Using the addEvents method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.

To fire your event use fireEvent method:

myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);

arg1, arg2, arg3, /* ... */ will be passed into handler. Now we can handle your event:

myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
  // event handling here
  console.log(arg1, arg2, arg3, /* ... */);
});

It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent method when you are defining new widget:

Ext.define('MyCustomButton', {
  extend: 'Ext.button.Button',
  // ... other configs,
  initComponent: function(){
    this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
    // ...
    this.callParent(arguments);
  }
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });

Preventing event bubbling

To prevent bubbling you can return false or use Ext.EventObject.preventDefault(). In order to prevent browser's default action use Ext.EventObject.stopPropagation().

For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:

myButton.on('click', function(btn, e){
  if (e.button !== 0)
    e.preventDefault();
});

How do I enable/disable log levels in Android?

I took a simple route - creating a wrapper class that also makes use of variable parameter lists.

 public class Log{
        public static int LEVEL = android.util.Log.WARN;


    static public void d(String tag, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args));
        }
    }

    static public void d(String tag, Throwable t, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args), t);
        }
    }

    //...other level logging functions snipped

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Example use of "continue" statement in Python?

continue simply skips the rest of the code in the loop until next iteration

How to round up a number in Javascript?

parseInt always rounds down soo.....

_x000D_
_x000D_
console.log(parseInt(5.8)+1);
_x000D_
_x000D_
_x000D_

do parseInt()+1

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

Creating executable files in Linux

I think the problem you're running into is that, even though you can set your own umask values in the system, this does not allow you to explicitly control the default permissions set on a new file by gedit (or whatever editor you use).

I believe this detail is hard-coded into gedit and most other editors. Your options for changing it are (a) hacking up your own mod of gedit or (b) finding a text editor that allows you to set a preference for default permissions on new files. (Sorry, I know of none.)

In light of this, it's really not so bad to have to chmod your files, right?

Android: show/hide status bar/power bar

For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,

Here is the solution that worked for me, (Documentation) (Flag Reference)

Hide Status Bar

// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
   View decorView = getWindow().getDecorView();
  // Hide Status Bar.
   int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
   decorView.setSystemUiVisibility(uiOptions);
}

Show Status Bar

   if (Build.VERSION.SDK_INT < 16) {
              getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    else {
       View decorView = getWindow().getDecorView();
      // Show Status Bar.
       int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
       decorView.setSystemUiVisibility(uiOptions);
    }

JPA Query selecting only specific columns without using Criteria Query?

Excellent answer! I do have a small addition. Regarding this solution:

TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();CustomObject.class);

To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:

String query = "SELECT NEW org.company.directory.CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

How to get source code of a Windows executable?

I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.

If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

Change Text Color of Selected Option in a Select Box

ONE COLOR CASE - CSS only

Just to register my experience, where I wanted to set only the color of the selected option to a specific one.

I first tried to set by css only the color of the selected option with no success.

Then, after trying some combinations, this has worked for me with SCSS:

select {
      color: white; // color of the selected option

      option {
        color: black; // color of all the other options
      }
 }

Take a look at a working example with only CSS:

_x000D_
_x000D_
select {_x000D_
  color: yellow; // color of the selected option_x000D_
 }_x000D_
_x000D_
select option {_x000D_
  color: black; // color of all the other options_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option value="apple" >Apple</option>_x000D_
    <option value="banana" >Banana</option>_x000D_
    <option value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

For different colors, depending on the selected option, you'll have to deal with js.

what is the size of an enum type data in C++?

The size is four bytes because the enum is stored as an int. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

0 0 0 0  January
0 0 0 1  February
0 0 1 0  March
0 0 1 1  April
0 1 0 0  May
0 1 0 1  June
0 1 1 0  July
0 1 1 1  August
1 0 0 0  September
1 0 0 1  October
1 0 1 0  November
1 0 1 1  December
1 1 0 0  ** unused **
1 1 0 1  ** unused **
1 1 1 0  ** unused **
1 1 1 1  ** unused **

Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

How do I compare two string variables in an 'if' statement in Bash?

You should be careful to leave a space between the sign of '[' and double quotes where the variable contains this:

if [ "$s1" == "$s2" ]; then
#   ^     ^  ^     ^
   echo match
fi

The ^s show the blank spaces you need to leave.

Read data from a text file using Java

public class ReadFileUsingFileInputStream {

/**
* @param args
*/
static int ch;

public static void main(String[] args) {
    File file = new File("C://text.txt");
    StringBuffer stringBuffer = new StringBuffer("");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            while((ch = fileInputStream.read())!= -1){
                stringBuffer.append((char)ch);  
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File contents :");
    System.out.println(stringBuffer);
    }
}

How to clear mysql screen console in windows?

Click with contextMenu button on Mysql prompt and choose "Scroll", because I didn't find any way to clean too. =P

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

How can I scale an image in a CSS sprite

Use transform: scale(0.8); with the value you need instead of 0.8

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

Spring schemaLocation fails when there is no internet connection

If there is no internet connection in your platform and you use Eclipse, follow these steps (it solves my problem)

  1. Find the exact xsd files (You can unzip these files from their jars. For example, spring-beans-x.y.xsd in spring-beans-x.y.z.RELEASE.jar)
  2. Add these xsd files to Eclipse XML Catalog. (Preferences->XML->XML Catalog, Add files)
  3. Add these files location to configuration file. (Be careful, write the exact version of file)

Example:

xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-x.y.xsd "

Align DIV to bottom of the page

Simple 2020 no-tricks method:

body {
    display: flex;
    flex-direction: column;
}

#footer {
    margin-top: auto;
}

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

Is there any way to change input type="date" format?

I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.

The order of keys in dictionaries

You could use OrderedDict (requires Python 2.7) or higher.

Also, note that OrderedDict({'a': 1, 'b':2, 'c':3}) won't work since the dict you create with {...} has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)]).

As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.

ESLint not working in VS Code?

Restarting VSCode worked for me.

Datatable select method ORDER BY clause

You can use the below simple method of sorting:

datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";

By the above method, you will be able to sort N number of columns.

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

HTML - how to make an entire DIV a hyperlink?

You can add the onclick for JavaScript into the div.

<div onclick="location.href='newurl.html';">&nbsp;</div>

EDIT: for new window

<div onclick="window.open('newurl.html','mywindow');" style="cursor: pointer;">&nbsp;</div>

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

How to pass in a react component into another react component to transclude the first component's content?

Late to the game, but here's a powerful HOC pattern for overriding a component by providing it as a prop. It's simple and elegant.

Suppose MyComponent renders a fictional A component but you want to allow for a custom override of A, in this example B, which wraps A in a <div>...</div> and also appends "!" to the text prop:

import A from 'fictional-tooltip';

const MyComponent = props => (
  <props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };

const B = props => (
  <div><A {...props} text={props.text + '!'}></div>
);

ReactDOM.render(<MyComponent A={B}/>);

How to convert a JSON string to a Map<String, String> with Jackson JSON

Warning you get is done by compiler, not by library (or utility method).

Simplest way using Jackson directly would be:

HashMap<String,Object> props;

// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);

Utility method you call probably just does something similar to this.

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

Convert JavaScript string in dot notation into an object reference

If you want to do this in the fastest possible way, while at the same time handling any issues with the path parsing or property resolution, check out path-value.

const {resolveValue} = require('path-value');

const value = resolveValue(obj, 'a.b.c');

The library is 100% TypeScript, works in NodeJS + all web browsers. And it is fully extendible, you can use lower-level resolvePath, and handle errors your own way, if you want.

const {resolvePath} = require('path-value');

const res = resolvePath(obj, 'a.b.c'); //=> low-level parsing result descriptor

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

Force decimal point instead of comma in HTML5 number input (client-side)

I don't know if this helps but I stumbled here when searching for this same problem, only from an input point of view (i.e. I noticed that my <input type="number" /> was accepting both a comma and a dot when typing the value, but only the latter was being bound to the angularjs model I assigned to the input). So I solved by jotting down this quick directive:

.directive("replaceComma", function() {
    return {
        restrict: "A",
        link: function(scope, element) {
            element.on("keydown", function(e) {
                if(e.keyCode === 188) {
                    this.value += ".";
                    e.preventDefault();
                }
            });
        }
    };
});

Then, on my html, simply: <input type="number" ng-model="foo" replace-comma /> will substitute commas with dots on-the-fly to prevent users from inputting invalid (from a javascript standpoint, not a locales one!) numbers. Cheers.

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

Android failed to load JS bundle

I found this to be weird but I got a solution. I noticed that every once in a while my project folder went read-only and I couldn't save it from VS. So I read a suggestion to transfer NPM from local user PATH to system-wide PATH global variable, and it worked like a charm.

React Native fetch() Network Request Failed

You can handle it using this :

catch((error) => {
      this.setState({
        typing_animation_button: false,
      });
      console.log(error);
      if ('Timeout' || 'Network request failed') {
        toast_show = true;
        toast_type = 'error';
        toast_text = 'Network failure';
      }
      this.setState({
        disable_button: false,
      });
    });

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Best way to display data via JSON using jQuery

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

Print a div using javascript in angularJS single page application

This is what worked for me in Chrome and Firefox! This will open the little print window and close it automatically once you've clicked print.

var printContents = document.getElementById('div-id-selector').innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no,top=50');
            popupWin.window.focus();
            popupWin.document.open();
            popupWin.document.write('<!DOCTYPE html><html><head><title>TITLE OF THE PRINT OUT</title>' 
                                    +'<link rel="stylesheet" type="text/css" href="app/directory/file.css" />' 
                                    +'</head><body onload="window.print(); window.close();"><div>' 
                                    + printContents + '</div></html>');
            popupWin.document.close();

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

Swift - How to convert String to Double

Or you could do:

var myDouble = Double((mySwiftString.text as NSString).doubleValue)

Can I inject a service into a directive in AngularJS?

You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.

template.html

<div my-directive api-service='ServiceName'></div>

my-directive.directive.coffee

angular.module 'my.module'
  .factory 'myDirective', ($injector) ->
    directive = 
      restrict: 'A'
      link: (scope, element, attributes) ->
        scope.apiService = $injector.get(attributes.apiService)

now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data

For example:

scope.apiService.query((response) ->
  scope.data = response
, (errorResponse) ->
  console.log "ERROR fetching data for service: #{attributes.apiService}"
  console.log errorResponse.data
)

I have found this technique to be very useful when making elements that interact with API endpoints especially.

What is logits, softmax and softmax_cross_entropy_with_logits?

One more thing that I would definitely like to highlight as logit is just a raw output, generally the output of last layer. This can be a negative value as well. If we use it as it's for "cross entropy" evaluation as mentioned below:

-tf.reduce_sum(y_true * tf.log(logits))

then it wont work. As log of -ve is not defined. So using o softmax activation, will overcome this problem.

This is my understanding, please correct me if Im wrong.

MySQL vs MySQLi when using PHP

What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.

Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.

Send values from one form to another form

you can pass as parameter the textbox of the Form1, like this:

On Form 1 buttom handler:

private void button2_Click(object sender, EventArgs e)
{
Form2 newWindow = new Form2(textBoxForReturnValue);
newWindow.Show(); 
}

On the Form 2

public static TextBox textBox2; // class atribute

public Form2(TextBox textBoxForReturnValue)
{
    textBox2= textBoxForReturnValue;
}

private void btnClose_Click(object sender, EventArgs e)
{

    textBox2.Text = dataGridView1.CurrentCell.Value.ToString().Trim();
    this.Close();
}

How to vertically align text in input type="text"?

Put it in a div tag seems to be the only way to FORCE that:

<div style="vertical-align: middle"><div><input ... /></div></div>

May be other tags like span works as like div do.

Creating a blocking Queue<T> in .NET?

"How can this be improved?"

Well, you need to look at every method in your class and consider what would happen if another thread was simultaneously calling that method or any other method. For example, you put a lock in the Remove method, but not in the Add method. What happens if one thread Adds at the same time as another thread Removes? Bad things.

Also consider that a method can return a second object that provides access to the first object's internal data - for example, GetEnumerator. Imagine one thread is going through that enumerator, another thread is modifying the list at the same time. Not good.

A good rule of thumb is to make this simpler to get right by cutting down the number of methods in the class to the absolute minimum.

In particular, don't inherit another container class, because you will expose all of that class's methods, providing a way for the caller to corrupt the internal data, or to see partially complete changes to the data (just as bad, because the data appears corrupted at that moment). Hide all the details and be completely ruthless about how you allow access to them.

I'd strongly advise you to use off-the-shelf solutions - get a book about threading or use 3rd party library. Otherwise, given what you're attempting, you're going to be debugging your code for a long time.

Also, wouldn't it make more sense for Remove to return an item (say, the one that was added first, as it's a queue), rather than the caller choosing a specific item? And when the queue is empty, perhaps Remove should also block.

Update: Marc's answer actually implements all these suggestions! :) But I'll leave this here as it may be helpful to understand why his version is such an improvement.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Use window.confirm() instead of window.alert().

HTML:

<input type="submit" onclick="return clicked();" value="Button" />

JavaScript:

function clicked() {
    return confirm('clicked');
}

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

Angular 2 two way binding using ngModel is not working

Angular 2 Beta

This answer is for those who use Javascript for angularJS v.2.0 Beta.

To use ngModel in your view you should tell the angular's compiler that you are using a directive called ngModel.

How?

To use ngModel there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES and ng.common.NgModel.

Actually ng.common.FORM_DIRECTIVES is nothing but group of directives which are useful when you are creating a form. It includes NgModel directive also.

app.myApp = ng.core.Component({
    selector: 'my-app',
    templateUrl: 'App/Pages/myApp.html',
    directives: [ng.common.NgModel] // specify all your directives here
}).Class({
    constructor: function () {
        this.myVar = {};
        this.myVar.text = "Testing";
    },

});

How can I use Timer (formerly NSTimer) in Swift?

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)

And Create Fun By The Name createEnemy

fund createEnemy ()
{
do anything ////
}

What is the pythonic way to detect the last element in a 'for' loop?

Although that question is pretty old, I came here via google and I found a quite simple way: List slicing. Let's say you want to put an '&' between all list entries.

s = ""
l = [1, 2, 3]
for i in l[:-1]:
    s = s + str(i) + ' & '
s = s + str(l[-1])

This returns '1 & 2 & 3'.

How to exit if a command failed?

Using exit directly may be tricky as the script may be sourced from other places (e.g. from terminal). I prefer instead using subshell with set -e (plus errors should go into cerr, not cout) :

set -e
ERRCODE=0
my_command || ERRCODE=$?
test $ERRCODE == 0 ||
    (>&2 echo "My command failed ($ERRCODE)"; exit $ERRCODE)

Iterate through 2 dimensional array

Just invert the indexes' order like this:

for (int j = 0; j<array[0].length; j++){
     for (int i = 0; i<array.length; i++){

because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix

Script for rebuilding and reindexing the fragmented index?

Query for REBUILD/REORGANIZE Indexes

  • 30%<= Rebuild
  • 5%<= Reorganize
  • 5%> do nothing

Query:

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName, 
ind.name AS IndexName, indexstats.index_type_desc AS IndexType, 
indexstats.avg_fragmentation_in_percent,
'ALTER INDEX ' + QUOTENAME(ind.name)  + ' ON ' +QUOTENAME(object_name(ind.object_id)) + 
CASE    WHEN indexstats.avg_fragmentation_in_percent>30 THEN ' REBUILD ' 
        WHEN indexstats.avg_fragmentation_in_percent>=5 THEN 'REORGANIZE'
        ELSE NULL END as [SQLQuery]  -- if <5 not required, so no query needed
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats 
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id 
    AND ind.index_id = indexstats.index_id 
WHERE 
--indexstats.avg_fragmentation_in_percent , e.g. >10, you can specify any number in percent 
ind.Name is not null 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

Output

TableName      IndexName            IndexType              avg_fragmentation_in_percent SQLQuery
--------------------------------------------------------------------------------------- ------------------------------------------------------
Table1         PK_Table1            CLUSTERED INDEX        75                           ALTER INDEX [PK_Table1] ON [Table1] REBUILD 
Table1         IX_Table1_col1_col2  NONCLUSTERED INDEX     66,6666666666667             ALTER INDEX [IX_Table1_col1_col2] ON [Table1] REBUILD 
Table2         IX_Table2_           NONCLUSTERED INDEX     10                           ALTER INDEX [IX_Table2_] ON [Table2] REORGANIZE
Table2         IX_Table2_           NONCLUSTERED INDEX     3                            NULL

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Extending an Object in Javascript

PLEASE ADD REASON FOR DOWNVOTE

  • No need to use any external library to extend

  • In JavaScript, everything is an object (except for the three primitive datatypes, and even they are automatically wrapped with objects when needed). Furthermore, all objects are mutable.

Class Person in JavaScript

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype = {
    getName: function() {
        return this.name;
    },
    getAge: function() {
        return this.age;
    }
}

/* Instantiate the class. */
var alice = new Person('Alice', 93);
var bill = new Person('Bill', 30);

Modify a specific instance/object.

alice.displayGreeting = function() 
{
    alert(this.getGreeting());
}

Modify the class

Person.prototype.getGreeting = function() 
{
    return 'Hi ' + this.getName() + '!';
};

Or simply say : extend JSON and OBJECT both are same

var k = {
    name : 'jack',
    age : 30
}

k.gender = 'male'; /*object or json k got extended with new property gender*/

thanks to ross harmes , dustin diaz

How do I get the Git commit count?

If you’re looking for a unique and still quite readable identifier for commits, git describe might be just the thing for you.

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Cannot read property 'map' of undefined

You need to put the data before render

Should be like this:

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

Instead of this:

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

Difference between Convert.ToString() and .ToString()

In C# if you declare a string variable and if you don’t assign any value to that variable, then by default that variable takes a null value. In such a case, if you use the ToString() method then your program will throw the null reference exception. On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.

How to decode viewstate

Here is the source code for a ViewState visualizer from Scott Mitchell's article on ViewState (25 pages)

using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.UI;


namespace ViewStateArticle.ExtendedPageClasses
{
    /// <summary>
    /// Parses the view state, constructing a viaully-accessible object graph.
    /// </summary>
    public class ViewStateParser
    {
        // private member variables
        private TextWriter tw;
        private string indentString = "   ";

        #region Constructor
        /// <summary>
        /// Creates a new ViewStateParser instance, specifying the TextWriter to emit the output to.
        /// </summary>
        public ViewStateParser(TextWriter writer)
        {
            tw = writer;
        }
        #endregion

        #region Methods
        #region ParseViewStateGraph Methods
        /// <summary>
        /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
        /// </summary>
        /// <param name="viewState">The view state object to start parsing at.</param>
        public virtual void ParseViewStateGraph(object viewState)
        {
            ParseViewStateGraph(viewState, 0, string.Empty);    
        }

        /// <summary>
        /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
        /// </summary>
        /// <param name="viewStateAsString">A base-64 encoded representation of the view state to parse.</param>
        public virtual void ParseViewStateGraph(string viewStateAsString)
        {
            // First, deserialize the string into a Triplet
            LosFormatter los = new LosFormatter();
            object viewState = los.Deserialize(viewStateAsString);

            ParseViewStateGraph(viewState, 0, string.Empty);    
        }

        /// <summary>
        /// Recursively parses the view state.
        /// </summary>
        /// <param name="node">The current view state node.</param>
        /// <param name="depth">The "depth" of the view state tree.</param>
        /// <param name="label">A label to display in the emitted output next to the current node.</param>
        protected virtual void ParseViewStateGraph(object node, int depth, string label)
        {
            tw.Write(System.Environment.NewLine);

            if (node == null)
            {
                tw.Write(String.Concat(Indent(depth), label, "NODE IS NULL"));
            } 
            else if (node is Triplet)
            {
                tw.Write(String.Concat(Indent(depth), label, "TRIPLET"));
                ParseViewStateGraph(((Triplet) node).First, depth+1, "First: ");
                ParseViewStateGraph(((Triplet) node).Second, depth+1, "Second: ");
                ParseViewStateGraph(((Triplet) node).Third, depth+1, "Third: ");
            }
            else if (node is Pair)
            {
                tw.Write(String.Concat(Indent(depth), label, "PAIR"));
                ParseViewStateGraph(((Pair) node).First, depth+1, "First: ");
                ParseViewStateGraph(((Pair) node).Second, depth+1, "Second: ");
            }
            else if (node is ArrayList)
            {
                tw.Write(String.Concat(Indent(depth), label, "ARRAYLIST"));

                // display array values
                for (int i = 0; i < ((ArrayList) node).Count; i++)
                    ParseViewStateGraph(((ArrayList) node)[i], depth+1, String.Format("({0}) ", i));
            }
            else if (node.GetType().IsArray)
            {
                tw.Write(String.Concat(Indent(depth), label, "ARRAY "));
                tw.Write(String.Concat("(", node.GetType().ToString(), ")"));
                IEnumerator e = ((Array) node).GetEnumerator();
                int count = 0;
                while (e.MoveNext())
                    ParseViewStateGraph(e.Current, depth+1, String.Format("({0}) ", count++));
            }
            else if (node.GetType().IsPrimitive || node is string)
            {
                tw.Write(String.Concat(Indent(depth), label));
                tw.Write(node.ToString() + " (" + node.GetType().ToString() + ")");
            }
            else
            {
                tw.Write(String.Concat(Indent(depth), label, "OTHER - "));
                tw.Write(node.GetType().ToString());
            }
        }
        #endregion

        /// <summary>
        /// Returns a string containing the <see cref="IndentString"/> property value a specified number of times.
        /// </summary>
        /// <param name="depth">The number of times to repeat the <see cref="IndentString"/> property.</param>
        /// <returns>A string containing the <see cref="IndentString"/> property value a specified number of times.</returns>
        protected virtual string Indent(int depth)
        {
            StringBuilder sb = new StringBuilder(IndentString.Length * depth);
            for (int i = 0; i < depth; i++)
                sb.Append(IndentString);

            return sb.ToString();
        }
        #endregion

        #region Properties
        /// <summary>
        /// Specifies the indentation to use for each level when displaying the object graph.
        /// </summary>
        /// <value>A string value; the default is three blank spaces.</value>
        public string IndentString
        {
            get
            {
                return indentString;
            }
            set
            {
                indentString = value;
            }
        }
        #endregion
    }
}

And here's a simple page to read the viewstate from a textbox and graph it using the above code

private void btnParse_Click(object sender, System.EventArgs e)
        {
            // parse the viewState
            StringWriter writer = new StringWriter();
            ViewStateParser p = new ViewStateParser(writer);

            p.ParseViewStateGraph(txtViewState.Text);
            ltlViewState.Text = writer.ToString();
        }

Auto-center map with multiple markers in Google Maps API v3

i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:

_x000D_
_x000D_
//input_x000D_
var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
_x000D_
function getCenterPosition(tempdata){_x000D_
 var tempLat = tempdata[0].split("-");_x000D_
 var latitudearray = [];_x000D_
 var longitudearray = [];_x000D_
 var i;_x000D_
 for(i=0; i<tempLat.length;i++){_x000D_
  var coordinates = tempLat[i].split("|");_x000D_
  latitudearray.push(coordinates[0]);_x000D_
  longitudearray.push(coordinates[1]);_x000D_
 }_x000D_
 latitudearray.sort(function (a, b) { return a-b; });_x000D_
 longitudearray.sort(function (a, b) { return a-b; });_x000D_
 var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
 var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
 var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
 var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
 temp = (longidifferenece / 2).toFixed(4) ;_x000D_
 var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
 var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
 var zoomvalue; _x000D_
 if(maxdifference >= 0 && maxdifference <= 0.0037)  //zoom 17_x000D_
  zoomvalue='17';_x000D_
 else if(maxdifference > 0.0037 && maxdifference <= 0.0070)  //zoom 16_x000D_
  zoomvalue='16';_x000D_
 else if(maxdifference > 0.0070 && maxdifference <= 0.0130)  //zoom 15_x000D_
  zoomvalue='15';_x000D_
 else if(maxdifference > 0.0130 && maxdifference <= 0.0290)  //zoom 14_x000D_
  zoomvalue='14';_x000D_
 else if(maxdifference > 0.0290 && maxdifference <= 0.0550)  //zoom 13_x000D_
  zoomvalue='13';_x000D_
 else if(maxdifference > 0.0550 && maxdifference <= 0.1200)  //zoom 12_x000D_
  zoomvalue='12';_x000D_
 else if(maxdifference > 0.1200 && maxdifference <= 0.4640)  //zoom 10_x000D_
  zoomvalue='10';_x000D_
 else if(maxdifference > 0.4640 && maxdifference <= 1.8580)  //zoom 8_x000D_
  zoomvalue='8';_x000D_
 else if(maxdifference > 1.8580 && maxdifference <= 3.5310)  //zoom 7_x000D_
  zoomvalue='7';_x000D_
 else if(maxdifference > 3.5310 && maxdifference <= 7.3367)  //zoom 6_x000D_
  zoomvalue='6';_x000D_
 else if(maxdifference > 7.3367 && maxdifference <= 14.222)  //zoom 5_x000D_
  zoomvalue='5';_x000D_
 else if(maxdifference > 14.222 && maxdifference <= 28.000)  //zoom 4_x000D_
  zoomvalue='4';_x000D_
 else if(maxdifference > 28.000 && maxdifference <= 58.000)  //zoom 3_x000D_
  zoomvalue='3';_x000D_
 else_x000D_
  zoomvalue='1';_x000D_
 return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_
}
_x000D_
_x000D_
_x000D_

Can you require two form fields to match with HTML5?

A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.

Unfortunately, you also need to escape the regex, for which no standard function exists.

<form>
    <input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
    <input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
</script>

Spring Boot + JPA : Column name annotation ignored

It seems that

@Column(name="..")

is completely ignored unless there is

spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy

specified, so to me this is a bug.

I spent a few hours trying to figure out why @Column(name="..") was ignored.

SFTP in Python? (platform independent)

You should check out pysftp https://pypi.python.org/pypi/pysftp it depends on paramiko, but wraps most common use cases to just a few lines of code.

import pysftp
import sys

path = './THETARGETDIRECTORY/' + sys.argv[1]    #hard-coded
localpath = sys.argv[1]

host = "THEHOST.com"                    #hard-coded
password = "THEPASSWORD"                #hard-coded
username = "THEUSERNAME"                #hard-coded

with pysftp.Connection(host, username=username, password=password) as sftp:
    sftp.put(localpath, path)

print 'Upload done.'

How to sort an STL vector?

Overload less than operator, then sort. This is an example I found off the web...

class MyData
{
public:
  int m_iData;
  string m_strSomeOtherData;
  bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};

std::sort(myvector.begin(), myvector.end());

Source: here

How do I force Kubernetes to re-pull an image?

My hack during development is to change my Deployment manifest to add the latest tag and always pull like so

image: etoews/my-image:latest
imagePullPolicy: Always

Then I delete the pod manually

kubectl delete pod my-app-3498980157-2zxhd

Because it's a Deployment, Kubernetes will automatically recreate the pod and pull the latest image.

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

Repeat rows of a data.frame

Another way to do this would to first get row indices, append extra copies of the df, and then order by the indices:

df$index = 1:nrow(df)
df = rbind(df,df)
df = df[order(df$index),][,-ncol(df)]

Although the other solutions may be shorter, this method may be more advantageous in certain situations.

Angular ui-grid dynamically calculate height of the grid

following @tony's approach, changed the getTableHeight() function to

<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>

getTableHeight() {
    var offsetValue = 365;
    return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}

the grid would have a dynamic height with regards to window height as well.