Programs & Examples On #Scatterview

pip not working in Python Installation in Windows 10

You should use python and pip in terminal or powershell terminal not in IDLE.

Examples:

pip install psycopg2

or

python -m pip install psycop2

Remember about add python to Windows PATH. I paste examples for Win7. I believe in Win10 this is similar.

Adding Python Path on Windows 7

python 2.7: cannot pip on windows "bash: pip: command not found"

Good luck:)

Edit Crystal report file without Crystal Report software

This may be a long shot, but Crystal Reports for Eclipse is free. I'm not sure if it will work, but if all you need is to edit some static text, you could get that version of CR and get the job done.

is there a tool to create SVG paths from an SVG file?

(In reply to the "has the situation improved?" part of the question):

Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.

If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).

With Hanpuku, you could do something like:

  1. Select the path of interest in Illustrator
  2. Click the "To D3" button
  3. In the script editor, type:

    selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');

  4. Click run

  5. If the change is as expected, click "To Illustrator" to apply the changes to the document

Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).

TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.

How to stop/shut down an elasticsearch node?

Considering you have 3 nodes.

Prepare your cluster

export ES_HOST=localhost:9200

# Disable shard allocation
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}
'

# Stop non-essential indexing and perform a synced flush
curl -X POST "$ES_HOST/_flush/synced"

Stop elasticsearch service in each node

# check nodes
export ES_HOST=localhost:9200
curl -X GET "$ES_HOST/_cat/nodes"

# node 1
systemctl stop elasticsearch.service

# node 2
systemctl stop elasticsearch.service

# node 3
systemctl stop elasticsearch.service

Restarting cluster again

# start
systemctl start elasticsearch.service

# Reenable shard allocation once the node has joined the cluster
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
  "persistent": {
    "cluster.routing.allocation.enable": null
  }
}
'

Tested on Elasticseach 6.5

Source:

  1. https://www.elastic.co/guide/en/elasticsearch/reference/6.5/stopping-elasticsearch.html
  2. https://www.elastic.co/guide/en/elasticsearch/reference/6.5/rolling-upgrades.html

How to access ssis package variables inside script component

This should work:

IDTSVariables100 vars = null;
VariableDispenser.LockForRead("System::TaskName");
VariableDispenser.GetVariables(vars);
string TaskName = vars("System::TaskName").Value.ToString();
vars.Unlock();

Your initial code lacks call of the GetVariables() method.

How to remove a newline from a string in Bash

Using bash:

echo "|${COMMAND/$'\n'}|"

(Note that the control character in this question is a 'newline' (\n), not a carriage return (\r); the latter would have output REBOOT| on a single line.)

Explanation

Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}:

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.

Also uses the $'' ANSI-C quoting construct to specify a newline as $'\n'. Using a newline directly would work as well, though less pretty:

echo "|${COMMAND/
}|"

Full example

#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|

Or, using newlines:

#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|

calculating execution time in c++

This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.

Depending on what problem you're trying to solve, there might be a faster algorithm.

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

return query based on date

Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:

{ $gte: new Date(dateVar).toISOString() }

I'm passing in an ISODate (e.g. 2016-04-22T00:00:00Z) and this works for a .find() query with or without the toISOString function. But when using in an .aggregate() $match query it doesn't like the toISOString function!

How to automatically update an application without ClickOnce?

The most common way would be to put a simple text file (XML/JSON would be better) on your webserver with the last build version. The application will then download this file, check the version and start the updater. A typical file would look like this:

Application Update File (A unique string that will let your application recognize the file type)

version: 1.0.0 (Latest Assembly Version)

download: http://yourserver.com/... (A link to the download version)

redirect: http://yournewserver.com/... (I used this field in case of a change in the server address.)

This would let the client know that they need to be looking at a new address.

You can also add other important details.

How to remove default chrome style for select Input?

Mixin for Less

.appearance (@value: none) {
    -webkit-appearance:     @value;
    -moz-appearance:        @value;
    -ms-appearance:         @value;
    -o-appearance:          @value;
    appearance:             @value;
}

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

If you are getting this error when you run stuffs on automated cluster and you are downloading the stable version of the google chrome every time then you can use the below shell script to download the compatible version of the chrome driver dynamically every time even if the stable version of the chrome gets updated.

%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL** 
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**

I was able to get the compatible version of chrome browser and chrome driver using the above approach when running scheduled job on the databricks environment and it worked like a charm without any issues.

Hope it helps others in one way or other.

How to send email to multiple address using System.Net.Mail

MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);

SmtpClient smtp = new SmtpClient();
smtp.Send(msg);

To is a MailAddressCollection, so you can add how many addresses you need.

If you need a display name, try this:

MailAddress to = new MailAddress(
    String.Format("{0} <{1}>",display_name, address));

What is DOM Event delegation?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

See this link --> http://www.akadia.com/services/dotnet_delegates_and_events.html

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.

Get selected text from a drop-down list (select box) using jQuery

Various ways

1. $("#myselect option:selected").text();

2. $("#myselect :selected").text();

3. $("#myselect").children(":selected").text();

4. $("#myselect").find(":selected").text();

Building executable jar with maven?

Actually, I think that the answer given in the question you mentioned is just wrong (UPDATE - 20101106: someone fixed it, this answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.


It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.

The first one is the JAR of the logmanager module generated during the package phase by jar:jar (because the module has a packaging of type jar). The second one is the assembly generated by assembly:assembly and should contain the classes from the current module and its dependencies (if you used the descriptor jar-with-dependencies).

I get an error when I double-click on the first jar:

Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.

If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <mainClass>com.gorkwobble.logmanager.LogManager</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>

So logmanager-0.1.0.jar is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain com.gorkwobble.logmanager.LogManager (this is what the error is saying, check the content of the jar).

A slightly different error when I double-click the jar-with-dependencies.jar:

Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar

Again, if you configured the assembly plugin as suggested, you have something like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin>

With this setup, logmanager-0.1.0-jar-with-dependencies.jar contains the classes from the current module and its dependencies but, according to the error, its META-INF/MANIFEST.MF doesn't contain a Main-Class entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually not executable, which again is not what you want.


So, my suggestion would be to remove the configuration element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.2</version>
    <!-- nothing here -->
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-4</version>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <archive>
        <manifest>
          <mainClass>org.sample.App</mainClass>
        </manifest>
      </archive>
    </configuration>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Of course, replace org.sample.App with the class you want to have executed. Little bonus, I've bound assembly:single to the package phase so you don't have to run assembly:assembly anymore. Just run mvn install and the assembly will be produced during the standard build.

So, please update your pom.xml with the configuration given above and run mvn clean install. Then, cd into the target directory and try again:

java -jar logmanager-0.1.0-jar-with-dependencies.jar

If you get an error, please update your question with it and post the content of the META-INF/MANIFEST.MF file and the relevant part of your pom.xml (the plugins configuration parts). Also please post the result of:

java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager

to demonstrate it's working fine on the command line (regardless of what eclipse is saying).

EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

What is the use of the JavaScript 'bind' method?

Simple Explanation:

bind() create a new function, a new reference at a function it returns to you.

In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.

You can preconfigure as many parameters as you want.

Simple Example to understand bind:

function calculate(operation) {
  if (operation === 'ADD') {
   alert('The Operation is Addition');
  } else if (operation === 'SUBTRACT') {
   alert('The Operation is Subtraction');
  }
}

addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));

Visual Studio SignTool.exe Not Found

If you do not care about sign your program when you publish, just right click your project then choose Properties --> Signing --> un-check Sign the ClickOnce manifest . I had the same issue when building my program on another machine which did not have ClickOne.

Pythonic way to find maximum value and its index in a list?

I made some big lists. One is a list and one is a numpy array.

import numpy as np
import random
arrayv=np.random.randint(0,10,(100000000,1))
listv=[]
for i in range(0,100000000):
    listv.append(random.randint(0,9))

Using jupyter notebook's %%time function I can compare the speed of various things.

2 seconds:

%%time
listv.index(max(listv))

54.6 seconds:

%%time
listv.index(max(arrayv))

6.71 seconds:

%%time
np.argmax(listv)

103 ms:

%%time
np.argmax(arrayv)

numpy's arrays are crazy fast.

How to bring an activity to foreground (top of stack)?

In general I think this method of activity management is not recommended. The problem with reactivating an activity two Steps down in The Stack is that this activity has likely been killed. My advice into remember the state of your activities and launch them with startActivity ()

I'm sure you've Seen this page but for your convenience this link

Parse string to DateTime in C#

The simple and straightforward answer -->

using System;

namespace DemoApp.App

{
public class TestClassDate
{
    public static DateTime GetDate(string string_date)
    {
        DateTime dateValue;
        if (DateTime.TryParse(string_date, out dateValue))
            Console.WriteLine("Converted '{0}' to {1}.", string_date, dateValue);
        else
            Console.WriteLine("Unable to convert '{0}' to a date.", string_date);
        return dateValue;
    }
    public static void Main()
    {
        string inString = "05/01/2009 06:32:00";
        GetDate(inString);
    }
}
}

