Programs & Examples On #Slickedit

SlickEdit is a non-free software for developers with multi-language development tools. It's a cross-platform and support 40+ languages.

How do I get a list of folders and sub folders without the files?

dir /ad /b /s will give the required answer.

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

jQuery Keypress Arrow Keys

$(document).on( "keydown",  keyPressed);

function keyPressed (e){
    e = e || window.e;
    var newchar = e.which || e.keyCode;
    alert(newchar)
}

EnterKey to press button in VBA Userform

Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

package javax.servlet.http does not exist

The solution that work for is were add the next dependency to my pom.xml file.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

Convert JSON to DataTable

You can make use of JSON.Net here. Take a look at JsonConvert.DeserializeObject method.

How do you keep parents of floated elements from collapsing?

One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.

It goes something like this...

.cf:after {
    content: " ";
    display: block;
    visibility: hidden;
    height: 0;
    clear: both;
}

You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.

What I use is another variation which comes from Nicolas Gallagher.

It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).

.cf:after {
    content: " ";
    display: table;
    clear: float;
}

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

How to check if a column exists in a SQL Server table?

A more concise version

IF COL_LENGTH('table_name','column_name') IS NULL
BEGIN
/* Column does not exist or caller does not have permission to view the object */
END

The point about permissions on viewing metadata applies to all answers not just this one.

Note that the first parameter table name to COL_LENGTH can be in one, two, or three part name format as required.

An example referencing a table in a different database is

COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')

One difference with this answer compared to using the metadata views is that metadata functions such as COL_LENGTH always only return data about committed changes irrespective of the isolation level in effect.

How to check if a variable is not null?

Here is how you can test if a variable is not NULL:

if (myVar !== null) {...}

the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..

How to convert HTML file to word?

A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.

How to export and import environment variables in windows?

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

Difference between TCP and UDP?

Short and simple differences between Tcp and Udp protocol:

1) Tcp - Transmission control protocol and Udp - User datagram protocol.

2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.

3) Tcp is a stream oriented, where as Udp is a message oriented protocol.

4) Tcp is a slower than Udp.

What's the best way to add a full screen background image in React Native

I've heard about having to use BackgroundImage because in future you are supposed to not be able to nest the Image tag. But I could not get BackgroudImage to properly display my background. What I did was nest my Image inside a View tag and style both the outer View as well as the image. Keys were setting width to null, and setting resizeMode to 'stretch'. Below is my code:

_x000D_
_x000D_
import React, {Component} from 'react';_x000D_
import { View, Text, StyleSheet, Image} from 'react-native';_x000D_
_x000D_
export default class BasicImage extends Component {_x000D_
 constructor(props) {_x000D_
   super(props);_x000D_
_x000D_
   this.state = {};_x000D_
 }_x000D_
_x000D_
 render() {_x000D_
  return (_x000D_
   <View style={styles.container}>_x000D_
       <Image _x000D_
         source={this.props.source}_x000D_
         style={styles.backgroundImage}_x000D_
       />_x000D_
      </View>_x000D_
  )_x000D_
 }_x000D_
}_x000D_
_x000D_
const styles = StyleSheet.create({   _x000D_
  container: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   marginBottom: 50_x000D_
  },_x000D_
    text: {_x000D_
      marginLeft: 5,_x000D_
      marginTop: 22,_x000D_
      fontFamily: 'fontawesome',_x000D_
        color: 'black',_x000D_
        fontSize: 25,_x000D_
        backgroundColor: 'rgba(0,0,0,0)',_x000D_
    },_x000D_
  backgroundImage: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   resizeMode: 'stretch',_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

How to run a shell script at startup

  • Add your script to /etc/init.d/ directory
  • Update your rc run-levels: $ update-rc.d myScript.sh defaults NN where NN is the order in which it should be executed. 99 for example will mean it would be run after 98 and before 100.

How to get the type of T from a member of a generic class or method?

With the following extension method you can get away without reflection:

public static Type GetListType<T>(this List<T> _)
{
    return typeof(T);
}

Or more general:

public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return typeof(T);
}

Usage:

List<string>        list    = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;

Type listType    = list.GetListType();           // string
Type stringsType = strings.GetEnumeratedType();  // string
Type objectsType = objects.GetEnumeratedType();  // BEWARE: object

pip issue installing almost any library

I had this with PyCharm and upgrading pip to 10.0.1 broke pip with "'main' not found in module" error.

I could solve this problem by installing pip 9.0.3 as seen in some other thread. These are the steps I did:

  1. Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn't be used to install it).
  2. Install pip 9.0.3 from tar.gz python -m pip install pip-9.0.3.tar.gz

Everything started to work after that.

Run cmd commands through Java

You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.

To set the current working directory in your actual Java program, you should write:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

How to get JS variable to retain value after page refresh?

You can do that by storing cookies on client side.

HashMaps and Null values?

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

How do you properly determine the current script directory?

Hopefully this helps:- If you run a script/module from anywhere you'll be able to access the __file__ variable which is a module variable representing the location of the script.

On the other hand, if you're using the interpreter you don't have access to that variable, where you'll get a name NameError and os.getcwd() will give you the incorrect directory if you're running the file from somewhere else.

This solution should give you what you're looking for in all cases:

from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))

I haven't thoroughly tested it but it solved my problem.

Pip Install not installing into correct directory?

  1. download pip at https://pypi.python.org/pypi/pip (tar)
  2. unzip tar file
  3. cd to the file’s directory
  4. sudo python2.7 setup.py install

Assigning variables with dynamic names in Java

Try this way:

    HashMap<String, Integer> hashMap = new HashMap();

    for (int i=1; i<=3; i++) {
        hashMap.put("n" + i, 5);
    }

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.

libpng warning: iCCP: known incorrect sRGB profile

Libpng-1.6 is more stringent about checking ICC profiles than previous versions. You can ignore the warning. To get rid of it, remove the iCCP chunk from the PNG image.

Some applications treat warnings as errors; if you are using such an application you do have to remove the chunk. You can do that with any of a variety of PNG editors such as ImageMagick's

convert in.png out.png

To remove the invalid iCCP chunk from all of the PNG files in a folder (directory), you can use mogrify from ImageMagick:

mogrify *.png

This requires that your ImageMagick was built with libpng16. You can easily check it by running:

convert -list format | grep PNG

If you'd like to find out which files need to be fixed instead of blindly processing all of them, you can run

pngcrush -n -q *.png

where the -n means don't rewrite the files and -q means suppress most of the output except for warnings. Sorry, there's no option yet in pngcrush to suppress everything but the warnings.


Binary Releases of ImageMagick are here


For Android Projects (Android Studio) navigate into res folder.

For example:

C:\{your_project_folder}\app\src\main\res\drawable-hdpi\mogrify *.png

How can I specify the schema to run an sql file against in the Postgresql command line

The PGOPTIONS environment variable may be used to achieve this in a flexible way.

In an Unix shell:

PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql

If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS only once and export it.

PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS

psql -d somebase
psql -d someotherbase
...

or invoke the top-level shell script with PGOPTIONS set from the outside

PGOPTIONS="--search_path=my_schema_01"  ./my-upgrade-script.sh

In Windows CMD environment, set PGOPTIONS=value should work the same.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

    D:\Java\jdk1.5.0_10\bin\keytool -import -file "D:\Certificates\SDS services\Dev\dev-sdsservices-was8.infavig.com.cer" -keystore "D:\Java\jdk1.5.0_10\jre\lib\security\cacerts" -alias "sds certificate"

jQuery get text as number

number = parseInt(number);

That should do the trick.

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

Edit: this information is for visualvm specifically, not for any other java app

As mentioned by others, you need to modify the visualvm.conf

For the latest version of JvisualVM 1.3.6 on Mac, the install directories have changed.

It is currently in /Applications/VisualVM.app/Contents/Resources/visualvm/etc/visualvm.conf.

However this may depend on where you have installed VisualVM. The easiest way to find where your VisualVM is to start it, and then look at the process using:

ps -ef | grep VisualVM

You will see something like:

... -Dnetbeans.dirs=/Applications/VisualVM.app/Contents/Resources/visualvm/visualvm...

You want to take the netbeans.dir property and look up a directory and you will find the etc folder.

Uncomment this line in the visualvm.conf and change the path to the jdk

visualvm_jdkhome="/path/to/jdk"

Additionally, if you are having slowness with your visualvm and you have a lot of memory, I would suggest greatly increasing the amount of memory available and running it in server mode:

visualvm_default_options="-J-XX:MaxPermSize=96m -J-Xmx2048m -J-Xms2048m -J-server -J-XX:+UseCompressedOops -J-XX:+UseConcMarkSweepGC -J-XX:+UseParNewGC -J-XX:NewRatio=2 -J-Dnetbeans.accept_license_class=com.sun.tools.visualvm.modules.startup.AcceptLicense -J-Dsun.jvmstat.perdata.syncWaitMs=10000 -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.d3d=false"

Remove all constraints affecting a UIView

Based on previous answers (swift 4)

You can use immediateConstraints when you don't want to crawl entire hierarchies.