/**
 * Output:
 * Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
 * */

How to map an array of objects in React

I think you want to print the name of the person or both the name and email :

const renObjData = this.props.data.map(function(data, idx) {
    return <p key={idx}>{data.name}</p>;
});

or :

const renObjData = this.props.data.map(function(data, idx) {
   return ([
       <p key={idx}>{data.name}</p>,
       <p key={idx}>{data.email}</p>,
   ]);
});

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Just FYI, @ and its numpy equivalents dot and matmul are all equally fast. (Plot created with perfplot, a project of mine.)

enter image description here

Code to reproduce the plot:

import perfplot
import numpy


def setup(n):
    A = numpy.random.rand(n, n)
    x = numpy.random.rand(n)
    return A, x


def at(data):
    A, x = data
    return A @ x


def numpy_dot(data):
    A, x = data
    return numpy.dot(A, x)


def numpy_matmul(data):
    A, x = data
    return numpy.matmul(A, x)


perfplot.show(
    setup=setup,
    kernels=[at, numpy_dot, numpy_matmul],
    n_range=[2 ** k for k in range(15)],
)

How do I search for names with apostrophe in SQL Server?

SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0 

When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.

While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.

Reference SO post for comparative view.

Change value in a cell based on value in another cell

=IF(A2="Y","Male",IF(A2="N","Female",""))

Vagrant stuck connection timeout retrying

The solution I've found is to check the cable connection option in the adapter 1 which is attached to NAT. I really don't know, this is my 4th vagrant box but this is the only one with cable connection option not checked, and upon checking it, it works. NAT cable connection

Is there a command line utility for rendering GitHub flavored Markdown?

Improving upon @barry-stae's solution. Stick this snippet in ~/.bashrc

function mdviewer(){
  pandoc $* | lynx -stdin
}

Then we can quickly view the file from the command-line. Also works nicely over SSH/Telnet sessions.

mdviewer README.md

Last segment of URL in jquery

To get the last segment of your current window:

window.location.href.substr(window.location.href.lastIndexOf('/') +1)

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

Unable to preventDefault inside passive event listener

I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.

.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}

or

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

You can run with PYTHONPATH in project root

PYTHONPATH=. py.test

Or use pip install as editable import

pip install -e .   # install package using setup.py in editable mode

SQL Server JOIN missing NULL values

The only correct answer is not to join columns with null values. This can lead to unwanted behaviour very quickly.

e.g. isnull(b.colId,''): What happens if you have empty strings in your data? The join maybe duplicate rows which I guess is not intended in this case.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

How can you encode a string to Base64 in JavaScript?

I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex and encodeFromHex.

The code:

var Base64 = (function() {
    "use strict";

    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    var _utf8_encode = function (string) {

        var utftext = "", c, n;

        string = string.replace(/\r\n/g,"\n");

        for (n = 0; n < string.length; n++) {

            c = string.charCodeAt(n);

            if (c < 128) {

                utftext += String.fromCharCode(c);

            } else if((c > 127) && (c < 2048)) {

                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);

            } else {

                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);

            }

        }

        return utftext;
    };

    var _utf8_decode = function (utftext) {
        var string = "", i = 0, c = 0, c1 = 0, c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {

                string += String.fromCharCode(c);
                i++;

            } else if((c > 191) && (c < 224)) {

                c1 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
                i += 2;

            } else {

                c1 = utftext.charCodeAt(i+1);
                c2 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
                i += 3;

            }

        }

        return string;
    };

    var _hexEncode = function(input) {
        var output = '', i;

        for(i = 0; i < input.length; i++) {
            output += input.charCodeAt(i).toString(16);
        }

        return output;
    };

    var _hexDecode = function(input) {
        var output = '', i;

        if(input.length % 2 > 0) {
            input = '0' + input;
        }

        for(i = 0; i < input.length; i = i + 2) {
            output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
        }

        return output;
    };

    var encode = function (input) {
        var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;

        input = _utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output += _keyStr.charAt(enc1);
            output += _keyStr.charAt(enc2);
            output += _keyStr.charAt(enc3);
            output += _keyStr.charAt(enc4);

        }

        return output;
    };

    var decode = function (input) {
        var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output += String.fromCharCode(chr1);

            if (enc3 !== 64) {
                output += String.fromCharCode(chr2);
            }
            if (enc4 !== 64) {
                output += String.fromCharCode(chr3);
            }

        }

        return _utf8_decode(output);
    };

    var decodeToHex = function(input) {
        return _hexEncode(decode(input));
    };

    var encodeFromHex = function(input) {
        return encode(_hexDecode(input));
    };

    return {
        'encode': encode,
        'decode': decode,
        'decodeToHex': decodeToHex,
        'encodeFromHex': encodeFromHex
    };
}());

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I think You are using Spring 3.0.5 and you need to use Spring 4.0.* This will resolve your problem. org.springframework.web.bind.annotation.RequestMapping is not available in Spring-web earlier then Spring-web 4.0.*

A field initializer cannot reference the nonstatic field, method, or property

This line:

private dynamic defaultReminder = 
                          reminder.TimeSpanText[TimeSpan.FromMinutes(15)];

You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.

Instead, just use:

private dynamic defaultReminder = TimeSpan.FromMinutes(15);

Alternatively, set up the value in the constructor:

private dynamic defaultReminder;

public Reminders()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 
}

There are more details about this compiler error on MSDN - Compiler Error CS0236.

How do I check whether input string contains any spaces?

A simple answer, along similar lines to the previous ones is:

str.matches(".*\\s.*")
  • The first ".*" says that there can be zero or more instances of any character in front of the space.
  • The "\\s" says it must contain any whitespace character.
  • The last ".*" says there can be zero or more instances of any character after the space.

When you put all those together, this returns true if there are one or more whitespace characters anywhere in the string.

Here is a simple test you can run to benchmark your solution against:

boolean containsWhitespace(String str){
    return str.matches(".*\\s.*");
}

String[] testStrings = {"test", " test", "te st", "test ", "te   st", 
                        " t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
        System.out.println( "Does \"" + eachString + "\" contain whitespace? " + 
                             containsWhitespace(eachString));
}

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Sssuming you have a parent Post entity and a child PostComment as illustrated in the following diagram:

enter image description here

If you call find when you try to set the @ManyToOne post association:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.find(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

Hibernate will execute the following statements:

SELECT p.id AS id1_0_0_,
       p.title AS title2_0_0_
FROM   post p
WHERE p.id = 1
 
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

The SELECT query is useless this time because we don’t need the Post entity to be fetched. We only want to set the underlying post_id Foreign Key column.

Now, if you use getReference instead:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.getReference(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

This time, Hibernate will issue just the INSERT statement:

INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

Unlike find, the getReference only returns an entity Proxy which only has the identifier set. If you access the Proxy, the associated SQL statement will be triggered as long as the EntityManager is still open.

However, in this case, we don’t need to access the entity Proxy. We only want to propagate the Foreign Key to the underlying table record so loading a Proxy is sufficient for this use case.

When loading a Proxy, you need to be aware that a LazyInitializationException can be thrown if you try to access the Proxy reference after the EntityManager is closed.

How do I include a file over 2 directories back?

I recomend to use __DIR__ to specify current php file directory. Check here for the reason.

__DIR__ . /../../index.php

Where is the Keytool application?

If you are working with a Mac... the keytool is part of the Java SDK and can be found in the following location /System/Library/Java/JavaVirtualMachines/[VERSION].jdk/Contents/Home/bin/keytool

js window.open then print()

As most of browsers has been updated, So print and close do not any more as It worked before. So you should add onafterprint event listener in order to close print window.

    var printWindow = window.open('https://stackoverflow.com/');
    printWindow.print();

    //Close window once print is finished
    printWindow.onafterprint = function(){
       printWindow.close()
    };

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

What is the use of hashCode in Java?

hashCode() is a function that takes an object and outputs a numeric value. The hashcode for an object is always the same if the object doesn't change.

Functions like HashMap, HashTable, HashSet, etc. that need to store objects will use a hashCode modulo the size of their internal array to choose in what "memory position" (i.e. array position) to store the object.

There are some cases where collisions may occur (two objects end up with the same hashcode), and that, of course, needs to be solved carefully.

Efficient way to Handle ResultSet in Java

this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.

private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    Map<String, List<Object>> map = new HashMap<>(columns);
    for (int i = 1; i <= columns; ++i) {
        map.put(md.getColumnName(i), new ArrayList<>());
    }
    while (rs.next()) {
        for (int i = 1; i <= columns; ++i) {
            map.get(md.getColumnName(i)).add(rs.getObject(i));
        }
    }

    return map;
}

Java word count program

Not sure if there is a drawback, but this worked for me...

    Scanner input = new Scanner(System.in);
    String userInput = input.nextLine();
    String trimmed = userInput.trim();
    int count = 1;

    for (int i = 0; i < trimmed.length(); i++) {
      if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
        count++;
      }
    }

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

When to use RabbitMQ over Kafka?

Use RabbitMQ when:

  • You don’t have to handle with Bigdata and you prefer a convenient in-built UI for monitoring
  • No need of automatically replicable queues
  • No multi subscribers for the messages- Since unlike Kafka which is a log, RabbitMQ is a queue and messages are removed once consumed and acknowledgment arrived
  • If you have the requirements to use Wildcards and regex for messages
  • If defining message priority is important

In Short: RabbitMQ is good for simple use cases, with low traffic of data, with the benefit of priority queue and flexible routing options. For massive data and high throughput use Kafka.

Conda activate not working?

????

source activate

????

source deactivate

JavaScript: Passing parameters to a callback function

Code from a question with any number of parameters and a callback context:

function SomeFunction(name) {
    this.name = name;
}
function tryMe(param1, param2) {
    console.log(this.name + ":  " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
    console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
    callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");

// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)

Foreign Key to multiple tables

Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Subject varchar(50) NULL
)

CREATE TABLE dbo.Owner
(
    ID int NOT NULL,
    User_ID int NULL,
    Group_ID int NULL,
    {{AdditionalEntity_ID}} int NOT NULL
)

With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).

If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
    Subject varchar(50) NULL
)

With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.

Sorry if I got some SQL wrong, I just threw this together.

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Embed Google Map code in HTML with marker

Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.

It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).

Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Multiple where clauses

    $query=DB::table('users')
        ->whereRaw("users.id BETWEEN 1003 AND 1004")
        ->whereNotIn('users.id', [1005,1006,1007])
        ->whereIn('users.id',  [1008,1009,1010]);
    $query->where(function($query2) use ($value)
    {
        $query2->where('user_type', 2)
            ->orWhere('value', $value);
    });

   if ($user == 'admin'){
        $query->where('users.user_name', $user);
    }

finally getting the result

    $result = $query->get();

Find Active Tab using jQuery and Twitter Bootstrap

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active")

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
  activeTab = e.target;
})

Determine which MySQL configuration file is being used

Using MySQL Workbench it will be shown under "Server Status": enter image description here

Vue.js dynamic images not working

You can try the require function. like this:

<img :src="require(`@/xxx/${name}.png`)" alt class="icon" />

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

When should we use Observer and Observable?

You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.

Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.

The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.

What is the best way to parse html in C#?

I found a project called Fizzler that takes a jQuery/Sizzler approach to selecting HTML elements. It's based on HTML Agility Pack. It's currently in beta and only supports a subset of CSS selectors, but it's pretty damn cool and refreshing to use CSS selectors over nasty XPath.

http://code.google.com/p/fizzler/

How to make CSS width to fill parent?

box-sizing: border-box;
width: 100%;
padding: 5px;

box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.

MDN

Centering a button vertically in table cell, using Twitter Bootstrap

To fix this, i put this class on the webpage

<style>                        
    td.vcenter {
        vertical-align: middle !important;
        text-align: center !important;
    }
</style>

and this in my TemplateField

<asp:TemplateField ItemStyle-CssClass="vcenter">

as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.

Hope it helps

load external URL into modal jquery ui dialog

Modals always load the content into an element on the page, which more often than not is a div. Think of this div as the iframe equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>

</head>

<body>

    <p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
    <div id="dialog"></div>
</body>

<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>

<script type="text/javascript">

$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
    showDialog();
    var titletext=$(this).attr("title");
    var openpage=$(this).attr("href");
    $("#dialog").dialog( "option", "title", titletext );
    $("#dialog").dialog( "option", "resizable", false );
    $("#dialog").dialog( "option", "buttons", { 
        "Close": function() { 
            $(this).dialog("close");
            $(this).dialog("destroy");
        } 
    });
    $("#dialog").load(openpage);
    return false;
});

//modal window end

//Modal Window Initiation start

function showDialog(){
    $("#dialog").dialog({
        height: 400,
        width: 500,
        modal: true 
    }
</script>

</html>

There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.

How to use z-index in svg elements?

its easy to do it:

  1. clone your items
  2. sort cloned items
  3. replace items by cloned

_x000D_
_x000D_
function rebuildElementsOrder( selector, orderAttr, sortFnCallback ) {_x000D_
 let $items = $(selector);_x000D_
 let $cloned = $items.clone();_x000D_
 _x000D_
 $cloned.sort(sortFnCallback != null ? sortFnCallback : function(a,b) {_x000D_
    let i0 = a.getAttribute(orderAttr)?parseInt(a.getAttribute(orderAttr)):0,_x000D_
        i1 = b.getAttribute(orderAttr)?parseInt(b.getAttribute(orderAttr)):0;_x000D_
    return i0 > i1?1:-1;_x000D_
 });_x000D_
_x000D_
        $items.each(function(i, e){_x000D_
            e.replaceWith($cloned[i]);_x000D_
 })_x000D_
}_x000D_
_x000D_
$('use[order]').click(function() {_x000D_
    rebuildElementsOrder('use[order]', 'order');_x000D_
_x000D_
    /* you can use z-index property for inline css declaration_x000D_
    ** getComputedStyle always return "auto" in both Internal and External CSS decl [tested in chrome]_x000D_
    _x000D_
    rebuildElementsOrder( 'use[order]', null, function(a, b) {_x000D_
        let i0 = a.style.zIndex?parseInt(a.style.zIndex):0,_x000D_
        i1 = b.style.zIndex?parseInt(b.style.zIndex):0;_x000D_
    return i0 > i1?1:-1;_x000D_
    });_x000D_
    */_x000D_
});
_x000D_
use[order] {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="keybContainer" viewBox="0 0 150 150" xml:space="preserve">_x000D_
<defs>_x000D_
    <symbol id="sym-cr" preserveAspectRatio="xMidYMid meet" viewBox="0 0 60 60">_x000D_
        <circle cx="30" cy="30" r="30" />_x000D_
        <text x="30" y="30" text-anchor="middle" font-size="0.45em" fill="white">_x000D_
            <tspan dy="0.2em">Click to reorder</tspan>_x000D_
        </text>_x000D_
    </symbol>_x000D_
</defs>_x000D_
    <use order="1" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="0" y="0" width="60" height="60" style="fill: #ff9700; z-index: 1;"></use>_x000D_
    <use order="4" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="50" y="20" width="50" height="50" style="fill: #0D47A1; z-index: 4;"></use>_x000D_
    <use order="5" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="15" y="30" width="50" height="40" style="fill: #9E9E9E; z-index: 5;"></use>_x000D_
    <use order="3" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="25" y="30" width="80" height="80" style="fill: #D1E163; z-index: 3;"></use>_x000D_
    <use order="2" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="30" y="0" width="50" height="70" style="fill: #00BCD4; z-index: 2;"></use>_x000D_
    <use order="0" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="5" y="5" width="100" height="100" style="fill: #E91E63; z-index: 0;"></use>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Most efficient way to concatenate strings in JavaScript?

Three years past since this question was answered but I will provide my answer anyway :)

Actually, accepted answer is not fully correct. Jakub's test uses hardcoded string which allows JS engine to optimize code execution (Google's V8 is really good in this stuff!). But as soon as you use completely random strings (here is JSPerf) then string concatenation will be on a second place.

Priority queue in .Net

Here's my attempt at a .NET heap

public abstract class Heap<T> : IEnumerable<T>
{
    private const int InitialCapacity = 0;
    private const int GrowFactor = 2;
    private const int MinGrow = 1;

    private int _capacity = InitialCapacity;
    private T[] _heap = new T[InitialCapacity];
    private int _tail = 0;

    public int Count { get { return _tail; } }
    public int Capacity { get { return _capacity; } }

    protected Comparer<T> Comparer { get; private set; }
    protected abstract bool Dominates(T x, T y);

    protected Heap() : this(Comparer<T>.Default)
    {
    }

    protected Heap(Comparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)
    {
    }

    protected Heap(IEnumerable<T> collection)
        : this(collection, Comparer<T>.Default)
    {
    }

    protected Heap(IEnumerable<T> collection, Comparer<T> comparer)
    {
        if (collection == null) throw new ArgumentNullException("collection");
        if (comparer == null) throw new ArgumentNullException("comparer");

        Comparer = comparer;

        foreach (var item in collection)
        {
            if (Count == Capacity)
                Grow();

            _heap[_tail++] = item;
        }

        for (int i = Parent(_tail - 1); i >= 0; i--)
            BubbleDown(i);
    }

    public void Add(T item)
    {
        if (Count == Capacity)
            Grow();

        _heap[_tail++] = item;
        BubbleUp(_tail - 1);
    }

    private void BubbleUp(int i)
    {
        if (i == 0 || Dominates(_heap[Parent(i)], _heap[i])) 
            return; //correct domination (or root)

        Swap(i, Parent(i));
        BubbleUp(Parent(i));
    }

    public T GetMin()
    {
        if (Count == 0) throw new InvalidOperationException("Heap is empty");
        return _heap[0];
    }

    public T ExtractDominating()
    {
        if (Count == 0) throw new InvalidOperationException("Heap is empty");
        T ret = _heap[0];
        _tail--;
        Swap(_tail, 0);
        BubbleDown(0);
        return ret;
    }

    private void BubbleDown(int i)
    {
        int dominatingNode = Dominating(i);
        if (dominatingNode == i) return;
        Swap(i, dominatingNode);
        BubbleDown(dominatingNode);
    }

    private int Dominating(int i)
    {
        int dominatingNode = i;
        dominatingNode = GetDominating(YoungChild(i), dominatingNode);
        dominatingNode = GetDominating(OldChild(i), dominatingNode);

        return dominatingNode;
    }

    private int GetDominating(int newNode, int dominatingNode)
    {
        if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))
            return newNode;
        else
            return dominatingNode;
    }

    private void Swap(int i, int j)
    {
        T tmp = _heap[i];
        _heap[i] = _heap[j];
        _heap[j] = tmp;
    }

    private static int Parent(int i)
    {
        return (i + 1)/2 - 1;
    }

    private static int YoungChild(int i)
    {
        return (i + 1)*2 - 1;
    }

    private static int OldChild(int i)
    {
        return YoungChild(i) + 1;
    }

    private void Grow()
    {
        int newCapacity = _capacity*GrowFactor + MinGrow;
        var newHeap = new T[newCapacity];
        Array.Copy(_heap, newHeap, _capacity);
        _heap = newHeap;
        _capacity = newCapacity;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _heap.Take(Count).GetEnumerator();
    }

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