extension UIView {
/**
 * Deactivates immediate constraints that target this view (self + superview)
 */
func deactivateImmediateConstraints(){
    NSLayoutConstraint.deactivate(self.immediateConstraints)
}
/**
 * Deactivates all constrains that target this view
 */
func deactiveAllConstraints(){
    NSLayoutConstraint.deactivate(self.allConstraints)
}
/**
 * Gets self.constraints + superview?.constraints for this particular view
 */
var immediateConstraints:[NSLayoutConstraint]{
    let constraints = self.superview?.constraints.filter{
        $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
        } ?? []
    return self.constraints + constraints
}
/**
 * Crawls up superview hierarchy and gets all constraints that affect this view
 */
var allConstraints:[NSLayoutConstraint] {
    var view: UIView? = self
    var constraints:[NSLayoutConstraint] = []
    while let currentView = view {
        constraints += currentView.constraints.filter {
            return $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
        }
        view = view?.superview
    }
    return constraints
}
}

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

Unable to run Java GUI programs with Ubuntu

I stopped getting this exception when I installed default-jdk using apt. I'm running Ubuntu 14.04 (Trusty Tahr), and the problem appears to have been the result of having a "headless" Java installed. All I did was:

sudo apt-get install default-jdk

TypeError: ObjectId('') is not JSON serializable

in my case I needed something like this:

class JsonEncoder():
    def encode(self, o):
        if '_id' in o:
            o['_id'] = str(o['_id'])
        return o

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

How can I color dots in a xy scatterplot according to column value?

Non-VBA Solution:

You need to make an additional group of data for each color group that represent the Y values for that particular group. You can use these groups to make multiple data sets within your graph.

Here is an example using your data:

     A       B        C        D                    E                        F                            G
----------------------------------------------------------------------------------------------------------------------
1| COMPANY  XVALUE   YVALUE   GROUP                 Red                     Orange                       Green
2| Apple     45       35       red         =IF($D2="red",$C2,NA()) =IF($D2="orange",$C2,NA()) =IF($D2="green",$C2,NA())
3| Xerox     45       38       red         =IF($D3="red",$C3,NA()) =IF($D3="orange",$C3,NA()) =IF($D3="green",$C3,NA())
4| KMart     63       50       orange      =IF($D4="red",$C4,NA()) =IF($D4="orange",$C4,NA()) =IF($D4="green",$C4,NA())
5| Exxon     53       59       green       =IF($D5="red",$C5,NA()) =IF($D5="orange",$C5,NA()) =IF($D5="green",$C5,NA())

It should look like this afterwards:

     A       B        C        D          E           F          G
---------------------------------------------------------------------
1| COMPANY  XVALUE   YVALUE   GROUP       Red         Orange     Green
2| Apple     45       35       red         35         #N/A       #N/A    
3| Xerox     45       38       red         38         #N/A       #N/A
4| KMart     63       50       orange     #N/A         50        #N/A
5| Exxon     53       59       green      #N/a        #N/A        59

Now you can generate your graph using different data sets. Here is a picture showing just this example data:

enter image description here

You can change the series (X;Y) values to B:B ; E:E, B:B ; F:F, B:B ; G:G respectively, to make it so the graph is automatically updated when you add more data.

Get Selected value of a Combobox

You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()
'your code here
End Sub

Also you can get the selected value using below

ComboBox1.Value

How to get item count from DynamoDB?

This is solution for AWS JavaScript SDK users, it is almost same for other languages.

Result.data.Count will give you what you are looking for

 apigClient.getitemPost({}, body, {})

    .then(function(result){

        var dataoutput = result.data.Items[0];

        console.log(result.data.Count);
  }).catch( function(result){

});

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

Two solutions for this error:

1. add this permission in your androidManifest.xml of your Android project

<uses-permission android:name="android.permission.INTERNET"/>

2. Turn on the Internet Connection of your device first.

Add shadow to custom shape on Android

This is how I do it:

Android Native Button with Shadows

Code bellow for one button STATE:

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

            <corners android:radius="15dp" />
        </shape>
    </item>
    <!-- background color -->
    <item
        android:bottom="3px"
        android:left="3px"
        android:right="3px"
        android:top="3px">
        <shape android:shape="rectangle" >
            <solid android:color="#cc2b2b" />


            <corners android:radius="8dp" />
        </shape>
    </item>
    <!-- over left shadow -->
    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="180"
                android:centerColor="#00FF0000"
                android:centerX="0.9"
                android:endColor="#99000000"
                android:startColor="#00FF0000" />

            <corners android:radius="8dp" />
        </shape>
    </item>
    <!-- over right shadow -->
    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="360"
                android:centerColor="#00FF0000"
                android:centerX="0.9"
                android:endColor="#99000000"
                android:startColor="#00FF0000" />

            <corners android:radius="8dp" />
        </shape>
    </item>
    <!-- over top shadow -->
    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="-90"
                android:centerColor="#00FF0000"
                android:centerY="0.9"
                android:endColor="#00FF0000"
                android:startColor="#99000000"
                android:type="linear" />

            <corners android:radius="8dp" />
        </shape>
    </item>
    <!-- over bottom shadow -->
    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="90"
                android:centerColor="#00FF0000"
                android:centerY="0.9"
                android:endColor="#00FF0000"
                android:startColor="#99000000"
                android:type="linear" />

            <corners android:radius="8dp" />
        </shape>
    </item>
</layer-list>

Then you should have a selector with diferent versions of the button, something like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_button_red_pressed" android:state_pressed="true"/> <!-- pressed -->
    <item android:drawable="@drawable/ic_button_red_selected" android:state_focused="true"/> <!-- focused -->
    <item android:drawable="@drawable/ic_button_red_selected" android:state_selected="true"/> <!-- selected -->
    <item android:drawable="@drawable/ic_button_red_default"/> <!-- default -->

</selector>

hope this can help you..good luck

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text

Open text file and program shortcut in a Windows batch file

I was able to figure out the solution:

start notepad "myfile.txt"
"myshortcut.lnk"
exit

AJAX reload page with POST

There's another way with post instead of ajax

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

adb shell command to make Android package uninstall dialog appear

Running the @neverever415 answer I got:

Failure [DELETE_FAILED_INTERNAL_ERROR]

In this case check that you wrote a right package name, maybe it is a debug version like com.package_name.debug:

adb shell pm uninstall com.package_name.debug

Or see https://android.stackexchange.com/questions/179575/how-to-uninstall-a-system-app-using-adb-uninstall-command-not-remove-via-rm-or.

ImportError: No module named PyQt4.QtCore

As mentioned in the comments, you need to install the python-qt4 package - no need to recompile it yourself.

sudo apt-get install python-qt4

ArrayList of int array in java

Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

Jquery in React is not defined

Add "ref" to h1 tag :

<h1 ref="source">Hey there.</h1>

and
const { source } = this.props; change to const { source } = this.refs;

How do you implement a class in C?

you can take a look at GOBject. it's an OS library that give you a verbose way to do an object.

http://library.gnome.org/devel/gobject/stable/

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

I ran into a merge conflict. How can I abort the merge?

Since Git 1.6.1.3 git checkout has been able to checkout from either side of a merge:

git checkout --theirs _widget.html.erb

Oracle Convert Seconds to Hours:Minutes:Seconds

The following is Yet Another Way (tm) - still involves a little calculation but provides an example of using EXTRACT to pull the individual fields out of an INTERVAL:

DECLARE 
  SUBTYPE BIG_INTERVAL IS INTERVAL DAY(9) TO SECOND;

  i        BIG_INTERVAL;
  nSeconds NUMBER := 86400000;

  FUNCTION INTERVAL_TO_HMS_STRING(inv IN BIG_INTERVAL)
    RETURN VARCHAR2
  IS
    nHours    NUMBER;
    nMinutes  NUMBER;
    nSeconds  NUMBER;
    strHour_format  VARCHAR2(10) := '09';
    workInv   INTERVAL DAY(9) TO SECOND(9);
  BEGIN
    nHours := EXTRACT(HOUR FROM inv) + (EXTRACT(DAY FROM inv) * 24);
    strHour_format := TRIM(RPAD(' ', LENGTH(TRIM(TO_CHAR(ABS(nHours)))), '0') || '9');

    nMinutes := ABS(EXTRACT(MINUTE FROM inv));
    nSeconds := ABS(EXTRACT(SECOND FROM inv));

    RETURN TRIM(TO_CHAR(nHours, strHour_format)) || ':' ||
           TRIM(TO_CHAR(nMInutes, '09')) || ':' ||
           TRIM(TO_CHAR(nSeconds, '09'));
  END INTERVAL_TO_HMS_STRING;

BEGIN
  i := NUMTODSINTERVAL(nSeconds, 'SECOND');

  DBMS_OUTPUT.PUT_LINE('i (fields) = ' || INTERVAL_TO_HMS_STRING(i));
END;

The code which extracts the fields, etc, still has to contain a calculation to convert the DAY field to equivalent hours, and is not the prettiest, but wrapped up neatly in a procedure it's not too bad to use.

Share and enjoy.

WPF MVVM: How to close a window

The solution to close a window in wpf that that worked for me is not answered here so i thought i would add my solution too.

        private static Window GetWindow(DependencyObject sender)
        {
            Window window = null;
            if (sender is Window)
                window = (Window)sender;
            if (window == null)
                window = Window.GetWindow(sender);
            return window;
        }
        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender as DependencyObject;

            Window window = GetWindow(button);
                if (window != null)
                    window.Close();
                   // window.Visibility = Visibility.Hidden; 
           // choose between window.close or set window.visibility to close or hide the window.

            //            }
        }

Add CloseWindow event to the button in you window as following.

<Button Content="Cancel" Click="CloseWindow" >

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

Java: is there a map function?

Since Java 8, there are some standard options to do this in JDK:

Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());

See java.util.Collection.stream() and java.util.stream.Collectors.toList().