public class MaxHeap<T> : Heap<T>
{
    public MaxHeap()
        : this(Comparer<T>.Default)
    {
    }

    public MaxHeap(Comparer<T> comparer)
        : base(comparer)
    {
    }

    public MaxHeap(IEnumerable<T> collection, Comparer<T> comparer)
        : base(collection, comparer)
    {
    }

    public MaxHeap(IEnumerable<T> collection) : base(collection)
    {
    }

    protected override bool Dominates(T x, T y)
    {
        return Comparer.Compare(x, y) >= 0;
    }
}

public class MinHeap<T> : Heap<T>
{
    public MinHeap()
        : this(Comparer<T>.Default)
    {
    }

    public MinHeap(Comparer<T> comparer)
        : base(comparer)
    {
    }

    public MinHeap(IEnumerable<T> collection) : base(collection)
    {
    }

    public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)
        : base(collection, comparer)
    {
    }

    protected override bool Dominates(T x, T y)
    {
        return Comparer.Compare(x, y) <= 0;
    }
}

Some tests:

[TestClass]
public class HeapTests
{
    [TestMethod]
    public void TestHeapBySorting()
    {
        var minHeap = new MinHeap<int>(new[] {9, 8, 4, 1, 6, 2, 7, 4, 1, 2});
        AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());

        minHeap = new MinHeap<int> { 7, 5, 1, 6, 3, 2, 4, 1, 2, 1, 3, 4, 7 };
        AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());

        var maxHeap = new MaxHeap<int>(new[] {1, 5, 3, 2, 7, 56, 3, 1, 23, 5, 2, 1});
        AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());

        maxHeap = new MaxHeap<int> {2, 6, 1, 3, 56, 1, 4, 7, 8, 23, 4, 5, 7, 34, 1, 4};
        AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());
    }

    private static void AssertHeapSort(Heap<int> heap, IEnumerable<int> expected)
    {
        var sorted = new List<int>();
        while (heap.Count > 0)
            sorted.Add(heap.ExtractDominating());

        Assert.IsTrue(sorted.SequenceEqual(expected));
    }
}

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

Google Maps API v3: InfoWindow not sizing correctly

As of mid-2014 there appears to be an InfoWindow sizing bug in Google Maps v3 that affects multiple browsers.

It has been reported here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5713
(and a demo JSFiddle here)
Please click the star on the issue above to vote for it to be fixed!

From all my testing, it appears to be related to element size rounding errors, as it only occurs at some font-sizes.

Bad workarounds:

Having toyed with most suggestions on this page, the following are NOT good solutions:

  • overflow: hidden (can potentially cut off content)
  • white-space: nowrap (can potentially cut off content)
  • Passing a jQuery object or DOM nodes (content potentially overflows outside the InfoWindow)
  • Setting the InfoWindow content after it is opened (on its own, does not help)
  • Changing font away from Roboto (the issue can occur with any font)

One possible workaround is giving your InfoWindow a fixed width (such as those who've suggested setting max-width and min-width), however when you have lots of markers and the amount of content varies fluctuates, this is not ideal. It's also bad for mobile/responsive designs.

A reasonable workaround:

So until Google fix this, I've had to build a workaround. After about 12+ hours of testing and debugging I came up with the following:

This does not have the same drawbacks as other suggestions.

  • Content should never be clipped (unless you have large images that exceed the width of the InfoWindow).
  • Vertical scrollbars are added, but only when necessary.
  • No content should overflow outside of the InfoWindow
  • In most cases the InfoWindow is sized automatically to fit the content (not a fixed size)
  • Should be suitable for mobiles and responsive layouts
  • Margins, padding, fonts should all work OK

Downsides:

  • My version requires jQuery, but it could probably be reworked to be pure JS
  • It creates 20px of padding on the right of the content to make room for the scrollbar in case it is needed. You could skip this if you prefer, or do some more checking to only add padding when necessary.
  • It's rather hacky, but without editing Google's javascript, it's possibly the only way.

View Code on Github

Please submit improvements and corrections as you find them.

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

Execution time of C program

(All answers here are lacking, if your sysadmin changes the systemtime, or your timezone has differing winter- and sommer-times. Therefore...)

On linux use: clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable); It's not affected if the system-admin changes the time, or you live in a country with winter-time different from summer-time, etc.

#include <stdio.h>
#include <time.h>

#include <unistd.h> /* for sleep() */

int main() {
    struct timespec begin, end;
    clock_gettime(CLOCK_MONOTONIC_RAW, &begin);

    sleep(1);      // waste some time

    clock_gettime(CLOCK_MONOTONIC_RAW, &end);

    printf ("Total time = %f seconds\n",
            (end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
            (end.tv_sec  - begin.tv_sec));

}

man clock_gettime states:

CLOCK_MONOTONIC
              Clock  that  cannot  be set and represents monotonic time since some unspecified starting point.  This clock is not affected by discontinuous jumps in the system time
              (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.

APK signing error : Failed to read key from keystore

It could be any one of the parameter, not just the file name or alias - for me it was the Key Password.

Calculate percentage Javascript

It seems working :

HTML :

 <input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

JavaScript :

    $(function(){

    $('#pointspossible').on('input', function() {
      calculate();
    });
    $('#pointsgiven').on('input', function() {
     calculate();
    });
    function calculate(){
        var pPos = parseInt($('#pointspossible').val()); 
        var pEarned = parseInt($('#pointsgiven').val());
        var perc="";
        if(isNaN(pPos) || isNaN(pEarned)){
            perc=" ";
           }else{
           perc = ((pEarned/pPos) * 100).toFixed(3);
           }

        $('#pointsperc').val(perc);
    }

});

Demo : http://jsfiddle.net/vikashvverma/1khs8sj7/1/

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

ERROR: npm ERR! Unexpected end of JSON input while parsing near '...ore-js":"3.0.0-beta.1

This occurs when installing the expo CLI globally, This works for me!

npm cache clean --force

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you want to add the value on aspx page , Just enter <a href='your link'>clickhere</a>

If you are trying to achieve it via Code-Behind., Make use of the Hyperlink control

HyperLink hl1 = new HyperLink();
hl1.text="Click Here";
hl1.NavigateUrl="http://www.stackoverflow.com";

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

Copy output of a JavaScript variable to the clipboard

When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject

How do I prompt a user for confirmation in bash script?

Here's the function I use :

function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}

And an example using it:

if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
      "no" == $(ask_yes_or_no "Are you *really* sure?") ]]
then
    echo "Skipped."
    exit 0
fi

# Do something really dangerous...
  • The output is always "yes" or "no"
  • It's "no" by default
  • Everything except "y" or "yes" returns "no", so it's pretty safe for a dangerous bash script
  • And it's case insensitive, "Y", "Yes", or "YES" work as "yes".

I hope you like it,
Cheers!

Xcode 10: A valid provisioning profile for this executable was not found

After I tired most of solution, I found what its make it work without any issue for me, Its resolved by go to developer.apple.com then account then Certificates, identifiers & profiles and I click on All link under Devices and then add a new device.

then you need to set device name, and uuid, and after save it. Go to xcode and clean cache, build, and all its work fine.

Note 1: make sure your team is set truth.

Note 2: You can get uuid by connect device to your mac device, and click on iTunes, and press on security label, you will see UUID.

Which This Answer its helpful too.

How to specify the download location with wget?

"-P" is the right option, please read on for more related information:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -P prefix
   --directory-prefix=prefix
       Set directory prefix to prefix.  The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree.  The default is . (the current directory).

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

Initialization of an ArrayList in one line

Like Tom said:

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

But since you complained of wanting an ArrayList, you should firstly know that ArrayList is a subclass of List and you could simply add this line:

ArrayList<String> myPlaces = new ArrayList(places);

Although, that might make you complain of 'performance'.

In that case it doesn't make sense to me, why, since your list is predefined it wasn't defined as an array (since the size is known at time of initialisation). And if that's an option for you:

String[] places = {"Buenos Aires", "Córdoba", "La Plata"};

In case you don't care of the minor performance differences then you can also copy an array to an ArrayList very simply:

ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));

Okay, but in future you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list which will never change during run-time, then it's fitting to use an enum set, which would require re-compilation if the list needed to be changed in the future.

enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}

would become:

enum Places {
    BUENOS_AIRES("Buenos Aires",123),
    CORDOBA("Córdoba",456),
    LA_PLATA("La Plata",789);

    String name;
    int code;
    Places(String name, int code) {
      this.name=name;
      this.code=code;
    }
}

Enum's have a static values method that returns an array containing all of the values of the enum in the order they are declared, e.g.:

for (Places p:Places.values()) {
    System.out.printf("The place %s has code %d%n",
                  p.name, p.code);
}

In that case I guess you wouldn't need your ArrayList.

P.S. Randyaa demonstrated another nice way using the static utility method Collections.addAll.

How to uninstall a windows service and delete its files without rebooting

(so Windows releases it's hold on the file)

Instead, do Ctrl+Alt+Del right after the Stop of the service and kill the .exe of the service. Than, you can uninstall the service without rebooting. This happened to me in the past and it solves the part that you need to reboot.

The request failed or the service did not respond in a timely fashion?

Had the same problem, I fixed it.

  1. Open SQL Server Configuration manager
  2. Click on the SQL Server Services (on the left)
  3. Double-click on the SQL Server Instance that I wanted to start
  4. Select the Built-in account radio button in the Log On tab and choose Local system from the dropdown menu
  5. Click apply at the bottom, then right click the instance and select Start

Get the height and width of the browser viewport without scrollbars using jquery?

$(window).height();
$(window).width();

More info

Using jQuery is not essential for getting those values, however. Use

document.documentElement.clientHeight;
document.documentElement.clientWidth;

to get sizes excluding scrollbars, or

window.innerHeight;
window.innerWidth;

to get the whole viewport, including scrollbars.

document.documentElement.clientHeight <= window.innerHeight;  // is always true

Reading RFID with Android phones

You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):

1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.

2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.

Right now, I'm working in the second option but with iPhone.

Purpose of Unions in C and C++

In the C language as it was documented in 1974, all structure members shared a common namespace, and the meaning of "ptr->member" was defined as adding the member's displacement to "ptr" and accessing the resulting address using the member's type. This design made it possible to use the same ptr with member names taken from different structure definitions but with the same offset; programmers used that ability for a variety of purposes.

When structure members were assigned their own namespaces, it became impossible to declare two structure members with the same displacement. Adding unions to the language made it possible to achieve the same semantics that had been available in earlier versions of the language (though the inability to have names exported to an enclosing context may have still necessitated using a find/replace to replace foo->member into foo->type1.member). What was important was not so much that the people who added unions have any particular target usage in mind, but rather that they provide a means by which programmers who had relied upon the earlier semantics, for whatever purpose, should still be able to achieve the same semantics even if they had to use a different syntax to do it.

How can I check if PostgreSQL is installed or not via Linux script?

What about trying the which command?

If you were to run which psql and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:

> which psql
>

But if Postgres is installed you'll get a response with the path to the location of the Postgres install:

> which psql
/opt/boxen/homebrew/bin/psql

Looking at man which there also appears to be an option that could help you out:

-s      No output, just return 0 if any of the executables are found, or
        1 if none are found.

So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql and use the return value to determine if Postgres is installed. From there you can print that result however you like.

I do have postgres installed on my machine so I run the following

> which -s psql
> echo $?
0

which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.

Here's the information about using echo $?

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here

How do I install Maven with Yum?

For future reference and for simplicity sake for the lazy people out there that don't want much explanations but just run things and make it work asap:

1) sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

2) sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

3) sudo yum install -y apache-maven

4) mvn --version

Hope you enjoyed this copy & paste session.

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

For those who need the input file to open directly the camera, you just have to declare capture parameter to the input file, like this :

<input type="file" accept="image/*" capture>

How to limit text width

<style>
     p{
         width:     70%
         word-wrap: break-word;
     }
</style>

This wasn't working in my case. It worked fine after adding following style.

<style>
     p{
        width:     70%
        word-break: break-all;
     }
</style>

Using {% url ??? %} in django templates

The selected answer is out of date and no others worked for me (Django 1.6 and [apparantly] no registered namespace.)

For Django 1.5 and later (from the docs)

Warning Don’t forget to put quotes around the function path or pattern name!

With a named URL you could do:

(r'^login/', login_view, name='login'),
...
<a href="{% url 'login' %}">logout</a>

Just as easy if the view takes another parameter

def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>

How to exclude a directory from ant fileset, based on directories contents

There is actually an example for this type of issue in the Ant documentation. It makes use of Selectors (mentioned above) and mappers. See last example in http://ant.apache.org/manual/Types/dirset.html :

<dirset id="dirset" dir="${workingdir}">
   <present targetdir="${workingdir}">
        <mapper type="glob" from="*" to="*/${markerfile}" />
   </present>
</dirset>

Selects all directories somewhere under ${workingdir} which contain a ${markerfile}.

What is the best collation to use for MySQL with PHP?

It is best to use character set utf8mb4 with the collation utf8mb4_unicode_ci.

The character set, utf8, only supports a small amount of UTF-8 code points, about 6% of possible characters. utf8 only supports the Basic Multilingual Plane (BMP). There 16 other planes. Each plane contains 65,536 characters. utf8mb4 supports all 17 planes.

MySQL will truncate 4 byte UTF-8 characters resulting in corrupted data.

The utf8mb4 character set was introduced in MySQL 5.5.3 on 2010-03-24.

Some of the required changes to use the new character set are not trivial:

  • Changes may need to be made in your application database adapter.
  • Changes will need to be made to my.cnf, including setting the character set, the collation and switching innodb_file_format to Barracuda
  • SQL CREATE statements may need to include: ROW_FORMAT=DYNAMIC
    • DYNAMIC is required for indexes on VARCHAR(192) and larger.

NOTE: Switching to Barracuda from Antelope, may require restarting the MySQL service more than once. innodb_file_format_max does not change until after the MySQL service has been restarted to: innodb_file_format = barracuda.

MySQL uses the old Antelope InnoDB file format. Barracuda supports dynamic row formats, which you will need if you do not want to hit the SQL errors for creating indexes and keys after you switch to the charset: utf8mb4

  • #1709 - Index column size too large. The maximum column size is 767 bytes.
  • #1071 - Specified key was too long; max key length is 767 bytes

The following scenario has been tested on MySQL 5.6.17: By default, MySQL is configured like this:

SHOW VARIABLES;

innodb_large_prefix = OFF
innodb_file_format = Antelope

Stop your MySQL service and add the options to your existing my.cnf:

[client]
default-character-set= utf8mb4

[mysqld]
explicit_defaults_for_timestamp = true
innodb_large_prefix = true
innodb_file_format = barracuda
innodb_file_format_max = barracuda
innodb_file_per_table = true

# Character collation
character_set_server=utf8mb4
collation_server=utf8mb4_unicode_ci

Example SQL CREATE statement:

CREATE TABLE Contacts (
 id INT AUTO_INCREMENT NOT NULL,
 ownerId INT DEFAULT NULL,
 created timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
 modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 contact VARCHAR(640) NOT NULL,
 prefix VARCHAR(128) NOT NULL,
 first VARCHAR(128) NOT NULL,
 middle VARCHAR(128) NOT NULL,
 last VARCHAR(128) NOT NULL,
 suffix VARCHAR(128) NOT NULL,
 notes MEDIUMTEXT NOT NULL,
 INDEX IDX_CA367725E05EFD25 (ownerId),
 INDEX created (created),
 INDEX modified_idx (modified),
 INDEX contact_idx (contact),
 PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT=DYNAMIC;
  • You can see error #1709 generated for INDEX contact_idx (contact) if ROW_FORMAT=DYNAMIC is removed from the CREATE statement.

NOTE: Changing the index to limit to the first 128 characters on contacteliminates the requirement for using Barracuda with ROW_FORMAT=DYNAMIC

INDEX contact_idx (contact(128)),

Also note: when it says the size of the field is VARCHAR(128), that is not 128 bytes. You can use have 128, 4 byte characters or 128, 1 byte characters.

This INSERT statement should contain the 4 byte 'poo' character in the 2 row:

INSERT INTO `Contacts` (`id`, `ownerId`, `created`, `modified`, `contact`, `prefix`, `first`, `middle`, `last`, `suffix`, `notes`) VALUES
(1, NULL, '0000-00-00 00:00:00', '2014-08-25 03:00:36', '1234567890', '12345678901234567890', '1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678', '', ''),
(2, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '', '', ''),
(3, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '123', '', '');

You can see the amount of space used by the last column:

mysql> SELECT BIT_LENGTH(`last`), CHAR_LENGTH(`last`) FROM `Contacts`;
+--------------------+---------------------+
| BIT_LENGTH(`last`) | CHAR_LENGTH(`last`) |
+--------------------+---------------------+
|               1024 |                 128 | -- All characters are ASCII
|               4096 |                 128 | -- All characters are 4 bytes
|               4024 |                 128 | -- 3 characters are ASCII, 125 are 4 bytes
+--------------------+---------------------+

In your database adapter, you may want to set the charset and collation for your connection:

SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'

In PHP, this would be set for: \PDO::MYSQL_ATTR_INIT_COMMAND

References:

How to save to local storage using Flutter?

You can use shared preferences from flutter's official plugins. https://github.com/flutter/plugins/tree/master/packages/shared_preferences

It uses Shared Preferences for Android, NSUserDefaults for iOS.

How can I symlink a file in Linux?

To create a new symlink (will fail if symlink exists already):

ln -s /path/to/file /path/to/symlink

To create or update a symlink:

ln -sf /path/to/file /path/to/symlink

How do I navigate to a parent route from a child route?

My solution is:

const urlSplit = this._router.url.split('/');
this._router.navigate([urlSplit.splice(0, urlSplit.length - 1).join('/')], { relativeTo: this._route.parent });

And the Router injection:

private readonly _router: Router

Disable native datepicker in Google Chrome

If you have misused <input type="date" /> you can probably use:

$('input[type="date"]').attr('type','text');

after they have loaded to turn them into text inputs. You'll need to attach your custom datepicker first:

$('input[type="date"]').datepicker().attr('type','text');

Or you could give them a class:

$('input[type="date"]').addClass('date').attr('type','text');

How to change line color in EditText

drawable/bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item
        android:left="-2dp"
        android:right="-2dp"
        android:top="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@color/colorDivider" />
        </shape>
    </item>
</layer-list>

Set to EditText

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_edittext"/>

How to populate/instantiate a C# array with a single value?

For large arrays or arrays that will be variable sized you should probably use:

Enumerable.Repeat(true, 1000000).ToArray();

For small array you can use the collection initialization syntax in C# 3:

bool[] vals = new bool[]{ false, false, false, false, false, false, false };

The benefit of the collection initialization syntax, is that you don't have to use the same value in each slot and you can use expressions or functions to initialize a slot. Also, I think you avoid the cost of initializing the array slot to the default value. So, for example:

bool[] vals = new bool[]{ false, true, false, !(a ||b) && c, SomeBoolMethod() };

Remove Duplicate objects from JSON Array

Reviving an old question, but I wanted to post an iteration on @adeneo's answer. That answer is completely general, but for this use case it could be more efficient (it's slow on my machine with an array of a few thousand objects). If you know the specific properties of the objects you need to compare, just compare them directly:

var sl = standardsList;
var out = [];

for (var i = 0, l = sl.length; i < l; i++) {
    var unique = true;
    for (var j = 0, k = out.length; j < k; j++) {
        if ((sl[i].Grade === out[j].Grade) && (sl[i].Domain === out[j].Domain)) {
            unique = false;
        }
    }
    if (unique) {
        out.push(sl[i]);
    }
}

console.log(sl.length); // 10
console.log(out.length); // 5

How do I horizontally center a span element inside a div

One option is to give the <a> a display of inline-block and then apply text-align: center; on the containing block (remove the float as well):

div { 
    background: red;
    overflow: hidden; 
    text-align: center;
}

span a {
    background: #222;
    color: #fff;
    display: inline-block;
    /* float:left;  remove */
    margin: 10px 10px 0 0;
    padding: 5px 10px
}

http://jsfiddle.net/Adrift/cePe3/

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

How to override toString() properly in Java?

Java toString() method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

Output without toString() method

class Student{  
 int id;  
 String name;  
 String address;  

 Student(int id, String name, String address){  
 this.id=id;  
 this.name=name;  
 this.address=address;  
 }  

 public static void main(String args[]){  
   Student s1=new Student(100,”Joe”,”success”);  
   Student s2=new Student(50,”Jeff”,”fail”);  

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
}  

Output:Student@2kaa9dc
       Student@4bbc148

You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:

Example#2

Output with overriding toString() method

class Student{  
 int id;  
 String name;  
 String address;  

 Student(int id, String name, String address){  
 this.id=id;  
 this.name=name;  
 this.address=address;  
 }  

//overriding the toString() method  
public String toString(){ 
  return id+" "+name+" "+address;  
 }  
 public static void main(String args[]){  
   Student s1=new Student(100,”Joe”,”success”);  
   Student s2=new Student(50,”Jeff”,”fail”);  

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
} 

Output:100 Joe success
       50 Jeff fail

Note that toString() mostly is related to the concept of polymorphism in Java. In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

Java web start - Unable to load resource

Include your IP address in your host file (C:\Windows\System32\drivers\etc\host) for the respective server:

Sample Entry:

10.100.101.102 server1.us.vijay.com Vijay's Server

How can I have grep not print out 'No such file or directory' errors?

Have you tried the -0 option in xargs? Something like this:

ls -r1 | xargs -0 grep 'some text'

Regular expression to get a string between two strings in Javascript

You can use destructuring to only focus on the part of your interest.

So you can do:

_x000D_
_x000D_
let str = "My cow always gives milk";

let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];

console.log(result);
_x000D_
_x000D_
_x000D_

In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || [] may be interesting if you are not sure there will be a match at all. In that case match would return null which cannot be destructured, and so we return [] instead in that case, and then result will be null.

The additional \b ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+ is needed to avoid that the match includes some outer spacing.

How to show current user name in a cell?

Based on the instructions at the link below, do the following.

In VBA insert a new module and paste in this code:

Public Function UserName()
    UserName = Environ$("UserName")
End Function

Call the function using the formula:

=Username()

Based on instructions at:

https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f

java howto ArrayList push, pop, shift, and unshift

Great Answer by Jon.

I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<String> animals = new ArrayList<>();

        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add() -> push(): Add items to the end of an array
        animals.add("Elephant");
        System.out.println(animals);  // [Lion, Tiger, Cat, Dog, Elephant]

        // remove() -> pop(): Remove an item from the end of an array
        animals.remove(animals.size() - 1);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add(0,"xyz") -> unshift(): Add items to the beginning of an array
        animals.add(0, "Penguin");
        System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]

        // remove(0) -> shift(): Remove an item from the beginning of an array
        animals.remove(0);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

    }

}

How can I pass a parameter to a setTimeout() callback?

After doing some research and testing, the only correct implementation is:

setTimeout(yourFunctionReference, 4000, param1, param2, paramN);

setTimeout will pass all extra parameters to your function so they can be processed there.

The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.

How to add items into a numpy array

If x is just a single scalar value, you could try something like this to ensure the correct shape of the array that is being appended/concatenated to the rightmost column of a:

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10
b = np.hstack((a,x*np.ones((a.shape[0],1))))

returns b as:

array([[  1.,   3.,   4.,  10.],
       [  1.,   2.,   3.,  10.],
       [  1.,   2.,   1.,  10.]])

Open a new tab in the background?

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

Get the value for a listbox item by index

Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.

Items of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method.

GetItemValue Extension Method

We can create GetItemValue Extension Method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.

This method is applicable on ComboBox and CheckedListBox too.

How to call C++ function from C?

You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

React: trigger onChange if input value is changing by state?

I had a similar need and end up using componentDidMount(), that one is called long after component class constructor (where you can initialize state from props - as an exmple using redux )

Inside componentDidMount you can then invoke your handleChange method for some UI animation or perform any kind of component properties updates required.

As an example I had an issue updating an input checkbox type programatically, that's why I end up using this code, as onChange handler was not firing at component load:

   componentDidMount() {

    // Update checked 
    const checkbox = document.querySelector('[type="checkbox"]');

    if (checkbox) 
      checkbox.checked = this.state.isChecked;
  }

State was first updated in component class constructor and then utilized to update some input component behavior

Pandas: drop a level from a multi-level column index?

As of Pandas 0.24.0, we can now use DataFrame.droplevel():

cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
df = pd.DataFrame([[1,2], [3,4]], columns=cols)