How to get CRON to call in the correct PATHs

Most likely, cron is running in a very sparse environment. Check the environment variables cron is using by appending a dummy job which dumps env to a file like this:

* * * * * env > env_dump.txt

Compare that with the output of env in a normal shell session.

You can prepend your own environment variables to the local crontab by defining them at the top of your crontab.

Here's a quick fix to prepend $PATH to the current crontab:

# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron

The resulting crontab will look similar to chrissygormley's answer, with PATH defined before the crontab rules.

How do I split an int into its digits?

Reversed order digit extractor (eg. for 23 will be 3 and 2):

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    //print digit
}

Normal order digit extractor (eg. for 23 will be 2 and 3):

std::stack<int> sd;

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    sd.push(digit);
}

while (!sd.empty())
{
    int digit = sd.top();
    sd.pop();
    //print digit
}

MVC3 EditorFor readOnly

Try using:

@Html.DisplayFor(model => model.userName) <br/>
@Html.HiddenFor(model => model.userName)

What is the difference between typeof and instanceof and when should one be used vs. the other?

Use instanceof for custom types:

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 

Use typeof for simple built in types:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

true instanceof Boolean; // false
typeof true == 'boolean'; // true

99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true

function() {} instanceof Function; // true
typeof function() {} == 'function'; // true

Use instanceof for complex built in types:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

And the last one is a little bit tricky:

typeof null; // object

Remove ALL white spaces from text

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'')

MySQL combine two columns and add into a new column

Create the column:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);

Update the current values:

UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);

Update all future values automatically:

CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

How can I select records ONLY from yesterday?

This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today

SELECT  * 
FROM 
WHERE date(tran_date) = CURRENT_DATE()

Yesterday

SELECT  * 
FROM yourtable 
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

7-Zip command to create and extract a password-protected ZIP file on Windows?

I'm maybe a little bit late but I'm currently trying to develop a program which can brute force a password protected zip archive. First I tried all commands I found in the internet to extract it through cmd... But it never worked....Every time I tried it, the cmd output said, that the key was wrong but it was right. I think they just disenabled this function in a current version.

What I've done to Solve the problem was to download an older 7zip version(4.?) and to use this for extracting through cmd.

This is the command: "C:/Program Files (86)/old7-zip/7z.exe" x -pKey "C:/YOURE_ZIP_PATH"

The first value("C:/Program Files (86)/old7-zip/7z.exe") has to be the path where you have installed the old 7zip to. The x is for extract and the -p For you're password. Make sure you put your password without any spaces behind the -p! The last value is your zip archive to extract. The destination where the zip is extracted to will be the current path of cmd. You can change it with: cd YOURE_PATH

Now I let execute this command through java with my password trys. Then I check the error output stream of cmd and if it is null-> then the password is right!

How to get base url in CodeIgniter 2.*

You need to add url helper in config/autoload

$autoload['helper'] = array('form', 'url', 'file', 'html'); <-- Like This

Then you can use base_url or any kind of url.

Keep values selected after form submission

Try this solution for keep selected value in dropdown:

<form action="<?php echo get_page_link(); ?>" method="post">
    <select name="<?php echo $field_key['key']; ?>" onchange="javascript: 
       submit()">
    <option value="">All Category</option>
    <?php 
    foreach( $field['choices'] as $key => $value ){ 
       if($post_key==$key){ ?>
          <option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
   }else{?>
  <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
 <?php }
  }?>
 </select>
</form>

How do you make a LinearLayout scrollable?

Here is how I did it by trial and error.

ScrollView - (the outer wrapper).

    LinearLayout (child-1).

        LinearLayout (child-1a).

        LinearLayout (child-1b).

Since ScrollView can have only one child, that child is a linear layout. Then all the other layout types occur in the first linear layout. I haven't tried to include a relative layout yet, but they drive me nuts so I will wait until my sanity returns.

Conditional Replace Pandas

.ix indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the .ix indexer is deprecated, so you should avoid using it. Instead, you can use .loc or iloc indexers. You can solve this problem by:

mask = df.my_channel > 20000
column_name = 'my_channel'
df.loc[mask, column_name] = 0

Or, in one line,

df.loc[df.my_channel > 20000, 'my_channel'] = 0

mask helps you to select the rows in which df.my_channel > 20000 is True, while df.loc[mask, column_name] = 0 sets the value 0 to the selected rows where maskholds in the column which name is column_name.

Update: In this case, you should use loc because if you use iloc, you will get a NotImplementedError telling you that iLocation based boolean indexing on an integer type is not available.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

How to Sign an Already Compiled Apk

You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

Datatables warning(table id = 'example'): cannot reinitialise data table

I know its an old question. This problem can be easily reproduced if you try to reinitialize the Datatable again.

For example in your function somewhere you are calling $('#example').DataTable( { searching: false} ); again.

There is easy resolving this issue. Please follow the steps

  1. Initialize the Datatable to a variable rather than directly initializing DataTable method.
    1. For Example Instead of calling $('#example').DataTable( { searching: false} ); try to declare it globally (or in scope of javascription that you are using) like this var table = $('#example').DataTable( { searching: false } );.
  2. Now Whenever you are calling this method $('#example').DataTable( { searching: false} ); again then before calling it perform the following actions
    1. if (table != undefined && table != null) { table.destroy(); table = null; }
  3. Once you have followed the steps above then go ahead with re-initializing the table with same variable without using var keyword (as you have already defined it) i.e table = $('#example').DataTable( { searching: false } );

JSFiddle Code Also attached for any reference of same code http://jsfiddle.net/vibs2006/qxy4nwfg/

What is the difference between _tmain() and main() in C++?

_tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.

The correct declaration is

 int _tmain(int argc, _TCHAR *argv[]) 

If the macro UNICODE is defined, that expands to

int wmain(int argc, wchar_t *argv[])

Otherwise it expands to

int main(int argc, char *argv[])

Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to

 int wmain(int argc, char *argv[])

which is just plain wrong.

std::cout works with ASCII characters. You need std::wcout if you are using wide characters.

try something like this

#include <iostream>
#include <tchar.h>

#if defined(UNICODE)
    #define _tcout std::wcout
#else
    #define _tcout std::cout
#endif

int _tmain(int argc, _TCHAR *argv[]) 
{
   _tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;

   // Loop through each argument and print its number and value
   for (int i=0; i<argc; i++)
      _tcout << i << _T(" ") << argv[i] << std::endl;

   return 0;
}

Or you could just decide in advance whether to use wide or narrow characters. :-)

Updated 12 Nov 2013:

Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.

End Update

How to check if a string "StartsWith" another string?

You can also return all members of an array that start with a string by creating your own prototype / extension to the the array prototype, aka

Array.prototype.mySearch = function (target) {
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str){
        return this.slice(0, str.length) == str;
      };
    }
    var retValues = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i].startsWith(target)) { retValues.push(this[i]); }
    }
    return retValues;
};

And to use it:

var myArray = ['Hello', 'Helium', 'Hideout', 'Hamster'];
var myResult = myArray.mySearch('Hel');
// result -> Hello, Helium

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

Xcode project -> goto info.plist and Click + Button then Add (App Transport Security Settings)Expand, Allow Arbitrary Loads Set YES. Thanks

OpenJDK availability for Windows OS

In case you are still looking for a Windows build of OpenJDK, Azul Systems launched the Zulu product line last fall. The Zulu distribution of OpenJDK is built and tested on Windows and Linux. We posted the OpenJDK 8 version this week, though OpenJDK 7 and 6 are both available too. The following URL leads to you free downloads, the Zulu community forum, and other details: http://www.azulsystems.com/products/zulu These are binary downloads, so you do not need to build OpenJDK from scratch to use them.

I can attest that building OpenJDK 6 for Windows was not a trivial exercise. Of the six different platforms we've built (OpenJDK6, OpenJDK7, and OpenJDK8, each for Windows and Linux) for x64 so far, the Windows OpenJDK6 build took by far the most effort to wring out items that didn't work on Windows, or would not pass the Technical Compatibility Kit test protocol for Java SE 6 "as is."

Disclaimer: I am the Product Manager for Zulu. You can review my Zulu release notices here: https://support.azulsystems.com/hc/communities/public/topics/200063190-Zulu-Releases I hope this helps.

HTML-Tooltip position relative to mouse pointer

One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:

http://codepen.io/c0un7z3r0/pen/LZWXEw

Note that the span that contains the tooltip content is relative to the parent li. The magic is here:

ul#list_of_thrones li > span{
  display:none;
}
ul#list_of_thrones li:hover > span{
  position: absolute;
  display:block;
  ...
}

As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.

I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

How to make an introduction page with Doxygen

I tried all the above with v 1.8.13 to no avail. What worked for me (on macOS) was to use the doxywizard->Expert tag to fill the USE_MD_FILE_AS_MAINPAGE setting.

It made the following changes to my Doxyfile:

USE_MDFILE_AS_MAINPAGE = ../README.md
...
INPUT                  = ../README.md \
                         ../sdk/include \
                         ../sdk/src

Note the line termination for INPUT, I had just been using space as a separator as specified in the documentation. AFAICT this is the only change between the not-working and working version of the Doxyfile.

Getting a random value from a JavaScript array

In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:

window.choice = function() {
  if (!this.length || this.length == 0) return;
  if (this.length == 1) return this[0];
  return this[Math.floor(Math.random()*this.length)];
}

Now anywhere on your app you call it like:

var rand = window.choice.call(array)