df.droplevel(0, axis=1) 

#   b  c
#0  1  2
#1  3  4

This is very useful if you want to keep your DataFrame method-chain rolling.

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

How to connect HTML Divs with Lines?

It's kind of a pain to position, but you could use 1px wide divs as lines and position and rotate them appropriately.

http://jsfiddle.net/sbaBG/1

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>

<div class="line" id="line1"></div>
<div class="line" id="line2"></div>
.box {
    border: 1px solid black;
    background-color: #ccc;
    width: 100px;
    height: 100px;
    position: absolute;
}
.line {
    width: 1px;
    height: 100px;
    background-color: black;
    position: absolute;
}
#box1 {
    top: 0;
    left: 0;
}
#box2 {
    top: 200px;
    left: 0;
}
#box3 {
    top: 250px;
    left: 200px;
}
#line1 {
    top: 100px;
    left: 50px;
}
#line2 {
    top: 220px;
    left: 150px;
    height: 115px;

    transform: rotate(120deg);
    -webkit-transform: rotate(120deg);
    -ms-transform: rotate(120deg);
}

How to avoid "RuntimeError: dictionary changed size during iteration" error?

Python 3 does not allow deletion while iterating (using for loop above) dictionary. There are various alternatives to do; one simple way is the to change following line

for i in x.keys():

With

for i in list(x)

How to enable C# 6.0 feature in Visual Studio 2013?

It worth mentioning that the build time will be increased for VS 2015 users after:

Install-Package Microsoft.Net.Compilers

Those who are using VS 2015 and have to keep this package in their projects can fix increased build time.

Edit file packages\Microsoft.Net.Compilers.1.2.2\build\Microsoft.Net.Compilers.props and clean it up. The file should look like:

<Project DefaultTargets="Build" 
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

Doing so forces a project to be built as it was before adding Microsoft.Net.Compilers package

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

I just want to add my solution:

I use german umlauts like ö, ü, ä and got the same error.
@Jarek Zmudzinski just told you how it works, but here is mine:

Add this code to the top of your Controller: # encoding: UTF-8
(for example to use flash message with umlauts)

example of my Controller:

# encoding: UTF-8
class UserController < ApplicationController

Now you can use ö, ä ,ü, ß, "", etc.

Bootstrap Alert Auto Close

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").alert('close');
});

Where fadeTo parameters are fadeTo(speed, opacity)

How can I "reset" an Arduino board?

After scratching my head about this problem, here is a very simple solution that works anytime:

  • Unplug your USB cable
  • Go in Device Manager
  • Click on Ports (COM & LPT)
  • Right click on Arduino....(COMx)
  • Properties
  • Port Settings
  • Put Flow Control to HARDWARE
  • Create an empty sketch (Optional)
  • Connect the USB cable
  • Upload (Ctrl + U)

// Empty sketch to fix the upload problem
// Created by Eric Phenix
// Nov 2014

void setup()
{
}

// The loop routine runs over and over again forever:
void loop()
{
    delay(1000);
}

Et voila!

Clear the cache in JavaScript

If you are using php can do:

 <script src="js/myscript.js?rev=<?php echo time();?>"
    type="text/javascript"></script>

What's the difference between Unicode and UTF-8?

It's weird. Unicode is a standard, not an encoding. As it is possible to specify the endianness I guess it's effectively UTF-16 or maybe 32.

Where does this menu provide from?

When and where to use GetType() or typeof()?

You may find it easier to use the is keyword:

if (mycontrol is TextBox)

Git status shows files as changed even though contents are the same

After copying my local repository and working copy to another folder (on Windows by the way), I had four files that kept showing up as changed and tried every suggestion listed in the other answers. In the end what fixed it for me was deleting the local branch and downloading it again from the remote. In my case I guess it had something to do with copying a local repository rather than cloning.

How do I convert dmesg timestamp to custom date format?

In recent versions of dmesg, you can just call dmesg -T.

Call one constructor from another

Here is an example that calls another constructor, then checks on the property it has set.

    public SomeClass(int i)
    {
        I = i;
    }

    public SomeClass(SomeOtherClass soc)
        : this(soc.J)
    {
        if (I==0)
        {
            I = DoSomethingHere();
        }
    }

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

Specify foreign key for the details tables which references to the primary key of master and set Delete rule = Cascade .

Now when u delete a record from the master table all other details table record based on the deleting rows primary key value, will be deleted automatically.

So in that case a single delete query of master table can delete master tables data as well as child tables data.

Forking vs. Branching in GitHub

You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.

Forking is nothing more than a clone on the GitHub server side:

  • without the possibility to directly push back
  • with fork queue feature added to manage the merge request

You keep a fork in sync with the original project by:

  • adding the original project as a remote
  • fetching regularly from that original project
  • rebase your current development on top of the branch of interest you got updated from that fetch.

The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.

The goal is really to allow collaboration even though direct participation is not always possible.


The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.

fork on GitHub

The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream (rebase your work on top of new commits from upstream), and then git push --force origin, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.

See also:

How to correctly dismiss a DialogFragment?

I gave an upvote to Terel's answer. I just wanted to post this for any Kotlin users:

supportFragmentManager.findFragmentByTag(TAG_DIALOG)?.let {
    (it as DialogFragment).dismiss()
}

Is there an onSelect event or equivalent for HTML <select>?

I know this question is very old now, but for anyone still running into this problem, I have achieved this with my own website by adding an onInput event to my option tag, then in that called function, retrieving the value of that option input.

_x000D_
_x000D_
<select id='dropdown' onInput='myFunction()'>
  <option value='1'>1</option>
  <option value='2'>2</option>
</select>

<p>Output: </p> 
<span id='output'></span>

<script type='text/javascript'>
function myFunction() {
 var optionValue = document.getElementById("dropdown").value;
 document.getElementById("output").innerHTML = optionValue;
}
</script>
_x000D_
_x000D_
_x000D_

Python - Check If Word Is In A String

if 'seek' in 'those who seek shall find':
    print('Success!')

but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

Nodemailer with Gmail and NodeJS

Just attend those: 1- Gmail authentication for allow low level emails does not accept before you restart your client browser 2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like below

const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');



routes.get('/test', (req, res) => {
  res.status(200).json({ message: 'test!' });
});

routes.post('/Email', (req, res) =>{

    var smtpTransport = nodemailer.createTransport({
        host: "smtp.gmail.com",
        secureConnection: false,
        port: 587,
        requiresAuth: true,
        domains: ["gmail.com", "googlemail.com"],
        auth: {
            user: "your gmail account", 
            pass: "your password*"
        }
});  

  var mailOptions = {
      from: '[email protected]',
      to:'[email protected]',
      subject: req.body.subject,
      //text: req.body.content,
      html: '<p>'+req.body.content+' </p>'
  };

  smtpTransport.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log('Error while sending mail: ' + error);
    } else {
        console.log('Message sent: %s', info.messageId);
    }
    smtpTransport.close();
});  

})

module.exports = routes;

Detect the Enter key in a text input field

Try this to detect the Enter key pressed in a textbox.

$(document).on("keypress", "input", function(e){
    if(e.which == 13){
        alert("Enter key pressed");
    }
});

DEMO

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

To do the same I did following in terminal-

$ wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
$ sudo tar -xzf postman.tar.gz -C /opt
$ rm postman.tar.gz
$ sudo ln -s /opt/Postman/Postman /usr/bin/postman
  1. Now open file system, move to /usr/bin/ and search form "Postman"
  2. There was a sh file with name 'Postman'
  3. Double clicked on it which opened postman.
  4. Locked icon to launcher on right clicking its icon for further use.

Hope will hell others too.

How to check if a folder exists

To check if a directory exists with the new IO:

if (Files.isDirectory(Paths.get("directory"))) {
  ...
}

isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

See: documentation.

Extension methods must be defined in a non-generic static class

Change it to

public static class LinqHelper

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

JSON datetime between Python and JavaScript

Using json, you can subclass JSONEncoder and override the default() method to provide your own custom serializers:

import json
import datetime

class DateTimeJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        else:
            return super(DateTimeJSONEncoder, self).default(obj)

Then, you can call it like this:

>>> DateTimeJSONEncoder().encode([datetime.datetime.now()])
'["2010-06-15T14:42:28"]'

Printing an array in C++?

May I suggest using the fish bone operator?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(Can you spot it?)

Is there a way to collapse all code blocks in Eclipse?

In addition to the hotkey, if you right click in the gutter where you see the +/-, there is a context menu item 'Folding.' Opening the submenu associated with this, you can see a 'Collapse All' item. this will also do what you wish.

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

<div> cannot appear as a descendant of <p>

Your component might be rendered inside another component (such as a <Typography> ... </Typography>). Therefore, it will load your component inside a <p> .. </p> which is not allowed.

Fix: Remove <Typography>...</Typography> because this is only used for plain text inside a <p>...</p> or any other text element such as headings.