This way you can still use for(x in array) loop properly

COALESCE Function in TSQL

I'm not sure why you think the documentation is vague.

It simply goes through all the parameters one by one, and returns the first that is NOT NULL.

COALESCE(NULL, NULL, NULL, 1, 2, 3)
=> 1


COALESCE(1, 2, 3, 4, 5, NULL)
=> 1


COALESCE(NULL, NULL, NULL, 3, 2, NULL)
=> 3


COALESCE(6, 5, 4, 3, 2, NULL)
=> 6


COALESCE(NULL, NULL, NULL, NULL, NULL, NULL)
=> NULL

It accepts pretty much any number of parameters, but they should be the same data-type. (If they're not the same data-type, they get implicitly cast to an appropriate data-type using data-type order of precedence.)

It's like ISNULL() but for multiple parameters, rather than just two.

It's also ANSI-SQL, where-as ISNULL() isn't.

Why can't I do <img src="C:/localfile.jpg">?

C: is not a recognized URI scheme. Try file://c|/... instead.

How to style a disabled checkbox?

Checkboxes (radio buttons and <select>) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.

Your best bet it to put an overlay on top and style that instead.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

For generating icons for your Xcode projects, I'd suggest you consider using SquareIcon. I believe that it makes creating app icon sets for Apple platforms very easy. Just to let you know, this is my own app.

You can drop in a generic image file of your icon (like a PNG or JPG) and generate a .appiconset file which you can put in your Xcode project's asset catalog. This removes the requirement of manually resizing a bunch of images.

A html space is showing as %2520 instead of %20

A bit of explaining as to what that %2520 is :

The common space character is encoded as %20 as you noted yourself. The % character is encoded as %25.

The way you get %2520 is when your url already has a %20 in it, and gets urlencoded again, which transforms the %20 to %2520.

Are you (or any framework you might be using) double encoding characters?

Edit: Expanding a bit on this, especially for LOCAL links. Assuming you want to link to the resource C:\my path\my file.html:

  • if you provide a local file path only, the browser is expected to encode and protect all characters given (in the above, you should give it with spaces as shown, since % is a valid filename character and as such it will be encoded) when converting to a proper URL (see next point).
  • if you provide a URL with the file:// protocol, you are basically stating that you have taken all precautions and encoded what needs encoding, the rest should be treated as special characters. In the above example, you should thus provide file:///c:/my%20path/my%20file.html. Aside from fixing slashes, clients should not encode characters here.

NOTES:

  • Slash direction - forward slashes / are used in URLs, reverse slashes \ in Windows paths, but most clients will work with both by converting them to the proper forward slash.
  • In addition, there are 3 slashes after the protocol name, since you are silently referring to the current machine instead of a remote host ( the full unabbreviated path would be file://localhost/c:/my%20path/my%file.html ), but again most clients will work without the host part (ie two slashes only) by assuming you mean the local machine and adding the third slash.

chrome undo the action of "prevent this page from creating additional dialogs"

open a new window or tab with the same link.. the PREVENT option lasts per session only..

Cannot resolve symbol 'AppCompatActivity'

Lets get going step by step: first clean project by using

Build->Clean

if this doesn't helps then use your second step

File>Invalidate Caches/Restart...

But the real problem begins when all the above options doesn't works so use your ultimate solution is to close project and go to project location directory and delete

.idea

You can open your project now again.

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Sometimes Version problem in 'Postman' :

I have face the same problem. While sending the data using the oldest version of postman.
That time I have received the empty json data in server side.
And I have fix this problem, Once I uninstall the oldest version of postman and installed with latest version.

input file appears to be a text format dump. Please use psql

The answer above didn't work for me, this worked:

psql db_development < postgres_db.dump

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

or a @ResponseStatus to your method.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

Can I bind an array to an IN() condition?

For something quick:

//$db = new PDO(...);
//$ids = array(...);

$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");
$sth->execute($ids);

Solve error javax.mail.AuthenticationFailedException

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

How to install Python packages from the tar.gz file without using pip install

You can install a tarball without extracting it first. Just navigate to the directory containing your .tar.gz file from your command prompt and enter this command:

pip install my-tarball-file-name.tar.gz

I am running python 3.4.3 and this works for me. I can't tell if this would work on other versions of python though.

How to check all versions of python installed on osx and centos

Use,

yum list installed
command to find the packages you installed.

Apache VirtualHost and localhost

localhost will always redirect to 127.0.0.1. You can trick this by naming your other VirtualHost to other local loop-back address, such as 127.0.0.2. Make sure you also change the corresponding hosts file to implement this.

For example, my httpd-vhosts.conf looks like this:

<VirtualHost 127.0.0.2:80>
    DocumentRoot "D:/6. App Data/XAMPP Shared/htdocs/intranet"
    ServerName intranet.dev
    ServerAlias www.intranet.dev
    ErrorLog "logs/intranet.dev-error.log"
    CustomLog "logs/intranet.dec-access.log" combined

    <Directory "D:/6. App Data/XAMPP Shared/htdocs/intranet">
        Options Indexes FollowSymLinks ExecCGI Includes
        Order allow,deny
        Allow from all
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

(Notice that in <VirtualHost> section I typed 127.0.0.2:80. It means that this block of VirtualHost will only affects requests to IP address 127.0.0.2 port 80, which is the default port for HTTP.

To route the name intranet.dev properly, my hosts entry line is like this:

127.0.0.2 intranet.dev

This way, it will prevent you from creating another VirtualHost block for localhost, which is unnecessary.

regex pattern to match the end of a string

Use this Regex pattern: /([^/]*)$

Core dumped, but core file is not in the current directory?

Writing instructions to get a core dump under Ubuntu 16.04 LTS:

  1. As @jtn has mentioned in his answer, Ubuntu delegates the display of crashes to apport, which in turn refuses to write the dump because the program is not an installed package. Before making changes

  2. To remedy the problem, we need to make sure apport writes core dump files for non-package programs as well. To do so, create a file named ~/.config/apport/settings with the following contents:
    [main] unpackaged=true

  3. Now crash your program again, and see your crash files being generated within folder: /var/crash with names like *.1000.crash. Note that these files cannot be read by gdb directly. After making changes
  4. [Optional] To make the dumps readble by gdb, run the following command:

    apport-unpack <location_of_report> <target_directory>

References: Core_dump – Oracle VM VirtualBox

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

How to create a Custom Dialog box in android?

Full Screen Custom Alert Dialog Class in Kotlin

  1. Create XML file, same as you would an activity

  2. Create AlertDialog custom class

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
    
  3. Call the dialog within the activity

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()
    

Note**: If you do not want your dialog to be full screen, delete the following lines

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

How to margin the body of the page (html)?

I would say: (simple zero will work, 0px is a zero ;))

<body style="margin: 0;">

but maybe something overwrites your css. (assigns different style after you ;))

If you use Firefox - check out firebug plugin.

And in Chrome - just right-click on the page and chose "inspect element" in the menu. Find BODY in elements tree and check its properties.

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

Python Pandas : pivot table with aggfunc = count unique distinct

Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

In [1]:
import pandas as pd

# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})

# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)

Out [1]:
Z   Z1  Z2  Z3
Y           
Y1  1.0 1.0 NaN
Y2  NaN NaN 1.0

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

For me this worked: (added into .ssh\config)

Host *
HostkeyAlgorithms +ssh-dss
PubkeyAcceptedKeyTypes +ssh-dss

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

const char* concatenation

If you are using C++, why don't you use std::string instead of C-style strings?

std::string one="Hello";
std::string two="World";

std::string three= one+two;

If you need to pass this string to a C-function, simply pass three.c_str()

What's the best way to validate an XML file against an XSD file?

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

AngularJS For Loop with Numbers & Ranges

For those new to angularjs. The index can be gotten by using $index.

For example:

<div ng-repeat="n in [] | range:10">
    do something number {{$index}}
</div>

Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9

How to get text from each cell of an HTML table?

I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber) to reach the required cell. May be you can use webdriverbackedselenium and do this.

And you can get the total rows and columns by using

int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")

int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

The following simple fix worked for me, bypassing possible permissions issues with the socket.

In your nginx config, set fastcgi_pass to:

fastcgi_pass   127.0.0.1:9000;

Instead of

fastcgi_pass   /var/run/php5-fpm.sock;

This must match the listen = parameter in /etc/php5/fpm/pool.d/www.conf, so also set this to:

listen = 127.0.0.1:9000;

Then restart php5-fpm and nginx

service php5-fpm restart

And

service nginx restart

For more info, see: https://wildlyinaccurate.com/solving-502-bad-gateway-with-nginx-php-fpm/

Open two instances of a file in a single Visual Studio session

Window menu, New Horizontal/Vertical Tab Group there will do, I think.

RegEx: Grabbing values between quotation marks

In general, the following regular expression fragment is what you are looking for:

"(.*?)"

This uses the non-greedy *? operator to capture everything up to but not including the next double quote. Then, you use a language-specific mechanism to extract the matched text.

In Python, you could do:

>>> import re
>>> string = '"Foo Bar" "Another Value"'
>>> print re.findall(r'"(.*?)"', string)
['Foo Bar', 'Another Value']

How do you reverse a string in place in JavaScript?

The following technique (or similar) is commonly used to reverse a string in JavaScript:

// Don’t use this!
var naiveReverse = function(string) {
    return string.split('').reverse().join('');
}

In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:

naiveReverse('foo  bar');
// ? 'rab ?? oof'
// Where did the `` symbol go? Whoops!

If you’re wondering why this happens, read up on JavaScript’s internal character encoding. (TL;DR: is an astral symbol, and JavaScript exposes it as two separate code units.)

But there’s more:

// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('mañana man~ana');
// ? 'ana~nam anañam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.

A good string to test string reverse implementations is the following:

'foo  bar mañana man~ana'

Why? Because it contains an astral symbol () (which are represented by surrogate pairs in JavaScript) and a combining mark (the n~ in the last man~ana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).

The order in which surrogate pairs appear cannot be reversed, else the astral symbol won’t show up anymore in the ‘reversed’ string. That’s why you saw those ?? marks in the output for the previous example.

Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. That’s why the example output had a~ instead of ñ.

Hopefully, this explains why all the answers posted so far are wrong.


To answer your initial question — how to [properly] reverse a string in JavaScript —, I’ve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesn’t have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.

var input = 'foo  bar mañana man~ana';
esrever.reverse(input);
// ? 'anan~am anañam rab  oof'

As for the “in-place” part, see the other answers.

No Network Security Config specified, using platform default - Android Log

This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.

  1. Create an XML file Create XML file

  2. Add the following code on the new XML file you created Add base-config

  3. Add this on AndroidManifest.xml Add this code line

What is the @Html.DisplayFor syntax for?

Html.DisplayFor() will render the DisplayTemplate that matches the property's type.

If it can't find any, I suppose it invokes .ToString().


If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.


Example:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

How can I strip HTML tags from a string in ASP.NET?

string result = Regex.Replace(anytext, @"<(.|\n)*?>", string.Empty);

How do you transfer or export SQL Server 2005 data to Excel

SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).

  1. Right-click the database in SQL Management Studio
  2. Go to Tasks and then Export data, you'll then see an easy to use wizard.
  3. Your database will be the source, you can enter your SQL query
  4. Choose Excel as the target
  5. Run it at end of wizard

If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).

how to get the child node in div using javascript

var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;

Multi-dimensional arraylist or list in C#?

If you want to modify this I'd go with either of the following:

List<string[]> results;

-- or --

List<List<string>> results;

depending on your needs...

What is an example of the Liskov Substitution Principle?

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

When I first read about LSP, I assumed that this was meant in a very strict sense, essentially equating it to interface implementation and type-safe casting. Which would mean that LSP is either ensured or not by the language itself. For example, in this strict sense, ThreeDBoard is certainly substitutable for Board, as far as the compiler is concerned.

After reading up more on the concept though I found that LSP is generally interpreted more broadly than that.

In short, what it means for client code to "know" that the object behind the pointer is of a derived type rather than the pointer type is not restricted to type-safety. Adherence to LSP is also testable through probing the objects actual behavior. That is, examining the impact of an object's state and method arguments on the results of the method calls, or the types of exceptions thrown from the object.

Going back to the example again, in theory the Board methods can be made to work just fine on ThreeDBoard. In practice however, it will be very difficult to prevent differences in behavior that client may not handle properly, without hobbling the functionality that ThreeDBoard is intended to add.

With this knowledge in hand, evaluating LSP adherence can be a great tool in determining when composition is the more appropriate mechanism for extending existing functionality, rather than inheritance.

A generic list of anonymous class

You could do:

var list = new[] { o, o1 }.ToList();

There are lots of ways of skinning this cat, but basically they'll all use type inference somewhere - which means you've got to be calling a generic method (possibly as an extension method). Another example might be:

public static List<T> CreateList<T>(params T[] elements)
{
     return new List<T>(elements);
}

var list = CreateList(o, o1);

You get the idea :)

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

For myself, it turns out that wlan0 was down, which resulted in me being unable to connect out. So, ensuring that wlan0 was up, allowed pip / pip3 to work without issue.

Resolve Javascript Promise outside function scope

Accepted answer is wrong. It's pretty easy using scope and references, though it may make Promise purists angry:

const createPromise = () => {
    let resolver;
    return [
        new Promise((resolve, reject) => {
            resolver = resolve;
        }),
        resolver,
    ];
};

const [ promise, resolver ] = createPromise();
promise.then(value => console.log(value));
setTimeout(() => resolver('foo'), 1000);

We are essentially grabbing the reference to the resolve function when the promise is created, and we return that so it can be set externally.

In one second the console will output:

> foo

Git push requires username and password

I had the same issue.

So I changed the .git/config file from my project,

url = https://github.com/<your-user-here>/<your-repo-here>

to

url = [email protected]:<your-user-here>/<your-repo-here>

and added the SSH public key to the Git profile which is in setting.

For the SSH public key:

cat ~/.ssh/id_rsa.pub

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.

"Cannot update paths and switch to branch at the same time"

You can use these commands: git remote update, git fetch, git checkout -b branch_nameA origin:branch_nameB

I think maybe it's because of your local branch can not track remote branch

PHP - Move a file into a different folder on the server

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");

Installation error: INSTALL_FAILED_OLDER_SDK

I found that making the recommended change in the manifest didn't solve my problem.

The fix was found in the GradleScripts folder, in the build.gradle file for the Module:app.

Inside this file (build.gradle) the following line was modified. minSdkVersion 22 I changed this '22' value to '19' for my particular phone and the build completed without error.

Calling a javascript function recursively

I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)

  var fn = (function() {
    var innerFn = function(counter) {
      console.log(counter);

      if(counter > 0) {
        innerFn(counter-1);
      }
    };

    return innerFn;
  })();

  console.log("running fn");
  fn(3);

  var copyFn = fn;

  console.log("running copyFn");
  copyFn(3);

  fn = function() { console.log("done"); };

  console.log("fn after reassignment");
  fn(3);

  console.log("copyFn after reassignment of fn");
  copyFn(3);

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Expected response code 220 but got code "", with message "" in Laravel

In my case I had to set the

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465           <<<<<<<------------------------- (FOCUS THIS)
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>

MAIL_ENCRYPTION= ssl    <<<<<<<------------------------- (FOCUS THIS)

to work it.. Might be useful. Rest of the code was same as @Sid said.

And I think that editing both environment file and app/config/mail.php is unnecessary. Just use one method.

Edit as per the comment by @Zan

If you need to enable tls protection use following settings.

MAIL_PORT=587
MAIL_ENCRYPTION= tls  

See here for some other gmail settings

Spring - applicationContext.xml cannot be opened because it does not exist

This happens to me from time to time when using eclipse For some reason (eclipse bug??) the "excluded" parameter gets a value *.* (build path for my resources folder)

Just change the exclusion to none (see red rectangle vs green rectangle) I hope this helps someone in the future because it was very frustrating to find.

excluded

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

Error TF30063: You are not authorized to access ... \DefaultCollection

When Visual Studio prompted me for Visual Studio Team Services credentials there are two options:

  1. Use a "Work or School"
  2. Use a "Personal" account

In my situation I was using a work email address, however, I had to select "Personal" in order to get connected. Selecting "Work or School" gave me the "tf30063 you are not authorized to access..." error.

For some reason my email address appears to be registered as "personal" even though everything is setup in Office 365 / Azure as a company. I believe the Microsoft account was created prior to our Silver Partnership status with Microsoft.

Is it possible to serialize and deserialize a class in C++?

As far as "built-in" libraries go, the << and >> have been reserved specifically for serialization.

You should override << to output your object to some serialization context (usually an iostream) and >> to read data back from that context. Each object is responsible for outputting its aggregated child objects.

This method works fine so long as your object graph contains no cycles.

If it does, then you will have to use a library to deal with those cycles.

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

In order of activity, demos/examples available, and simplicity:

Related:

Selecting last element in JavaScript array

var last = array.slice(-1)[0];

I find slice at -1 useful for getting the last element (especially of an array of unknown length) and the performance is much better than calculating the length less 1.

Mozilla Docs on Slice

Performance of the various methods for selecting last array element

Android fade in and fade out with ImageView

I'm using this kind of routine for programmatically chaining animations.

    final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out); 
    final Animation anim_in  = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); 

    anim_out.setAnimationListener(new AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation)
        {
            ////////////////////////////////////////
            // HERE YOU CHANGE YOUR IMAGE CONTENT //
            ////////////////////////////////////////
            //ui_image.setImage...

            anim_in.setAnimationListener(new AnimationListener()
            {
                @Override
                public void onAnimationStart(Animation animation) {}

                @Override
                public void onAnimationRepeat(Animation animation) {}

                @Override
                public void onAnimationEnd(Animation animation) {}
            });

            ui_image.startAnimation(anim_in);
        }
    });

    ui_image.startAnimation(anim_out);

What is a correct MIME type for .docx, .pptx, etc.?

A working method in android to populates the mapping list mime types.