Where are SQL Server connection attempts logged?

You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".

Make sure to restart the SQL Server service.

Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.

How to assign bean's property an Enum value in Spring config file?

Spring-integration example, routing based on a an Enum field:

public class BookOrder {

    public enum OrderType { DELIVERY, PICKUP } //enum
    public BookOrder(..., OrderType orderType) //orderType
    ...

config:

<router expression="payload.orderType" input-channel="processOrder">
    <mapping value="DELIVERY" channel="delivery"/>
    <mapping value="PICKUP" channel="pickup"/>
</router>

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

Using prepared statements with JDBCTemplate

I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):

private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
    if (updateSales == null) {
        updateSales = con.prepareStatement(
            "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    }
    updateSales.setInt(1, sales);
    updateSales.setString(2, cof_name);
    updateSales.executeUpdate();
}

At that point, it is then just a matter of calling:

updateSales(75, "Colombian");

Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...

Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

Https Connection Android

If you are using a StartSSL or Thawte certificate, it will fail for Froyo and older versions. You can use a newer version's CAcert repository instead of trusting every certificate.

How to print in C

To print those numbers in C do the following:

printf("%d", addNumbers(a,b));

What is the single most influential book every programmer should read?

Inside the C++ Object Model by Stan Lippman. It made C++ finally "click" for me, before it was all "magic". This book gave me a different frame of mind when approaching a new programming language.

Randomize a List<T>

private List<GameObject> ShuffleList(List<GameObject> ActualList) {


    List<GameObject> newList = ActualList;
    List<GameObject> outList = new List<GameObject>();

    int count = newList.Count;

    while (newList.Count > 0) {

        int rando = Random.Range(0, newList.Count);

        outList.Add(newList[rando]);

        newList.RemoveAt(rando);

     

    }

    return (outList);

}

usage :

List<GameObject> GetShuffle = ShuffleList(ActualList);

Problems when trying to load a package in R due to rJava

I had a similar issue. It is caused due the dependent package 'rJava'. This problem can be overcome by re-directing the R to use a different JAVA_HOME.

if(Sys.getenv("JAVA_HOME")!=""){
    Sys.setenv(JAVA_HOME="")
}
library(rJava)

This worked for me.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to convert current date to epoch timestamp?

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

So, you need to do below

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

How to uninstall with msiexec using product id guid without .msi file present

There's no reason for the {} command not to work. The semi-obvious questions are:

  1. You are sure that the product is actually installed! There's something in ARP/Programs&Features.

  2. The original install is in fact visible in the current context. It looks as if it might have been a per-user install, and if you are logged in as somebody else now then it won't know about it - you'd need to log in under the same account as the original install.

  3. If the \windows\installer directory was damaged the cached file would be missing, and that's used to do the uninstall.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

When having a column defined with "NOT NULL DEFAULT CURRENT_TIMESTAMP," inserted records will always get set with UTC/GMT time.

Here's what I did to avoid having to include the time in my INSERT/UPDATE statements:

--Create a table having a CURRENT_TIMESTAMP:
CREATE TABLE FOOBAR (
    RECORD_NO INTEGER NOT NULL,
    TO_STORE INTEGER,
    UPC CHAR(30),
    QTY DECIMAL(15,4),
    EID CHAR(16),
    RECORD_TIME NOT NULL DEFAULT CURRENT_TIMESTAMP)

--Create before update and after insert triggers:
CREATE TRIGGER UPDATE_FOOBAR BEFORE UPDATE ON FOOBAR
    BEGIN
       UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
       WHERE rowid = new.rowid;
    END

CREATE TRIGGER INSERT_FOOBAR AFTER INSERT ON FOOBAR
    BEGIN
       UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
       WHERE rowid = new.rowid;
    END

Test to see if it works...

--INSERT a couple records into the table:
INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
    VALUES (0, 1, 'xyz1', 31, '777')

INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
    VALUES (1, 1, 'xyz2', 32, '777')

--UPDATE one of the records:
UPDATE foobar SET price = 29 WHERE upc = 'xyz2'

--Check the results:
SELECT * FROM foobar

Hope that helps.

validate a dropdownlist in asp.net mvc

There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel) Update: there was a typo in the below code snippet.

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")

For the validator use

@Html.ValidationMessage("Cat")

Is there a query language for JSON?

Another way to look at this would be to use mongoDB You can store your JSON in mongo and then query it via the mongodb query syntax.

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

Transfer files to/from session I'm logged in with PuTTY

Since you asked about to/from, here's a trick that works for the 'from' part. Open the 'Change settings...' screen, Terminal, and under 'Printer to send ANSI printer output to:' select 'Generic / Text Only'

Now on the remote system, run this on one line:

tput mc5; cat whatever.txt; tput mc4

Putty will inform you that the file was saved. What this is doing is putting the terminal into printer mode (tput mc5), printing the file to the screen (cat), and then turning off printer mode (tput mc4). If you don't put all the commands on one line, the screen will appear frozen because Putty is saving all terminal output to a file in the background.

If you're on a more limited system that doesn't have the tput command (e.g. a qnap), you can try printf "\x1b[5i" instead of tput mc5, and printf "\x1b[4i" instead of tput mc4.

The command in the middle is just anything that prints to the screen. So use tail -n 10000 blah.log to download the last 10k lines of the log file, or use a base64 encoder to map a binary file to something you can print (and then decode on your local system):

printf "\x1b[5i"; openssl enc -base64 -in something.zip; printf "\x1b[4i"

Private properties in JavaScript ES6 classes

Short answer, no, there is no native support for private properties with ES6 classes.

But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties. Note that the getters and setters gets redefine on each new instance of the class.

ES6

class Person {
    constructor(name) {
        var _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }
    }
}

ES5

function Person(name) {
    var _name = name
    this.setName = function(name) { _name = name; }
    this.getName = function() { return _name; }
}

How can I get a random number in Kotlin?

Kotlin >= 1.3, multiplatform support for Random

As of 1.3, the standard library provided multi-platform support for randoms, see this answer.

Kotlin < 1.3 on JavaScript

If you are working with Kotlin JavaScript and don't have access to java.util.Random, the following will work:

fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()

Used like this:

// will return an `Int` between 0 and 10 (incl.)
(0..10).random()

Configuration System Failed to Initialize

I just had this and it was because I had a <configuration> element nested inside of a <configuration> element.

What is the difference between <html lang="en"> and <html lang="en-US">?

RFC 3066 gives the details of the allowed values (emphasis and links added):

All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.

I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:

Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.

By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.

A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse):

Type: variant

Subtag: scouse

Description: Scouse

Added: 2006-09-18

Prefix: en

Comments: English Liverpudlian dialect known as 'Scouse'

There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad (17th century French).


The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:

Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.

I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.

Determine path of the executing script

I like this approach:

this.file <- sys.frame(tail(grep('source',sys.calls()),n=1))$ofile
this.dir <- dirname(this.file)

What does set -e mean in a bash script?

Script 1: without setting -e
#!/bin/bash
decho "hi"
echo "hello"
This will throw error in decho and program continuous to next line

Script 2: With setting -e
#!/bin/bash
set -e
decho "hi" 
echo "hello"
# Up to decho "hi" shell will process and program exit, it will not proceed further

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Is it possible to listen to a "style change" event?

Interesting question. The problem is that height() does not accept a callback, so you wouldn't be able to fire up a callback. Use either animate() or css() to set the height and then trigger the custom event in the callback. Here is an example using animate() , tested and works (demo), as a proof of concept :

$('#test').bind('style', function() {
    alert($(this).css('height'));
});

$('#test').animate({height: 100},function(){
$(this).trigger('style');
}); 

Calling ASP.NET MVC Action Methods from JavaScript

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

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

For me, the problem was caused not by the app in development itself but by the Chrome extension: React Developer Tool. I solved partially that by right-clicking the extension icon in the toolbar, clicking "manage extension" (I'm freely translating menu text here since my browser language is in Brazilian Portuguese), then enabling "Allow access to files URLs." But this measure fixed just some of the alerts.

I found issues in the react repo that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.

You can confirm is extension-related by accessing your app in an anonymous tab without any extension enabled.

Can I edit an iPad's host file?

The easiest way to do this is to run an iPad simulator using XCode and then add an entry in the hosts file (/etc/hosts) on the host system to point to your test site.

CSS Progress Circle

Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:

http://jsfiddle.net/maayan/byT76/

That's the basic css that enables it:

.clip1 {
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
}
.slice1 {
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,100px,200px,0px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

.clip2 
{
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0,100px,200px,0px);
}

.slice2
{
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

and the js rotates it as required.

quite easy to understand..

Hope it helps, Maayan

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

Can I set text box to readonly when using Html.TextBoxFor?

Updated for modern versions of .NET per @1c1cle's suggestion in a comment:

<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>

Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.

Something to be aware of is that if you set that readonly value to false, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that readonly attribute in.

Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):

<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>