private static void fileMimeTypeMapping() {
     MIMETYPE_MAPPING.put("3gp", Collections.list("video/3gpp"));
     MIMETYPE_MAPPING.put("7z", Collections.list("application/x-7z-compressed"));
     MIMETYPE_MAPPING.put("accdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("ai", Collections.list("application/illustrator"));
     MIMETYPE_MAPPING.put("apk", Collections.list("application/vnd.android.package-archive"));
     MIMETYPE_MAPPING.put("arw", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("avi", Collections.list("video/x-msvideo"));
     MIMETYPE_MAPPING.put("bash", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("bat", Collections.list("application/x-msdos-program"));
     MIMETYPE_MAPPING.put("blend", Collections.list("application/x-blender"));
     MIMETYPE_MAPPING.put("bin", Collections.list("application/x-bin"));
     MIMETYPE_MAPPING.put("bmp", Collections.list("image/bmp"));
     MIMETYPE_MAPPING.put("bpg", Collections.list("image/bpg"));
     MIMETYPE_MAPPING.put("bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("cb7", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cba", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbr", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbt", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbtc", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbz", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cc", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("cdr", Collections.list("application/coreldraw"));
     MIMETYPE_MAPPING.put("class", Collections.list("application/java"));
     MIMETYPE_MAPPING.put("cnf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("conf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("cpp", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("cr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("css", Collections.list("text/css"));
     MIMETYPE_MAPPING.put("csv", Collections.list("text/csv"));
     MIMETYPE_MAPPING.put("cvbdl", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("c", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("c++", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("dcr", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("deb", Collections.list("application/x-deb"));
     MIMETYPE_MAPPING.put("dng", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("doc", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("docm", Collections.list("application/vnd.ms-word.document.macroEnabled.12"));
     MIMETYPE_MAPPING.put("docx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
     MIMETYPE_MAPPING.put("dot", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("dotx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
     MIMETYPE_MAPPING.put("dv", Collections.list("video/dv"));
     MIMETYPE_MAPPING.put("eot", Collections.list("application/vnd.ms-fontobject"));
     MIMETYPE_MAPPING.put("epub", Collections.list("application/epub+zip"));
     MIMETYPE_MAPPING.put("eps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("erf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("exe", Collections.list("application/x-ms-dos-executable"));
     MIMETYPE_MAPPING.put("flac", Collections.list("audio/flac"));
     MIMETYPE_MAPPING.put("flv", Collections.list("video/x-flv"));
     MIMETYPE_MAPPING.put("gif", Collections.list("image/gif"));
     MIMETYPE_MAPPING.put("gpx", Collections.list("application/gpx+xml"));
     MIMETYPE_MAPPING.put("gz", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("gzip", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("h", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("heic", Collections.list("image/heic"));
     MIMETYPE_MAPPING.put("heif", Collections.list("image/heif"));
     MIMETYPE_MAPPING.put("hh", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("hpp", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("htaccess", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("ical", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("ics", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("iiq", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("impress", Collections.list("text/impress"));
     MIMETYPE_MAPPING.put("java", Collections.list("text/x-java-source"));
     MIMETYPE_MAPPING.put("jp2", Collections.list("image/jp2"));
     MIMETYPE_MAPPING.put("jpeg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jpg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jps", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("k25", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("kdc", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("key", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("keynote", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("kml", Collections.list("application/vnd.google-earth.kml+xml"));
     MIMETYPE_MAPPING.put("kmz", Collections.list("application/vnd.google-earth.kmz"));
     MIMETYPE_MAPPING.put("kra", Collections.list("application/x-krita"));
     MIMETYPE_MAPPING.put("ldif", Collections.list("text/x-ldif"));
     MIMETYPE_MAPPING.put("love", Collections.list("application/x-love-game"));
     MIMETYPE_MAPPING.put("lwp", Collections.list("application/vnd.lotus-wordpro"));
     MIMETYPE_MAPPING.put("m2t", Collections.list("video/mp2t"));
     MIMETYPE_MAPPING.put("m3u", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m3u8", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m4a", Collections.list("audio/mp4"));
     MIMETYPE_MAPPING.put("m4b", Collections.list("audio/m4b"));
     MIMETYPE_MAPPING.put("m4v", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("markdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("md", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("mdwn", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mkd", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("mkv", Collections.list("video/x-matroska"));
     MIMETYPE_MAPPING.put("mobi", Collections.list("application/x-mobipocket-ebook"));
     MIMETYPE_MAPPING.put("mov", Collections.list("video/quicktime"));
     MIMETYPE_MAPPING.put("mp3", Collections.list("audio/mpeg"));
     MIMETYPE_MAPPING.put("mp4", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("mpeg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpo", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("msi", Collections.list("application/x-msi"));
     MIMETYPE_MAPPING.put("mts", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("mt2s", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("nef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("numbers", Collections.list("application/x-iwork-numbers-sffnumbers"));
     MIMETYPE_MAPPING.put("odf", Collections.list("application/vnd.oasis.opendocument.formula"));
     MIMETYPE_MAPPING.put("odg", Collections.list("application/vnd.oasis.opendocument.graphics"));
     MIMETYPE_MAPPING.put("odp", Collections.list("application/vnd.oasis.opendocument.presentation"));
     MIMETYPE_MAPPING.put("ods", Collections.list("application/vnd.oasis.opendocument.spreadsheet"));
     MIMETYPE_MAPPING.put("odt", Collections.list("application/vnd.oasis.opendocument.text"));
     MIMETYPE_MAPPING.put("oga", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogg", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogv", Collections.list("video/ogg"));
     MIMETYPE_MAPPING.put("one", Collections.list("application/msonenote"));
     MIMETYPE_MAPPING.put("opus", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("orf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("otf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("pages", Collections.list("application/x-iwork-pages-sffpages"));
     MIMETYPE_MAPPING.put("pdf", Collections.list("application/pdf"));
     MIMETYPE_MAPPING.put("pfb", Collections.list("application/x-font"));
     MIMETYPE_MAPPING.put("pef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("php", Collections.list("application/x-php"));
     MIMETYPE_MAPPING.put("pl", Collections.list("application/x-perl"));
     MIMETYPE_MAPPING.put("pls", Collections.list("audio/x-scpls"));
     MIMETYPE_MAPPING.put("png", Collections.list("image/png"));
     MIMETYPE_MAPPING.put("pot", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("potm", Collections.list("application/vnd.ms-powerpoint.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("potx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.template"));
     MIMETYPE_MAPPING.put("ppa", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppam", Collections.list("application/vnd.ms-powerpoint.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pps", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppsm", Collections.list("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"));
     MIMETYPE_MAPPING.put("ppsx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.slideshow"));
     MIMETYPE_MAPPING.put("ppt", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("pptm", Collections.list("application/vnd.ms-powerpoint.presentation.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pptx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
     MIMETYPE_MAPPING.put("ps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("psd", Collections.list("application/x-photoshop"));
     MIMETYPE_MAPPING.put("py", Collections.list("text/x-python"));
     MIMETYPE_MAPPING.put("raf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("rar", Collections.list("application/x-rar-compressed"));
     MIMETYPE_MAPPING.put("reveal", Collections.list("text/reveal"));
     MIMETYPE_MAPPING.put("rss", Collections.list("application/rss+xml"));
     MIMETYPE_MAPPING.put("rtf", Collections.list("application/rtf"));
     MIMETYPE_MAPPING.put("rw2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("schema", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("sgf", Collections.list("application/sgf"));
     MIMETYPE_MAPPING.put("sh-lib", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("sh", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("srf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("sr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("tar", Collections.list("application/x-tar"));
     MIMETYPE_MAPPING.put("tar.bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tar.gz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tbz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tcx", Collections.list("application/vnd.garmin.tcx+xml"));
     MIMETYPE_MAPPING.put("tex", Collections.list("application/x-tex"));
     MIMETYPE_MAPPING.put("tgz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tiff", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("tif", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("ttf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("txt", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("vcard", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vcf", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vob", Collections.list("video/dvd"));
     MIMETYPE_MAPPING.put("vsd", Collections.list("application/vnd.visio"));
     MIMETYPE_MAPPING.put("vsdm", Collections.list("application/vnd.ms-visio.drawing.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vsdx", Collections.list("application/vnd.ms-visio.drawing"));
     MIMETYPE_MAPPING.put("vssm", Collections.list("application/vnd.ms-visio.stencil.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vssx", Collections.list("application/vnd.ms-visio.stencil"));
     MIMETYPE_MAPPING.put("vstm", Collections.list("application/vnd.ms-visio.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vstx", Collections.list("application/vnd.ms-visio.template"));
     MIMETYPE_MAPPING.put("wav", Collections.list("audio/wav"));
     MIMETYPE_MAPPING.put("webm", Collections.list("video/webm"));
     MIMETYPE_MAPPING.put("woff", Collections.list("application/font-woff"));
     MIMETYPE_MAPPING.put("wpd", Collections.list("application/vnd.wordperfect"));
     MIMETYPE_MAPPING.put("wmv", Collections.list("video/x-ms-wmv"));
     MIMETYPE_MAPPING.put("xcf", Collections.list("application/x-gimp"));
     MIMETYPE_MAPPING.put("xla", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlam", Collections.list("application/vnd.ms-excel.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xls", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlsb", Collections.list("application/vnd.ms-excel.sheet.binary.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsm", Collections.list("application/vnd.ms-excel.sheet.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
     MIMETYPE_MAPPING.put("xlt", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xltm", Collections.list("application/vnd.ms-excel.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xltx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.template"));
     MIMETYPE_MAPPING.put("xrf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("yaml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("yml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("zip", Collections.list("application/zip"));
     MIMETYPE_MAPPING.put("url", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("webloc", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("js", Arrays.asList("application/javascript", "text/plain"));
     MIMETYPE_MAPPING.put("json", Arrays.asList("application/json", "text/plain"));
     MIMETYPE_MAPPING.put("fb2", Arrays.asList("application/x-fictionbook+xml", "text/plain"));
     MIMETYPE_MAPPING.put("html", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("htm", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("m", Arrays.asList("text/x-matlab", "text/plain"));
     MIMETYPE_MAPPING.put("svg", Arrays.asList("image/svg+xml", "text/plain"));
     MIMETYPE_MAPPING.put("swf", Arrays.asList("application/x-shockwave-flash", "application/octet-stream"));
     MIMETYPE_MAPPING.put("xml", Arrays.asList("application/xml", "text/plain"));

}

SQL: How to properly check if a record exists

It's better to use either of the following:

-- Method 1.
SELECT 1
FROM table_name
WHERE unique_key = value;

-- Method 2.
SELECT COUNT(1)
FROM table_name
WHERE unique_key = value;

The first alternative should give you no result or one result, the second count should be zero or one.

How old is the documentation you're using? Although you've read good advice, most query optimizers in recent RDBMS's optimize SELECT COUNT(*) anyway, so while there is a difference in theory (and older databases), you shouldn't notice any difference in practice.

In c# is there a method to find the max of 3 numbers?

Maximum element value in priceValues[] is maxPriceValues :

double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();

django order_by query set, ascending and descending

  1. Ascending order

    Reserved.objects.all().filter(client=client_id).order_by('check_in')
    
  2. Descending order

    Reserved.objects.all().filter(client=client_id).order_by('-check_in')
    

- (hyphen) is used to indicate descending order here.

A server with the specified hostname could not be found

Turn off the push notification. Then,Restart your XCode and Turn back ON the Push Notification. It works for me.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))

How to detect installed version of MS-Office?

namespace Software_Info_v1._0
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop;

public class MS_Office
{
    public string GetOfficeVersion()
    {
        string sVersion = string.Empty;
        Microsoft.Office.Interop.Word.Application appVersion = new Microsoft.Office.Interop.Word.Application();
        appVersion.Visible = false;
        switch (appVersion.Version.ToString())
        {
            case "7.0":
                sVersion = "95";
                break;
            case "8.0":
                sVersion = "97";
                break;
            case "9.0":
                sVersion = "2000";
                break;
            case "10.0":
                sVersion = "2002";
                break;
            case "11.0":
                sVersion = "2003";
                break;
            case "12.0":
                sVersion = "2007";
                break;
            case "14.0":
                sVersion = "2010";
                break;
            default:
                sVersion = "Too Old!";
                break;
        }
        Console.WriteLine("MS office version: " + sVersion);
        return null;
    }



}
}

.htaccess redirect www to non-www with SSL/HTTPS

Ref: Apache redirect www to non-www and HTTP to HTTPS

http://example.com

http://www.example.com

https://www.example.com

to

https://example.com

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

.do extension in web pages?

I've occasionally thought that it might serve a purpose to add a layer of security by obscuring the back-end interpreter through a remapping of .php or whatever to .aspx or whatever so that any potential hacker would be sent down the wrong path, at least for a while. I never bothered to try it and I don't do a lot of webserver work any more so I'm unlikely to.

However, I'd be interested in the perspective of an experienced server admin on that notion.

Calculate rolling / moving average in C++

a simple moving average for 10 items, using a list:

#include <list>

std::list<float> listDeltaMA;

float getDeltaMovingAverage(float delta)
{
    listDeltaMA.push_back(delta);
    if (listDeltaMA.size() > 10) listDeltaMA.pop_front();
    float sum = 0;
    for (std::list<float>::iterator p = listDeltaMA.begin(); p != listDeltaMA.end(); ++p)
        sum += (float)*p;
    return sum / listDeltaMA.size();
}

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set AUTO_INCREMENT to PRIMARY KEY

How can I add comments in MySQL?

"A comment for a column can be specified with the COMMENT option. The comment is displayed by the SHOW CREATE TABLE and SHOW FULL COLUMNS statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"

As an example

--
-- Table structure for table 'accesslog'
--

CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry', 
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;

Is there a difference between "throw" and "throw ex"?

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

    static void Main(string[] args)
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace.ToString());
            Console.ReadKey();
        }
    }
    
    private static void Method2()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
            throw ex;
        }
    }
    
    private static void Method1()
    {
        try
        {
            throw new Exception("Inside Method1");
        }
        catch (Exception)
        {
            throw;
        }
    }
    

How to determine if a String has non-alphanumeric characters?

One approach is to do that using the String class itself. Let's say that your string is something like that:

String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);

Lollipop : draw behind statusBar with its color set to transparent

I will be adding some more information here. The latest Android developments have made it pretty easy to handle a lot of cases in status bar. Following are my observations from the styles.xml

  1. Background color: for SDK 21+, as a lot of answers mentioned,<item name="android:windowTranslucentStatus">true</item> will make the status bar transparent and show in front of UI. Your Activity will take the whole space of the top.
  2. Background color: again,for SDK 21+, <item name="android:statusBarColor">@color/your_color</item> will simply give a color to your status bar, without affecting anything else.

  3. However, in later devices (Android M/+), the icons started coming in different shades. The OS can give a darker shade of gray to the icons for SDK 23/+ , if you override your styles.xml file in values-23 folder and add <item name="android:windowLightStatusBar">true</item>.
    This way, you will be providing your user with a more visible status bar, if your status bar has a light color( think of how a lot of google apps have light background yet the icons are visible there in a greyish color).
    I would suggest you to use this, if you are giving color to your status bar via point #2

  4. In the most recent devices, SDK 29/+ comes with a system wide light and dark theme, controllable by the user. As devs, we are also supposed to override our style file in a new values-night folder, to give user 2 different experiences.
    Here again, I have found the point #2 to be effective in providing the "background color to status bar". But system was not changing the color of status bar icons for my app. since my day version of style consisted of lighter theme, this means that users will suffer from low visibility ( white icons on lighter background)
    This problem can be solved by using the point #3 approach or by overriding style file in values-29 folder and using a newer api <item name="android:enforceStatusBarContrast">true</item> . This will automatically enforce the grayish tint to icons, if your background color is too light.

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

<application 
    android:theme="@android:style/Theme.Holo"/>

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

<application 
    android:theme="@android:style/Theme.Black"/>

<application 
    android:theme="@android:style/Theme.DeviceDefault"/>

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

Check orientation on Android phone

You can use this (based on here) :

public static boolean isPortrait(Activity activity) {
    final int currentOrientation = getCurrentOrientation(activity);
    return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}

public static int getCurrentOrientation(Activity activity) {
    //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
    final Display display = activity.getWindowManager().getDefaultDisplay();
    final int rotation = display.getRotation();
    final Point size = new Point();
    display.getSize(size);
    int result;
    if (rotation == Surface.ROTATION_0
            || rotation == Surface.ROTATION_180) {
        // if rotation is 0 or 180 and width is greater than height, we have
        // a tablet
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a phone
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
    } else {
        // if rotation is 90 or 270 and width is greater than height, we
        // have a phone
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a tablet
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
        }
    }
    return result;
}

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

Automated testing for REST Api

One of the problems of doing automated testing for APIs is that many of the tools require you to have the API server up and running before you run your test suite. It can be a real advantage to have a unit testing framework that is capable of running and querying the APIs in a fully automated test environment.

An option that's good for APIs implemented with Node.JS / Express is to use mocha for automated testing. In addition to unit tests, its easy to write functional tests against the APIs, separated into different test suites. You can start up the API server automatically in the local test environment and set up a local test database. Using make, npm, and a build server, you can create a "make test" target and an incremental build that will run the entire test suite every time a piece of code is submitted to your repository. For the truly fastidious developer, it will even generate a nice HTML code-coverage report showing you which parts of your code base are covered by tests or not. If this sounds interesting, here's a blog post that provides all the technical details.

If you're not using node, then whatever the defacto unit testing framework for the language is (jUnit, cucumber/capybara, etc) - look at its support for spinning up servers in the local test environment and running the HTTP queries. If it's a large project, the effort to get automated API testing and continual integration working will pay off pretty quickly.

Hope that helps.

How to remove unwanted space between rows and columns in table?

I had this problem and none of the suggestions from several posts worked, I tried them all. My problem turned out that the table I was creating is nested in another table, inheriting on its properties. I needed to override the container table.

In this example, SuColTable is class on the table.

.SuColTable tr {
    border: none !important;
}

.SuColTable td {
    border-spacing: 0 !important;
    border: none !important;
    margin: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    padding-right: 0 !important;
}


.SuColTable {
    border-collapse: collapse !important;
    border: none !important;
    border-spacing: 0 !important;
    border-collapse: separate !important;
    padding-left: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
}
// all padding would be padding: 0 !important

The border-collapse, border:none and border-spacing get rid of table/row/column line. The padding 0 calls get rid the padding from the container table. I had to including !important on every style for it work, in order override the container table styles.

I have padding_top, left and bottom (instead of only padding) because I have two other classes that control the padding_right.

line-height: 0px;

Line-height zero makes the row one line high. If you have several lines, they are compressed into one line.

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

git checkout all the files

If you are at the root of your working directory, you can do git checkout -- . to check-out all files in the current HEAD and replace your local files.

You can also do git reset --hard to reset your working directory and replace all changes (including the index).

Mean per group in a data.frame

You can also accomplish this using the sqldf package as shown below:

library(sqldf)

x <- read.table(text='Name     Month  Rate1     Rate2
Aira       1      12        23
                Aira       2      18        73
                Aira       3      19        45
                Ben        1      53        19
                Ben        2      22        87
                Ben        3      19        45
                Cat        1      22        87
                Cat        2      67        43
                Cat        3      45        32', header=TRUE)

sqldf("
select 
  Name
  ,avg(Rate1) as Rate1_float
  ,avg(Rate2) as Rate2_float
  ,avg(Rate1) as Rate1
  ,avg(Rate2) as Rate2
from x
group by 
  Name
")

#  Name Rate1_float Rate2_float Rate1 Rate2
#1 Aira    16.33333    47.00000    16    47
#2  Ben    31.33333    50.33333    31    50
#3  Cat    44.66667    54.00000    44    54

I am a recent convert to dplyr as shown in other answers, but sqldf is nice as most data analysts/data scientists/developers have at least some fluency in SQL. In this way, I think it tends to make for more universally readable code than dplyr or other solutions presented above.

UPDATE: In responding to the comment below, I attempted to update the code as shown above. However, the behavior was not as I expected. It seems that the column definition (i.e. int vs float) is only carried through when the column alias matches the original column name. When you specify a new name, the aggregate column is returned without rounding.

Is it possible to run CUDA on AMD GPUs?

As of 2019_10_10 I have NOT tested it, but there is the "GPU Ocelot" project

http://gpuocelot.gatech.edu/

that according to its advertisement tries to compile CUDA code for a variety of targets, including AMD GPUs.

What is the purpose of .PHONY in a Makefile?

I often use them to tell the default target not to fire.

superclean: clean andsomethingelse

blah: superclean

clean:
   @echo clean

%:
   @echo catcher $@

.PHONY: superclean

Without PHONY, make superclean would fire clean, andsomethingelse, and catcher superclean; but with PHONY, make superclean won't fire the catcher superclean.

We don't have to worry about telling make the clean target is PHONY, because it isn't completely phony. Though it never produces the clean file, it has commands to fire so make will think it's a final target.

However, the superclean target really is phony, so make will try to stack it up with anything else that provides deps for the superclean target — this includes other superclean targets and the % target.

Note that we don't say anything at all about andsomethingelse or blah, so they clearly go to the catcher.

The output looks something like this:

$ make clean
clean

$ make superclean
clean
catcher andsomethingelse

$ make blah 
clean
catcher andsomethingelse
catcher blah

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

Access non-numeric Object properties by index?

You can use the Object.values() method if you dont want to use the Object.keys().

As opposed to the Object.keys() method that returns an array of a given object's own enumerable properties, so for instance:

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.keys(object1));

Would print out the following array:

[ 'a', 'b', 'c' ]

The Object.values() method returns an array of a given object's own enumerable property values.

So if you have the same object but use values instead,

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.values(object1));

You would get the following array:

[ 'somestring', 42, false ]

So if you wanted to access the object1.b, but using an index instead you could use:

Object.values(object1)[1] === 42

You can read more about this method here.

How to sort an array of integers correctly

I agree with aks, however instead of using

return a - b;

You should use

return a > b ? 1 : a < b ? -1 : 0;

jquery json to string?

The best way I have found is to use jQuery JSON

Using PHP variables inside HTML tags?

I recommend using the short ' instead of ". If you do so, you wont longer have to escape the double quote (\").

In that case you would write

echo '<a href="http://www.whatever.com/'. $param .'">Click Here</a>';

But look onto nicolaas' answer "what you really should do" to learn how to produce cleaner code.

How to pass a function as a parameter in Java?

I used the command pattern that @jk. mentioned, adding a return type:

public interface Callable<I, O> {

    public O call(I input);   
}

What is the best way to delete a value from an array in Perl?

I think your solution is the simplest and most maintainable.

The rest of the post documents the difficulty of turning tests on elements into splice offsets. Thus, making it a more complete answer.

Look at the gyrations you have to go through to have an efficient (i.e. one-pass) algorithm to turn tests on list items into indexes. And it's not that intuitive at all.

sub array_remove ( \@& ) { 
    my ( $arr_ref, $test_block ) = @_;
    my $sp_start  = 0;
    my $sp_len    = 0;
    for ( my $inx = 0; $inx <= $#$arr_ref; $inx++ ) {
        local $_ = $arr_ref->[$inx];
        next unless $test_block->( $_ );
        if ( $sp_len > 0 && $inx > $sp_start + $sp_len ) {
            splice( @$arr_ref, $sp_start, $sp_len );
            $inx    = $inx - $sp_len;
            $sp_len = 0;
        }
        $sp_start = $inx if ++$sp_len == 1;
    }
    splice( @$arr_ref, $sp_start, $sp_len ) if $sp_len > 0;
    return;
}

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

Bootstrap 4, How do I center-align a button?

In Bootstrap 4 one should use the text-center class to align inline-blocks.

NOTE: text-align:center; defined in a custom class you apply to your parent element will work regardless of the Bootstrap version you are using. And that's exactly what .text-center applies.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <button class="btn btn-default">Centered button</button>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


If the content to be centered is block or flex (not inline-), one could use flexbox to center it:

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="d-flex justify-content-center">_x000D_
  <button class="btn btn-default">Centered button</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

... which applies display: flex; justify-content: center to parent.

Note: don't use .row.justify-content-center instead of .d-flex.justify-content-center, as .row applies negative margins on certain responsiveness intervals, which results into unexpected horizontal scrollbars (unless .row is a direct child of .container, which applies lateral padding to counteract the negative margin, on the correct responsiveness intervals). If you must use .row, for whatever reason, override its margin and padding with .m-0.p-0, in which case you end up with pretty much the same styles as .d-flex.

Important note: The second solution is problematic when the centered content (the button) exceeds the width of the parent (.d-flex) especially when the parent has viewport width, specifically because it makes it impossible to horizontally scroll to the start of the content (left-most).
So don't use it when the content to be centered could become wider than the available parent width and all content should be accessible.

The backend version is not supported to design database diagrams or tables

I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:

USE [Database_Name]
GO

CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,

CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED 
(
[tableID] ASC
)
)

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

Display date/time in user's locale format and time offset

Once you have your date object constructed, here's a snippet for the conversion:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}

Python: how can I check whether an object is of type datetime.date?

If your existing code is already relying on from datetime import datetime, you can also simply also import date

from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)

In PHP how can you clear a WSDL cache?

Remove all wsdl* files in your /tmp folder on the server.

WSDL files are cached in your default location for all cache files defined in php.ini. Same location as your session files.

HTML5 canvas ctx.fillText won't do line breaks?

Canvas element doesn't support such characters as newline '\n', tab '\t' or < br /> tag.

Try it:

var newrow = mheight + 30;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line
ctx.fillText("play again", mwidth, newrow); //second line 

or perhaps multiple lines:

var textArray = new Array('line2', 'line3', 'line4', 'line5');
var rows = 98;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line

for(var i=0; i < textArray.length; ++i) {
rows += 30;
ctx.fillText(textArray[i], mwidth, rows); 
}  

MySQL: How to set the Primary Key on phpMyAdmin?

You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

After installing redis, type from terminal:

redis-server

And Redis-Server will be started

How to Find the Default Charset/Encoding in Java?

This is really strange... Once set, the default Charset is cached and it isn't changed while the class is in memory. Setting the "file.encoding" property with System.setProperty("file.encoding", "Latin-1"); does nothing. Every time Charset.defaultCharset() is called it returns the cached charset.

Here are my results:

Default Charset=ISO-8859-1
file.encoding=Latin-1
Default Charset=ISO-8859-1
Default Charset in Use=ISO8859_1

I'm using JVM 1.6 though.

(update)

Ok. I did reproduce your bug with JVM 1.5.

Looking at the source code of 1.5, the cached default charset isn't being set. I don't know if this is a bug or not but 1.6 changes this implementation and uses the cached charset:

JVM 1.5:

public static Charset defaultCharset() {
    synchronized (Charset.class) {
        if (defaultCharset == null) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                return cs;
            return forName("UTF-8");
        }
        return defaultCharset;
    }
}

JVM 1.6:

public static Charset defaultCharset() {
    if (defaultCharset == null) {
        synchronized (Charset.class) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                defaultCharset = cs;
            else
                defaultCharset = forName("UTF-8");
        }
    }
    return defaultCharset;
}

When you set the file encoding to file.encoding=Latin-1 the next time you call Charset.defaultCharset(), what happens is, because the cached default charset isn't set, it will try to find the appropriate charset for the name Latin-1. This name isn't found, because it's incorrect, and returns the default UTF-8.

As for why the IO classes such as OutputStreamWriter return an unexpected result,
the implementation of sun.nio.cs.StreamEncoder (witch is used by these IO classes) is different as well for JVM 1.5 and JVM 1.6. The JVM 1.6 implementation is based in the Charset.defaultCharset() method to get the default encoding, if one is not provided to IO classes. The JVM 1.5 implementation uses a different method Converters.getDefaultEncodingName(); to get the default charset. This method uses its own cache of the default charset that is set upon JVM initialization:

JVM 1.6:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Charset.defaultCharset().name();
    try {
        if (Charset.isSupported(csn))
            return new StreamEncoder(out, lock, Charset.forName(csn));
    } catch (IllegalCharsetNameException x) { }
    throw new UnsupportedEncodingException (csn);
}

JVM 1.5:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Converters.getDefaultEncodingName();
    if (!Converters.isCached(Converters.CHAR_TO_BYTE, csn)) {
        try {
            if (Charset.isSupported(csn))
                return new CharsetSE(out, lock, Charset.forName(csn));
        } catch (IllegalCharsetNameException x) { }
    }
    return new ConverterSE(out, lock, csn);
}

But I agree with the comments. You shouldn't rely on this property. It's an implementation detail.

jQuery/Javascript function to clear all the fields of a form

To reset form (but not clear the form) just trigger reset event:

$('#form').trigger("reset");

To clear a form see other answers.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status