Programs & Examples On #Doxia

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

This should fix the error

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.7</version>
     <dependencies>
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-filtering</artifactId>
             <version>1.3</version>
          </dependency>
      </dependencies>
</plugin>

How can I tell jaxb / Maven to generate multiple schema packages?

I encountered a lot of problems when using jaxb in Maven but i managed to solve your problem by doing the following

First create a schema.xjc file

<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema"
               jaxb:version="2.0">
    <jaxb:bindings schemaLocation="YOUR_URL?wsdl#types?schema1">
        <jaxb:schemaBindings>
            <jaxb:package name="your.package.name.schema1"/>
        </jaxb:schemaBindings>
    </jaxb:bindings>
    <jaxb:bindings schemaLocation="YOUR_URL??wsdl#types?schema2">
        <jaxb:schemaBindings>
            <jaxb:package name="your.package.name.schema2"/>
        </jaxb:schemaBindings>
    </jaxb:bindings>
</jaxb:bindings>

The package name can be anything you want it to be, as long as it doesn't contain any reserved keywords in Java

Next you have to create the wsimport.bat script to generate your packaged and code at the preferred location.

cd C:\YOUR\PATH\TO\PLACE\THE\PACKAGES
wsimport -keep -verbose -b "C:\YOUR\PATH\TO\schema.xjb" YOUR_URL?wsdl
pause

If you do not want to use cd, you can put the wsimport.bat in "C:\YOUR\PATH\TO\PLACE\THE\PACKAGES"

If you run it without -keep -verbose it will only generate the packages but not the .java files.

The -b will make sure the schema.xjc is used when generating

fileReader.readAsBinaryString to upload files

The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.

If you specifically want to send it as multipart/form-data, you can use a FormData object:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);

You can also send the data directly, instead of using multipart/form-data. See the documentation. Of course, this will need a server-side change as well.

// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);

xmlHttpRequest.setRequestHeader("Content-Type", file.type);

// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);

For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Use defaultValue and onChange like this

const [myValue, setMyValue] = useState('');

<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
                    
       <option>Option 1</option>
       <option>Option 2</option>
       <option>Option 3</option>

</select>

CSS background-image-opacity?

You can put a second element inside the element you wish to have a transparent background on.

<div class="container">
    <div class="container-background"></div>
    <div class="content">
         Yay, happy content!
    </div>
</div>

Then make the '.container-background' positioned absolutely to cover the parent element. At this point you'll be able to adjust the opacity of it without affecting the opacity of the content inside '.container'.

.container {
    position: relative;
}
.container .container-background {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: url(background.png);
    opacity: 0.5;
}
.container .content {
    position: relative;
    z-index: 1;
}

How do you parse and process HTML/XML in PHP?

I've created a library called HTML5DOMDocument that is freely available at https://github.com/ivopetkov/html5-dom-document-php

It supports query selectors too that I think will be extremely helpful in your case. Here is some example code:

$dom = new IvoPetkov\HTML5DOMDocument();
$dom->loadHTML('<!DOCTYPE html><html><body><h1>Hello</h1><div class="content">This is some text</div></body></html>');
echo $dom->querySelector('h1')->innerHTML;

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

git checkout master

That's result something like this:

Warning: you are leaving 2 commits behind, not connected to
any of your branches:

1e7822f readme
0116b5b returned to clean django

If you want to keep them by creating a new branch, this may be a good time to do so with:
git branch new_branch_name 1e7822f25e376d6a1182bb86a0adf3a774920e1e

So, let's do it:

git merge 1e7822f25e376d6a1182bb86a0adf3a774920e1e

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

How to get values and keys from HashMap?

Use the 'string' key of the hashmap, to access its value which is your tab class.

Tab mytab = hash.get("your_string_key_used_to_insert");

Makefile, header dependencies

A slightly modified version of Sophie's answer which allows to output the *.d files to a different folder (I will only paste the interesting part that generates the dependency files):

$(OBJDIR)/%.o: %.cpp
# Generate dependency file
    mkdir -p $(@D:$(OBJDIR)%=$(DEPDIR)%)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM -MT $@ $< -MF $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d)
# Generate object file
    mkdir -p $(@D)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $< -o $@

Note that the parameter

-MT $@

is used to ensure that the targets (i.e. the object file names) in the generated *.d files contain the full path to the *.o files and not just the file name.

I don't know why this parameter is NOT needed when using -MMD in combination with -c (as in Sophie's version). In this combination it seems to write the full path of the *.o files into the *.d files. Without this combination, -MMD also writes only the pure file names without any directory components into the *.d files. Maybe somebody knows why -MMD writes the full path when combined with -c. I have not found any hint in the g++ man page.

Properly close mongoose's connection once you're done

You can set the connection to a variable then disconnect it when you are done:

var db = mongoose.connect('mongodb://localhost:27017/somedb');

// Do some stuff

db.disconnect();

Newline in string attribute

<TextBlock>
    Stuff on line1 <LineBreak/>
    Stuff on line2
</TextBlock>

not that it's important to know but what you specify between the TextBlock tags is called inline content and goes into the TextBlock.Inlines property which is a InlineCollection and contains items of type Inline. Subclasses of Inline are Run and LineBreak, among others. see TextBlock.Inlines

Automatically create requirements.txt

I blindly followed the accepted answer of using pip3 freeze > requirements.txt

It generated a huge file that listed all the dependencies of the entire solution, which is not what I wanted.

So you need to figure out what sort of requirements.txt you are trying to generate.

If you need a requirements.txt file that has ALL the dependencies, then use the pip3

pip3 freeze > requirements.txt

However, if you want to generate a minimal requirements.txt that only lists the dependencies you need, then use the pipreqs package. Especially helpful if you have numerous requirements.txt files in per component level in the project and not a single file on the solution wide level.

pip install pipreqs
pipreqs [path to folder]
e.g. pipreqs .

C split a char array into different variables

#include<string.h>
#include<stdio.h>
int main()
{
    char input[16] = "abc,d";
    char *p;
    p = strtok(input, ",");

    if(p)
    {
    printf("%s\n", p);
    }
    p = strtok(NULL, ",");

    if(p)
           printf("%s\n", p);
    return 0;
}

you can look this program .First you should use the strtok(input, ",").input is the string you want to spilt.Then you use the strtok(NULL, ","). If the return value is true ,you can print the other group.

React Native Responsive Font Size

We use a simple, straight-forward, scaling utils functions we wrote:

import { Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');

//Guideline sizes are based on standard ~5" screen mobile device
const guidelineBaseWidth = 350;
const guidelineBaseHeight = 680;

const scale = size => width / guidelineBaseWidth * size;
const verticalScale = size => height / guidelineBaseHeight * size;
const moderateScale = (size, factor = 0.5) => size + ( scale(size) - size ) * factor;

export {scale, verticalScale, moderateScale};

Saves you some time doing many ifs. You can read more about it on my blog post.


Edit: I thought it might be helpful to extract these functions to their own npm package, I also included ScaledSheet in the package, which is an automatically scaled version of StyleSheet. You can find it here: react-native-size-matters.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

Whether a variable is undefined

if (var === undefined)

or more precisely

if (typeof var === 'undefined')

Note the === is used

Actual meaning of 'shell=True' in subprocess

>>> import subprocess
>>> subprocess.call('echo $HOME')
Traceback (most recent call last):
...
OSError: [Errno 2] No such file or directory
>>>
>>> subprocess.call('echo $HOME', shell=True)
/user/khong
0

Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command. In other words, using an intermediate shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run. Here, in the example, $HOME was processed before the echo command. Actually, this is the case of command with shell expansion while the command ls -l considered as a simple command.

source: Subprocess Module

Formatting MM/DD/YYYY dates in textbox in VBA

While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...

to accomplish what you need to do, with minimal changes to your code, there are two approaches.

  1. Use KeyUp() event instead of Change event for the textbox. Here is an example:

    Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    
        Dim TextStr As String
        TextStr = TextBox2.Text
    
        If KeyCode <> 8 Then ' i.e. not a backspace
    
            If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
                TextStr = TextStr & "/"
            End If
    
        End If
        TextBox2.Text = TextStr
    End Sub
    
  2. Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as

    12072003
    

while the result as he's typing appears as

    12/07/2003

But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.

    Private Sub TextBox1_Change()
        Dim TextStr As String

        TextStr = TextBox1.Text

        If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
            TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
        ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
            TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
        End If

        TextBox1.Text = TextStr
    End Sub

Decimal values in SQL for dividing results

Just another approach:

SELECT col1 * 1.0 / col2 FROM tbl1

Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.

A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:

SELECT col1 * 1. / col2 FROM tbl1

The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).

Principal advantage: less wordy than other approaches.

Peak signal detection in realtime timeseries data

Here is the Python / numpy implementation of the smoothed z-score algorithm (see answer above). You can find the gist here.

#!/usr/bin/env python
# Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
import numpy as np
import pylab

def thresholding_algo(y, lag, threshold, influence):
    signals = np.zeros(len(y))
    filteredY = np.array(y)
    avgFilter = [0]*len(y)
    stdFilter = [0]*len(y)
    avgFilter[lag - 1] = np.mean(y[0:lag])
    stdFilter[lag - 1] = np.std(y[0:lag])
    for i in range(lag, len(y)):
        if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]:
            if y[i] > avgFilter[i-1]:
                signals[i] = 1
            else:
                signals[i] = -1

            filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1]
            avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])
            stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])
        else:
            signals[i] = 0
            filteredY[i] = y[i]
            avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])
            stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])

    return dict(signals = np.asarray(signals),
                avgFilter = np.asarray(avgFilter),
                stdFilter = np.asarray(stdFilter))

Below is the test on the same dataset that yields the same plot as in the original answer for R/Matlab

# Data
y = np.array([1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1])

# Settings: lag = 30, threshold = 5, influence = 0
lag = 30
threshold = 5
influence = 0

# Run algo with settings from above
result = thresholding_algo(y, lag=lag, threshold=threshold, influence=influence)

# Plot result
pylab.subplot(211)
pylab.plot(np.arange(1, len(y)+1), y)

pylab.plot(np.arange(1, len(y)+1),
           result["avgFilter"], color="cyan", lw=2)

pylab.plot(np.arange(1, len(y)+1),
           result["avgFilter"] + threshold * result["stdFilter"], color="green", lw=2)

pylab.plot(np.arange(1, len(y)+1),
           result["avgFilter"] - threshold * result["stdFilter"], color="green", lw=2)

pylab.subplot(212)
pylab.step(np.arange(1, len(y)+1), result["signals"], color="red", lw=2)
pylab.ylim(-1.5, 1.5)
pylab.show()

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

Using subprocess to run Python script on Windows

When you are running a python script on windows in subprocess you should use python in front of the script name. Try:

process = subprocess.Popen("python /the/script.py")

How do I convert hex to decimal in Python?

You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100

Permission denied when launch python script via bash

You should be able to run the script typing:

$ chmod 755 ./scripts/replace-md5sums.py
$ ./scripts/replace-md5sums.py

There are times where the user you are currently logged with just don't have the permission to change file mode bits. In such cases if you have the root password you can change the file permission this way:

$ sudo chmod 755 ./scripts/replace-md5sums.py

SQL Server - Convert date field to UTC

I do not believe the above code will work. The reason is that it depends upon the difference between the current date in local and UTC times. For example, here in California we are now in PDT (Pacific Daylight Time); the difference between this time and UTC is 7 hours. The code provided will, if run now, add 7 hours to every date which is desired to be converted. But if a historical stored date, or a date in the future, is converted, and that date is not during daylight savings time, it will still add 7, when the correct offset is 8. Bottom line: you cannot convert date/times properly between time zones (including UTC, which does not obey daylight savings time) by only looking at the current date. You must consider the date itself that you are converting, as to whether daylight time was in force on that date. Furthermore, the dates at which daylight and standard times change themselves have changed (George Bush changed the dates during his administration for the USA!). In other words, any solution which even references getdate() or getutcdate() does not work. It must parse the actual date to be converted.

Retrieve the position (X,Y) of an HTML element relative to the browser window

The cleanest approach I have found is a simplified version of the technique used by jQuery's offset. Similar to some of the other answers it starts with getBoundingClientRect; it then uses the window and the documentElement to adjust for scroll position as well as things like the margin on the body (often the default).

var rect = el.getBoundingClientRect();
var docEl = document.documentElement;

var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;

_x000D_
_x000D_
var els = document.getElementsByTagName("div");_x000D_
var docEl = document.documentElement;_x000D_
_x000D_
for (var i = 0; i < els.length; i++) {_x000D_
_x000D_
  var rect = els[i].getBoundingClientRect();_x000D_
_x000D_
  var rectTop = rect.top + window.pageYOffset - docEl.clientTop;_x000D_
  var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;_x000D_
_x000D_
  els[i].innerHTML = "<b>" + rectLeft + ", " + rectTop + "</b>";_x000D_
}
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: red;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#rel {_x000D_
  position: relative;_x000D_
  left: 10px;_x000D_
  top: 10px;_x000D_
}_x000D_
#abs {_x000D_
  position: absolute;_x000D_
  top: 250px;_x000D_
  left: 250px;_x000D_
}
_x000D_
<div id="rel"></div>_x000D_
<div id="abs"></div>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How do I prevent Conda from activating the base environment by default?

The answer depends a little bit on the version of conda that you have installed. For versions of conda >= 4.4, it should be enough to deactivate the conda environment after the initialization, so add

conda deactivate

right underneath

# <<< conda initialize <<<

PHP call Class method / function

$f = new Functions;
$var = $f->filter($_GET['params']);

Have a look at the PHP manual section on Object Oriented programming

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]

text.replace(/[\W_]+/g," ");

\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)

Example at regex101.com

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

How to use a class object in C++ as a function parameter

I was asking the same too. Another solution is you could overload your method:

void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);

in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself

void remove_id(EmployeeClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(ProductClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(DepartmentClass _obj) {
    int saveId = _obj->id;
    ...
};

C++, copy set to vector

You need to use a back_inserter:

std::copy(input.begin(), input.end(), std::back_inserter(output));

std::copy doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at least large enough to hold the input range.

std::back_inserter creates an output iterator that calls push_back on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector to hold the range being copied:

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Or, you could use the std::vector range constructor:

std::vector<double> output(input.begin(), input.end()); 

Export DataBase with MySQL Workbench with INSERT statements

For the latest version of MySql Workbench

  1. Click on the Server menu in the top menu bar
  2. Select 'Data Export' submenu
  3. It will open up the Object Selection window where you can select the appropriate database which has the desired tables
  4. Once you select the database in the left side all the tables will appear in the right side with radio buttons
  5. Select the radio buttons in front of needed tables
  6. Just below the table selection you can see a dropdown to select Dump Structure Only or Data only or Structure & Data
  7. Under Objects to Export tick the box if you need stored procedures or events also. If you don't need those then untick those
  8. Under export option change the exporting file name and path
  9. If you want to create the schema once you import the dump file then tick include create schema
  10. Press Start Export button in the right-hand side corner. once it successful the summary will be showing in the Export progress tab

How to set a default value with Html.TextBoxFor?

Here's how I solved it. This works if you also use this for editing.

@Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })

Modal width (increase)

The following solution will work for Bootstrap 4.

.modal .modal-dialog {
  max-width: 850px;
}

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I normally use action="", which is XHTML valid and retains the GET data in the URL.

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Why do table names in SQL Server start with "dbo"?

It's new to SQL 2005 and offers a simplified way to group objects, especially for the purpose of securing the objects in that "group".

The following link offers a more in depth explanation as to what it is, why we would use it:

Understanding the Difference between Owners and Schemas in SQL Server

Are duplicate keys allowed in the definition of binary search trees?

1.) left <= root < right

2.) left < root <= right

3.) left < root < right, such that no duplicate keys exist.

I might have to go and dig out my algorithm books, but off the top of my head (3) is the canonical form.

(1) or (2) only come about when you start to allow duplicates nodes and you put duplicate nodes in the tree itself (rather than the node containing a list).

bootstrap responsive table content wrapping

Add your new class "tableresp" with table-responisve class and then add below code in your js file

$(".tableresp").on('click', '.dropdown-toggle', function(event) {

    if ($('.dropdown-menu').length) {
        var elm = $('.dropdown-menu'),
            docHeight = $(document).height(),
            docWidth = $(document).width(),
            btn_offset = $(this).offset(),
            btn_width = $(this).outerWidth(),
            btn_height = $(this).outerHeight(),
            elm_width = elm.outerWidth(),
            elm_height = elm.outerHeight(),
            table_offset = $(".tableresp").offset(),
            table_width = $(".tableresp").width(),
            table_height = $(".tableresp").height(),

            tableoffright = table_width + table_offset.left,
            tableoffbottom = table_height + table_offset.top,
            rem_tablewidth = docWidth - tableoffright,
            rem_tableheight = docHeight - tableoffbottom,
            elm_offsetleft = btn_offset.left,
            elm_offsetright = btn_offset.left + btn_width,
            elm_offsettop = btn_offset.top + btn_height,
            btn_offsetbottom = elm_offsettop,

            left_edge = (elm_offsetleft - table_offset.left) < elm_width,
            top_edge = btn_offset.top < elm_height,
            right_edge = (table_width - elm_offsetleft) < elm_width,
            bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;

        console.log(tableoffbottom);
        console.log(btn_offsetbottom);
        console.log(bottom_edge);
        console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);


        var table_offset_bottom = docHeight - (table_offset.top + table_height);

        var touchTableBottom = (btn_offset.top + btn_height + (elm_height * 2)) - table_offset.top;

        var bottomedge = touchTableBottom > table_offset_bottom;

        if (left_edge) {
            $(this).addClass('left-edge');
        } else {
            $('.dropdown-menu').removeClass('left-edge');
        }
        if (bottom_edge) {
            $(this).parent().addClass('dropup');
        } else {
            $(this).parent().removeClass('dropup');
        }

    }
});
var table_smallheight = $('.tableresp'),
    positioning = table_smallheight.parent();

if (table_smallheight.height() < 320) {
    positioning.addClass('positioning');
    $('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');

} else {
    positioning.removeClass('positioning');
    $('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');

}

Entity Framework: There is already an open DataReader associated with this Command

It is not about closing connection. EF manages connection correctly. My understanding of this problem is that there are multiple data retrieval commands executed on single connection (or single command with multiple selects) while next DataReader is executed before first one has completed the reading. The only way to avoid the exception is to allow multiple nested DataReaders = turn on MultipleActiveResultSets. Another scenario when this always happens is when you iterate through result of the query (IQueryable) and you will trigger lazy loading for loaded entity inside the iteration.

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

How do I combine two dataframes?

You can also use pd.concat, which is particularly helpful when you are joining more than two dataframes:

bigdata = pd.concat([data1, data2], ignore_index=True, sort=False)

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

You pretty much can't set the value of found. Debugging optimized programs is rarely worth the trouble, the compiler can rearrange the code in ways that it'll in no way correspond to the source code (other than producing the same result), thus confusing debuggers to no end.

How to reset form body in bootstrap modal box?

Just set the empty values to the input fields when modal is hiding.

$('#Modal_Id').on('hidden', function () {
   $('#Form_Id').find('input[type="text"]').val('');
});

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

Where can I get a list of Countries, States and Cities?

Geonames has a lot of data on places (including towns and cities) but it seems to be contributed and perhaps not complete.

Perhaps also try SQL Dumpster, I've used this website a lot for these kinds of databases, cities, provinces, etc. Unfortunately it's not free but only appears to be a one-time fee.

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

python paramiko ssh

###### Use paramiko to connect to LINUX platform############
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp) # Output 

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";

    if (controller == "Webmaster")
        cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
    else
        cLayout = "~/Views/Shared/_Layout.cshtml";

    Layout = cLayout;
}

Read Complete Article here "How to Render different Layout in ASP.NET MVC"

Getting Textbox value in Javascript

        <script type="text/javascript">
            function MyFunction() {
                var FNumber = Number(document.getElementById('txtFirstNumber').value);
                var SNumber = Number(document.getElementById("txtSecondNumber").value);
                var Sum = FNumber + SNumber;
                alert(Sum);
            }

        </script>

        <table class="auto-style1">
            <tr>
                <td>FirstNaumber</td>
                <td>
                    <asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>SecondNumber</td>
                <td>
                    <asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
                </td>
            </tr>
        </table>
    </div>
</form>

What is the difference between const and readonly in C#?

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.

public class MyClass
{
    public const double PI1 = 3.14159;
}

A readonly member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor, as well being able to be initialized as they are declared.

public class MyClass1
{
     public readonly double PI2 = 3.14159;

     //or

     public readonly double PI3;

     public MyClass2()
     {
         PI3 = 3.14159;
     }
}

const

  • They can not be declared as static (they are implicitly static)
  • The value of constant is evaluated at compile time
  • constants are initialized at declaration only

readonly

  • They can be either instance-level or static
  • The value is evaluated at run time
  • readonly can be initialized in declaration or by code in the constructor

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

PHP Warning: PHP Startup: ????????: Unable to initialize module

In my case, with Windows Server 2008, I had to change the PATH variable. The former version of PHP (VC9) was inside it.

I have changed it with the newer version of PHP (VC11).

After a restart of Apache, it was okay.

virtualenvwrapper and Python 3

I added export VIRTUALENV_PYTHON=/usr/bin/python3 to my ~/.bashrc like this:

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENV_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

then run source .bashrc

and you can specify the python version for each new env mkvirtualenv --python=python2 env_name

jQuery Validate Required Select

An easier solution has been outlined here: Validate select box

Make the value be empty and add the required attribute

<select id="select" class="required">
<option value="">Choose an option</option> 
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

How to use refs in React with Typescript

Just to add a different approach - you can simply cast your ref, something like:

let myInputElement: Element = this.refs["myInput"] as Element

How to find the size of an int[]?

Since you've marked this as C++, it's worth mentioning that there is a somewhat better way than the C-style macro:

template <class T, size_t N>
size_t countof(const T &array[N]) { return N; }

This has the advantage that if you accidentally try to pass something other than an array to it, the code simply won't compile (whereas passing a pointer to the C macro will compile but produce a bad result. The disadvantage is that this doesn't give you a compile-time constant, so you can't do something like this:

int a[20];

char x[countof(a)];

In C++11 or newer, you can add constexpr to get a compile-time constant:

template <class T, size_t N>
constexpr size_t countof(const T &array[N]) { return N; }

If you really want to support the same on older compilers, there is a way, originally invented by Ivan Johnson, AFAIK:

#define COUNTOF(x)  (                                           \
  0 * sizeof( reinterpret_cast<const ::Bad_arg_to_COUNTOF*>(x) ) +  \
  0 * sizeof( ::Bad_arg_to_COUNTOF::check_type((x), &(x))      ) +  \
  sizeof(x) / sizeof((x)[0])  )                                  


class Bad_arg_to_COUNTOF
{
public:
   class Is_pointer;
   class Is_array {};  
   template<typename T>
   static Is_pointer check_type(const T*, const T* const*);
   static Is_array check_type(const void*, const void*);
};

This uses sizeof(x)/sizeof(x[0]) to compute the size, just like the C macro does, so it gives a compile-time constant. The difference is that it first uses some template magic to cause a compile error if what you've passed isn't the name of an array. It does that by overloading check_type to return an incomplete type for a pointer, but a complete type for an array. Then (the really tricky part) it doesn't actually call that function at all -- it just takes the size of the type the function would return, which is zero for the overload that returns the complete type, but not allowed (forcing a compile error) for the incomplete type.

IMO, that's a pretty cool example of template meta programming -- though in all honesty, the result is kind of pointless. You really only need that size as a compile time constant if you're using arrays, which you should normally avoid in any case. Using std::vector, it's fine to supply the size at run-time (and resize the vector when/if needed).

Writing new lines to a text file in PowerShell

You can use the Environment class's static NewLine property to get the proper newline:

$errorMsg =  "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
               (Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg

How to create EditText with cross(x) button at end of it?

Clear text:

"Text field with a clear text trailing icon."

If set, an icon is displayed when text is present and pressing it clears the input text.

    ...
    app:endIconMode="clear_text">
?
    ...
?
</com.google.android.material.textfield.TextInputLayout>

I leave it here:

material.io

Example
example

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

C# Pass Lambda Expression as Method Parameter

You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action and Func.

In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

P.S. You should use PascalCase for method names - GetJobs, not getJobs.

Can an abstract class have a constructor?

Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.

How can I change the font-size of a select option?

check this fiddle,

i just edited the above fiddle, its working

http://jsfiddle.net/narensrinivasans/FpNxn/1/

.selectDefault, .selectDiv option
{
    font-family:arial;
    font-size:12px;
}

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

How to get images in Bootstrap's card to be the same height/width?

Try this in your css:

.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}

Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.

Alternate table row color using CSS?

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

How to check if a string starts with one of several prefixes?

A simple solution is:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...

A fancier solution would be:

List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
    // ...
}

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

Maximum call stack size exceeded error

There is a recursive loop somewhere in your code (i.e. a function that eventually calls itself again and again until the stack is full).

Other browsers either have bigger stacks (so you get a timeout instead) or they swallow the error for some reason (maybe a badly placed try-catch).

Use the debugger to check the call stack when the error happens.

Sum the digits of a number

Here is the best solution I found:

function digitsum(n) {
    n = n.toString();
    let result = 0;
    for (let i = 0; i < n.length; i++) {
        result += parseInt(n[i]);
    }
    return result;
}
console.log(digitsum(192));

Why do we need to install gulp globally and locally?

TLDR; Here's why:

The reason this works is because gulp tries to run your gulpfile.js using your locally installed version of gulp, see here. Hence the reason for a global and local install of gulp.

Essentially, when you install gulp locally the script isn't in your PATH and so you can't just type gulp and expect the shell to find the command. By installing it globally the gulp script gets into your PATH because the global node/bin/ directory is most likely on your path.

To respect your local dependencies though, gulp will use your locally installed version of itself to run the gulpfile.js.

not finding android sdk (Unity)

For Mac OS Users :

Go to your Android SDK folder and delete the tools folder (I recommend you to make a copy before deleting it, in case this solution does not solve the problem for you)

Then download the tools folder here :

http://dl-ssl.google.com/android/repository/tools_r25.2.5-macosx.zip

You can find all tools zip version here :

https://androidsdkoffline.blogspot.fr/p/android-sdk-build-tools.html

Then unzip the download file and place it in the Android sdk folder.

Hope it helps

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

Jasmine JavaScript Testing - toBe vs toEqual

I think toEqual is checking deep equal, toBe is the same reference of 2 variable

  it('test me', () => {
    expect([] === []).toEqual(false) // true
    expect([] == []).toEqual(false) // true

    expect([]).toEqual([]); // true // deep check
    expect([]).toBe([]); // false
  })

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I do not know if this is a bug from Google or an intended behavior but I (at least momentarily) solved it by changing compileSdkVersion and targetSdkVersion back to 26 in Gradle...

Create a new line in Java's FileWriter

Since 1.8, I thought this might be an additional solution worth adding to the responses:

Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException

StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());

If appending to the same file, perhaps use an Append flag with Files.write()

Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

link button property to open in new tab?

When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.

try

lbnkVidTtile1.Enabled = true;

I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.

how to deal with google map inside of a hidden div (Updated picture)

I've found this to work for me:

to hide:

$('.mapWrapper')
.css({
  visibility: 'hidden',
  height: 0
});

to show:

    $('.mapWrapper').css({
      visibility: 'visible',
      height: 'auto'
    });

What are the differences between numpy arrays and matrices? Which one should I use?

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product.

import numpy as np

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.

In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise (except for the new @ operator). Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot (or @ in Python >= 3.5, as shown above):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise.

There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).

The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.

Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.

In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.

If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.

PS. Of course, you really don't have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).


There is a synopsis of the differences between NumPy arrays vs NumPy matrixes here.

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

bodyParser is deprecated express 4

I found that while adding

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

helps, sometimes it's a matter of your querying that determines how express handles it.

For instance, it could be that your parameters are passed in the URL rather than in the body

In such a case, you need to capture both the body and url parameters and use whichever is available (with preference for the body parameters in the case below)

app.route('/echo')
    .all((req,res)=>{
        let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
        res.send(pars);
    });

data.table vs dplyr: can one do something well the other can't or does poorly?

We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed, Memory usage, Syntax and Features.

My intent is to cover each one of these as clearly as possible from data.table perspective.

Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.


The data.table syntax is consistent in its form - DT[i, j, by]. To keep i, j and by together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.

1. Speed

Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas. See also updated benchmarks, which include Spark and pydatatable as well.

On benchmarks, it would be great to cover these remaining aspects as well:

  • Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z] type operations.

  • Benchmark other operations such as update and joins.

  • Also benchmark memory footprint for each operation in addition to runtime.

2. Memory usage

  1. Operations involving filter() or slice() in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.

    Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.

  2. data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).

    # sub-assign by reference, updates 'y' in-place
    DT[x >= 1L, y := NA]
    

    But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):

    # copies the entire 'y' column
    ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
    

    A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.

    Therefore we are working towards exporting shallow() function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:

    foo <- function(DT) {
        DT = shallow(DT)          ## shallow copy DT
        DT[, newcol := 1L]        ## does not affect the original DT 
        DT[x > 2L, newcol := 2L]  ## no need to copy (internally), as this column exists only in shallow copied DT
        DT[x > 2L, x := 3L]       ## have to copy (like base R / dplyr does always); otherwise original DT will 
                                  ## also get modified.
    }
    

    By not using shallow(), the old functionality is retained:

    bar <- function(DT) {
        DT[, newcol := 1L]        ## old behaviour, original DT gets updated by reference
        DT[x > 2L, x := 3L]       ## old behaviour, update column x in original DT.
    }
    

    By creating a shallow copy using shallow(), we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.

    Also, once shallow() is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.

    But it will still lack many features that data.table provides, including (sub)-assignment by reference.

  3. Aggregate while joining:

    Suppose you have two data.tables as follows:

    DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
    #    x y z
    # 1: 1 a 1
    # 2: 1 a 2
    # 3: 1 b 3
    # 4: 1 b 4
    # 5: 2 a 5
    # 6: 2 a 6
    # 7: 2 b 7
    # 8: 2 b 8
    DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
    #    x y mul
    # 1: 1 a   4
    # 2: 2 b   3
    

    And you would like to get sum(z) * mul for each row in DT2 while joining by columns x,y. We can either:

    • 1) aggregate DT1 to get sum(z), 2) perform a join and 3) multiply (or)

      # data.table way
      DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
      
      # dplyr equivalent
      DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
          right_join(DF2) %>% mutate(z = z * mul)
      
    • 2) do it all in one go (using by = .EACHI feature):

      DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
      

    What is the advantage?

    • We don't have to allocate memory for the intermediate result.

    • We don't have to group/hash twice (one for aggregation and other for joining).

    • And more importantly, the operation what we wanted to perform is clear by looking at j in (2).

    Check this post for a detailed explanation of by = .EACHI. No intermediate results are materialised, and the join+aggregate is performed all in one go.

    Have a look at this, this and this posts for real usage scenarios.

    In dplyr you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).

  4. Update and joins:

    Consider the data.table code shown below:

    DT1[DT2, col := i.mul]
    

    adds/updates DT1's column col with mul from DT2 on those rows where DT2's key column matches DT1. I don't think there is an exact equivalent of this operation in dplyr, i.e., without avoiding a *_join operation, which would have to copy the entire DT1 just to add a new column to it, which is unnecessary.

    Check this post for a real usage scenario.

To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!

3. Syntax

Let's now look at syntax. Hadley commented here:

Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...

I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.

We will work with the dummy data shown below:

DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
  1. Basic aggregation/update operations.

    # case (a)
    DT[, sum(y), by = z]                       ## data.table syntax
    DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
    DT[, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
    
    # case (b)
    DT[x > 2, sum(y), by = z]
    DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
    DT[x > 2, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
    
    # case (c)
    DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
    DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
    DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
    DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
    
    • data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).

    • In case (b), we had to use filter() in dplyr while summarising. But while updating, we had to move the logic inside mutate(). In data.table however, we express both operations with the same logic - operate on rows where x > 2, but in first case, get sum(y), whereas in the second case update those rows for y with its cumulative sum.

      This is what we mean when we say the DT[i, j, by] form is consistent.

    • Similarly in case (c), when we have if-else condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if condition satisfies and skip otherwise, we cannot use summarise() directly (AFAICT). We have to filter() first and then summarise because summarise() always expects a single value.

      While it returns the same result, using filter() here makes the actual operation less obvious.

      It might very well be possible to use filter() in the first case as well (does not seem obvious to me), but my point is that we should not have to.

  2. Aggregation / update on multiple columns

    # case (a)
    DT[, lapply(.SD, sum), by = z]                     ## data.table syntax
    DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
    DT[, (cols) := lapply(.SD, sum), by = z]
    ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
    
    # case (b)
    DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
    DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
    
    # case (c)
    DT[, c(.N, lapply(.SD, sum)), by = z]     
    DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
    
    • In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply(), whereas dplyr introduces *_each() along with a bunch of functions to funs().

    • data.table's := requires column names to be provided, whereas dplyr generates it automatically.

    • In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.

    • In case (c) though, dplyr would return n() as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c() to concatenate .N to a list which returns a list.

    Note: Once again, in data.table, all we need to do is return a list in j. Each element of the list will become a column in result. You can use c(), as.list(), lapply(), list() etc... base functions to accomplish this, without having to learn any new functions.

    You will need to learn just the special variables - .N and .SD at least. The equivalent in dplyr are n() and .

  3. Joins

    dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by] (and with reason). It also provides an equivalent merge.data.table() function as an alternative.

    setkey(DT1, x, y)
    
    # 1. normal join
    DT1[DT2]            ## data.table syntax
    left_join(DT2, DT1) ## dplyr syntax
    
    # 2. select columns while join    
    DT1[DT2, .(z, i.mul)]
    left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
    
    # 3. aggregate while join
    DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
    DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
        inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
    
    # 4. update while join
    DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
    ??
    
    # 5. rolling join
    DT1[DT2, roll = -Inf]
    ??
    
    # 6. other arguments to control output
    DT1[DT2, mult = "first"]
    ??
    
    • Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by], or merge() which is similar to base R.

    • However dplyr joins do just that. Nothing more. Nothing less.

    • data.tables can select columns while joining (2), and in dplyr you will need to select() first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.

    • data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI feature. Why materialse the entire join result to add/update just a few columns?

    • data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.

    • data.table also has mult = argument which selects first, last or all matches (6).

    • data.table has allow.cartesian = TRUE argument to protect from accidental invalid joins.

Once again, the syntax is consistent with DT[i, j, by] with additional arguments allowing for controlling the output further.

  1. do()...

    dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do(). You have to know beforehand about all your functions return value.

    DT[, list(x[1], y[1]), by = z]                 ## data.table syntax
    DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
    DT[, list(x[1:2], y[1]), by = z]
    DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
    
    DT[, quantile(x, 0.25), by = z]
    DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
    DT[, quantile(x, c(0.25, 0.75)), by = z]
    DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
    
    DT[, as.list(summary(x)), by = z]
    DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
    
    • .SD's equivalent is .

    • In data.table, you can throw pretty much anything in j - the only thing to remember is for it to return a list so that each element of the list gets converted to a column.

    • In dplyr, cannot do that. Have to resort to do() depending on how sure you are as to whether your function would always return a single value. And it is quite slow.

Once again, data.table's syntax is consistent with DT[i, j, by]. We can just keep throwing expressions in j without having to worry about these things.

Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...

To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.

data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.

But one should also consider the number of features that dplyr lacks in comparison to data.table.

4. Features

I have pointed out most of the features here and also in this post. In addition:

  • fread - fast file reader has been available for a long time now.

  • fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.

  • Automatic indexing - another handy feature to optimise base R syntax as is, internally.

  • Ad-hoc grouping: dplyr automatically sorts the results by grouping variables during summarise(), which may not be always desirable.

  • Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.

  • Non-equi joins: Allows joins using other operators <=, <, >, >= along with all other advantages of data.table joins.

  • Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.

  • setorder() function in data.table that allows really fast reordering of data.tables by reference.

  • dplyr provides interface to databases using the same syntax, which data.table does not at the moment.

  • data.table provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff, fintersect, funion and fsetequal with additional all argument (as in SQL).

  • data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame compatibility when passed to any R package. dplyr changes base functions filter, lag and [ which can cause problems; e.g. here and here.


Finally:

  • On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.

  • On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).

    • Progress is being made currently (in v1.9.7 devel) towards parallelising known time consuming parts for incremental performance gains using OpenMP.

Using Java to find substring of a bigger string using Regular Expression

String input = "FOO[BAR]";
String result = input.substring(input.indexOf("[")+1,input.lastIndexOf("]"));

This will return the value between first '[' and last ']'

Foo[Bar] => Bar

Foo[Bar[test]] => Bar[test]

Note: You should add error checking if the input string is not well formed.

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

How to enumerate a range of numbers starting at 1

Easy, just define your own function that does what you want:

def enum(seq, start=0):
    for i, x in enumerate(seq):
        yield i+start, x

A function to convert null to string

It is possible to use the "?." (null conditional member access) with the "??" (null-coalescing operator) like this:

public string EmptyIfNull(object value)
{
    return value?.ToString() ?? string.Empty;
}

This method can also be written as an extension method for an object:

public static class ObjectExtensions
{
    public static string EmptyIfNull(this object value)
    {
        return value?.ToString() ?? string.Empty;
    }
}

And you can write same methods using "=>" (lambda operator):

public string EmptyIfNull(object value)
    => value?.ToString() ?? string.Empty;

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

Android Activity as a dialog

Set the theme in your android manifest file.

<activity android:name=".LoginActivity"
            android:theme="@android:style/Theme.Dialog"/>

And set the dialog state on touch to finish.

this.setFinishOnTouchOutside(false);

Get LatLng from Zip Code - Google Maps API

Here is the function I am using for my work

function getLatLngByZipcode(zipcode) 
{
    var geocoder = new google.maps.Geocoder();
    var address = zipcode;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        } else {
            alert("Request failed.")
        }
    });
    return [latitude, longitude];
}

How do I parse a string to a float or int?

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

Count the occurrences of DISTINCT values

Just changed Amber's COUNT(*) to COUNT(1) for the better performance.

SELECT name, COUNT(1) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

How to display HTML <FORM> as inline element?

<form> cannot go inside <p>, no. The browser is going to abruptly close your <p> element when it hits the opening <form> tag as it tries to handle what it thinks is an unclosed paragraph element:

<p>Read this sentence 
 </p><form style='display:inline;'>

memcpy() vs memmove()

Just because memcpy doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.

How to use OUTPUT parameter in Stored Procedure

You need to define the output parameter as an output parameter in the code with the ParameterDirection.Output enumeration. There are numerous examples of this out there, but here's one on MSDN.

How do I check for equality using Spark Dataframe without SQL Query?

To get the negation, do this ...

df.filter(not( ..expression.. ))

eg

df.filter(not($"state" === "TX"))

How do you add an in-app purchase to an iOS application?

Swift Users

Swift users can check out My Swift Answer for this question.
Or, check out Yedidya Reiss's Answer, which translates this Objective-C code to Swift.

Objective-C Users

The rest of this answer is written in Objective-C

App Store Connect

  1. Go to appstoreconnect.apple.com and log in
  2. Click My Apps then click the app you want do add the purchase to
  3. Click the Features header, and then select In-App Purchases on the left
  4. Click the + icon in the middle
  5. For this tutorial, we are going to be adding an in-app purchase to remove ads, so choose non-consumable. If you were going to send a physical item to the user, or give them something that they can buy more than once, you would choose consumable.
  6. For the reference name, put whatever you want (but make sure you know what it is)
  7. For product id put tld.websitename.appname.referencename this will work the best, so for example, you could use com.jojodmo.blix.removeads
  8. Choose cleared for sale and then choose price tier as 1 (99¢). Tier 2 would be $1.99, and tier 3 would be $2.99. The full list is available if you click view pricing matrix I recommend you use tier 1, because that's usually the most anyone will ever pay to remove ads.
  9. Click the blue add language button, and input the information. This will ALL be shown to the customer, so don't put anything you don't want them seeing
  10. For hosting content with Apple choose no
  11. You can leave the review notes blank FOR NOW.
  12. Skip the screenshot for review FOR NOW, everything we skip we will come back to.
  13. Click 'save'

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Setting up your project

Now that you've set up your in-app purchase information on App Store Connect, go into your Xcode project, and go to the application manager (blue page-like icon at the top of where your methods and header files are) click on your app under targets (should be the first one) then go to general. At the bottom, you should see linked frameworks and libraries click the little plus symbol and add the framework StoreKit.framework If you don't do this, the in-app purchase will NOT work!

If you are using Objective-C as the language for your app, you should skip these five steps. Otherwise, if you are using Swift, you can follow My Swift Answer for this question, here, or, if you prefer to use Objective-C for the In-App Purchase code but are using Swift in your app, you can do the following:

  1. Create a new .h (header) file by going to File > New > File... (Command ? + N). This file will be referred to as "Your .h file" in the rest of the tutorial

  2. When prompted, click Create Bridging Header. This will be our bridging header file. If you are not prompted, go to step 3. If you are prompted, skip step 3 and go directly to step 4.

  3. Create another .h file named Bridge.h in the main project folder, Then go to the Application Manager (the blue page-like icon), then select your app in the Targets section, and click Build Settings. Find the option that says Swift Compiler - Code Generation, and then set the Objective-C Bridging Header option to Bridge.h

  4. In your bridging header file, add the line #import "MyObjectiveCHeaderFile.h", where MyObjectiveCHeaderFile is the name of the header file that you created in step one. So, for example, if you named your header file InAppPurchase.h, you would add the line #import "InAppPurchase.h" to your bridge header file.

  5. Create a new Objective-C Methods (.m) file by going to File > New > File... (Command ? + N). Name it the same as the header file you created in step 1. For example, if you called the file in step 1 InAppPurchase.h, you would call this new file InAppPurchase.m. This file will be referred to as "Your .m file" in the rest of the tutorial.

Coding

Now we're going to get into the actual coding. Add the following code into your .h file:

BOOL areAdsRemoved;

- (IBAction)restore;
- (IBAction)tapsRemoveAds;

Next, you need to import the StoreKit framework into your .m file, as well as add SKProductsRequestDelegate and SKPaymentTransactionObserver after your @interface declaration:

#import <StoreKit/StoreKit.h>

//put the name of your view controller in place of MyViewController
@interface MyViewController() <SKProductsRequestDelegate, SKPaymentTransactionObserver>

@end

@implementation MyViewController //the name of your view controller (same as above)
  //the code below will be added here
@end

and now add the following into your .m file, this part gets complicated, so I suggest that you read the comments in the code:

//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product

#define kRemoveAdsProductIdentifier @"put your product id (the one that we just made in App Store Connect) in here"

- (IBAction)tapsRemoveAds{
    NSLog(@"User requests to remove ads");

    if([SKPaymentQueue canMakePayments]){
        NSLog(@"User can make payments");
    
        //If you have more than one in-app purchase, and would like
        //to have the user purchase a different product, simply define 
        //another function and replace kRemoveAdsProductIdentifier with 
        //the identifier for the other product

        SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kRemoveAdsProductIdentifier]];
        productsRequest.delegate = self;
        [productsRequest start];
    
    }
    else{
        NSLog(@"User cannot make payments due to parental controls");
        //this is called the user cannot make payments, most likely due to parental controls
    }
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if(count > 0){
        validProduct = [response.products objectAtIndex:0];
        NSLog(@"Products Available!");
        [self purchase:validProduct];
    }
    else if(!validProduct){
        NSLog(@"No products available");
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

- (void)purchase:(SKProduct *)product{
    SKPayment *payment = [SKPayment paymentWithProduct:product];

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (IBAction) restore{
    //this is called when the user restores purchases, you should hook this up to a button
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSLog(@"received restored transactions: %i", queue.transactions.count);
    for(SKPaymentTransaction *transaction in queue.transactions){
        if(transaction.transactionState == SKPaymentTransactionStateRestored){
            //called when the user successfully restores a purchase
            NSLog(@"Transaction state -> Restored");

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            [self doRemoveAds];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            break;
        }
    }   
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for(SKPaymentTransaction *transaction in transactions){
        //if you have multiple in app purchases in your app,
        //you can get the product identifier of this transaction
        //by using transaction.payment.productIdentifier
        //
        //then, check the identifier against the product IDs
        //that you have defined to check which product the user
        //just purchased            

        switch(transaction.transactionState){
            case SKPaymentTransactionStatePurchasing: NSLog(@"Transaction state -> Purchasing");
                //called when the user is in the process of purchasing, do not add any of your own code here.
                break;
            case SKPaymentTransactionStatePurchased:
            //this is called when the user has successfully purchased the package (Cha-Ching!)
                [self doRemoveAds]; //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                NSLog(@"Transaction state -> Purchased");
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"Transaction state -> Restored");
                //add the same code as you did from SKPaymentTransactionStatePurchased here
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                //called when the transaction does not finish
                if(transaction.error.code == SKErrorPaymentCancelled){
                    NSLog(@"Transaction state -> Cancelled");
                    //the user cancelled the payment ;(
                }
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
        }
    }
}

Now you want to add your code for what will happen when the user finishes the transaction, for this tutorial, we use removing adds, you will have to add your own code for what happens when the banner view loads.

- (void)doRemoveAds{
    ADBannerView *banner;
    [banner setAlpha:0];
    areAdsRemoved = YES;
    removeAdsButton.hidden = YES;
    removeAdsButton.enabled = NO;
    [[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
    //use NSUserDefaults so that you can load whether or not they bought it
    //it would be better to use KeyChain access, or something more secure
    //to store the user data, because NSUserDefaults can be changed.
    //You're average downloader won't be able to change it very easily, but
    //it's still best to use something more secure than NSUserDefaults.
    //For the purpose of this tutorial, though, we're going to use NSUserDefaults
    [[NSUserDefaults standardUserDefaults] synchronize];
}

If you don't have ads in your application, you can use any other thing that you want. For example, we could make the color of the background blue. To do this we would want to use:

- (void)doRemoveAds{
    [self.view setBackgroundColor:[UIColor blueColor]];
    areAdsRemoved = YES
    //set the bool for whether or not they purchased it to YES, you could use your own boolean here, but you would have to declare it in your .h file

    [[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
    //use NSUserDefaults so that you can load wether or not they bought it
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Now, somewhere in your viewDidLoad method, you're going to want to add the following code:

areAdsRemoved = [[NSUserDefaults standardUserDefaults] boolForKey:@"areAdsRemoved"];
[[NSUserDefaults standardUserDefaults] synchronize];
//this will load wether or not they bought the in-app purchase

if(areAdsRemoved){
    [self.view setBackgroundColor:[UIColor blueColor]];
    //if they did buy it, set the background to blue, if your using the code above to set the background to blue, if your removing ads, your going to have to make your own code here
}

Now that you have added all the code, go into your .xib or storyboard file, and add two buttons, one saying purchase, and the other saying restore. Hook up the tapsRemoveAds IBAction to the purchase button that you just made, and the restore IBAction to the restore button. The restore action will check if the user has previously purchased the in-app purchase, and give them the in-app purchase for free if they do not already have it.

Submitting for review

Next, go into App Store Connect, and click Users and Access then click the Sandbox Testers header, and then click the + symbol on the left where it says Testers. You can just put in random things for the first and last name, and the e-mail does not have to be real - you just have to be able to remember it. Put in a password (which you will have to remember) and fill in the rest of the info. I would recommend that you make the Date of Birth a date that would make the user 18 or older. App Store Territory HAS to be in the correct country. Next, log out of your existing iTunes account (you can log back in after this tutorial).

Now, run your application on your iOS device, if you try running it on the simulator, the purchase will always error, you HAVE TO run it on your iOS device. Once the app is running, tap the purchase button. When you are prompted to log into your iTunes account, log in as the test user that we just created. Next,when it asks you to confirm the purchase of 99¢ or whatever you set the price tier too, TAKE A SCREEN SNAPSHOT OF IT this is what your going to use for your screenshot for review on App Store Connect. Now cancel the payment.

Now, go to App Store Connect, then go to My Apps > the app you have the In-app purchase on > In-App Purchases. Then click your in-app purchase and click edit under the in-app purchase details. Once you've done that, import the photo that you just took on your iPhone into your computer, and upload that as the screenshot for review, then, in review notes, put your TEST USER e-mail and password. This will help apple in the review process.

After you have done this, go back onto the application on your iOS device, still logged in as the test user account, and click the purchase button. This time, confirm the payment Don't worry, this will NOT charge your account ANY money, test user accounts get all in-app purchases for free After you have confirmed the payment, make sure that what happens when the user buys your product actually happens. If it doesn't, then thats going to be an error with your doRemoveAds method. Again, I recommend using changing the background to blue for testing the in-app purchase, this should not be your actual in-app purchase though. If everything works and you're good to go! Just make sure to include the in-app purchase in your new binary when you upload it to App Store Connect!


Here are some common errors:

Logged: No Products Available

This could mean four things:

  • You didn't put the correct in-app purchase ID in your code (for the identifier kRemoveAdsProductIdentifier in the above code
  • You didn't clear your in-app purchase for sale on App Store Connect
  • You didn't wait for the in-app purchase ID to be registered in App Store Connect. Wait a couple hours from creating the ID, and your problem should be resolved.
  • You didn't complete filling your Agreements, Tax, and Banking info.

If it doesn't work the first time, don't get frustrated! Don't give up! It took me about 5 hours straight before I could get this working, and about 10 hours searching for the right code! If you use the code above exactly, it should work fine. Feel free to comment if you have any questions at all.

I hope this helps to all of those hoping to add an in-app purchase to their iOS application. Cheers!

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

Making a WinForms TextBox behave like your browser's address bar

private bool _isSelected = false;
private void textBox_Validated(object sender, EventArgs e)
{
    _isSelected = false;
}

private void textBox_MouseClick(object sender, MouseEventArgs e)
{
    SelectAllText(textBox);
}

private void textBox_Enter(object sender, EventArgs e)
{
    SelectAllText(textBox);
}

private void SelectAllText(TextBox text)
{
    if (!_isSelected)
    {
        _isSelected = true;
        textBox.SelectAll();
    }
}

Thread pooling in C++11

You can use C++ Thread Pool Library, https://github.com/vit-vit/ctpl.

Then the code your wrote can be replaced with the following

#include <ctpl.h>  // or <ctpl_stl.h> if ou do not have Boost library

int main (int argc, char *argv[]) {
    ctpl::thread_pool p(2 /* two threads in the pool */);
    int arr[4] = {0};
    std::vector<std::future<void>> results(4);
    for (int i = 0; i < 8; ++i) { // for 8 iterations,
        for (int j = 0; j < 4; ++j) {
            results[j] = p.push([&arr, j](int){ arr[j] +=2; });
        }
        for (int j = 0; j < 4; ++j) {
            results[j].get();
        }
        arr[4] = std::min_element(arr, arr + 4);
    }
}

You will get the desired number of threads and will not create and delete them over and over again on the iterations.

How to encode a URL in Swift

URLQueryAllowedCharacterSet should not be used for URL encoding of query parameters because this charset includes &, ?, / etc. which serve as delimiters in a URL query, e.g.

/?paramname=paramvalue&paramname=paramvalue

These characters are allowed in URL queries as a whole but not in parameter values.

RFC 3986 specifically talks about unreserved characters, which are different from allowed:

2.3. Unreserved Characters

Characters that are allowed in a URI but do not have a reserved
purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

Accordingly:

extension String {
    var URLEncoded:String {
        var URLEncoded:String {
    let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
    let encodedString = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
    return encodedString
}
    }
}

The code above doesn't make a call to alphanumericCharacterSet because of the enormous size of the charset it returns (103806 characters). And in view of how many Unicode characters alphanumericCharacterSet allows for, using it for the purpose of URL encoding would be simply erroneous.

Usage:

let URLEncodedString = myString.URLEncoded

Convert a string to an enum in C#

You can extend the accepted answer with a default value to avoid exceptions:

public static T ParseEnum<T>(string value, T defaultValue) where T : struct
{
    try
    {
        T enumValue;
        if (!Enum.TryParse(value, true, out enumValue))
        {
            return defaultValue;
        }
        return enumValue;
    }
    catch (Exception)
    {
        return defaultValue;
    }
}

Then you call it like:

StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);

If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.

After years of using this function in our code on many places maybe it's good to add the information that this operation costs performance!

Correct Semantic tag for copyright info - html5

Put it inside your <footer> by all means, but the most fitting element is the small element.

The HTML5 spec for this says:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

pretty-print JSON using JavaScript

To highlight and beautify it in HTML using Bootstrap:

function prettifyJson(json, prettify) {
    if (typeof json !== 'string') {
        if (prettify) {
            json = JSON.stringify(json, undefined, 4);
        } else {
            json = JSON.stringify(json);
        }
    }
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
        function(match) {
            let cls = "<span>";
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = "<span class='text-danger'>";
                } else {
                    cls = "<span>";
                }
            } else if (/true|false/.test(match)) {
                cls = "<span class='text-primary'>";
            } else if (/null/.test(match)) {
                cls = "<span class='text-info'>";
            }
            return cls + match + "</span>";
        }
    );
}

Add Auto-Increment ID to existing table?

Well, you must first drop the auto_increment and primary key you have and then add yours, as follows:

-- drop auto_increment capability
alter table `users` modify column id INT NOT NULL;
-- in one line, drop primary key and rebuild one
alter table `users` drop primary key, add primary key(id);
-- re add the auto_increment capability, last value is remembered
alter table `users` modify column id INT NOT NULL AUTO_INCREMENT;

"Stack overflow in line 0" on Internet Explorer

I have reproduced the same error on IE8. One of the text boxes has some event handlers to replace not valid data.

$('.numbersonly').on("keyup input propertychange", function () {
    //code
});

The error message was shown on entering data to this text box. We removed event "propertychange" from the code above and now it works correctly.

P.S. maybe it will help somebody

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

How to get UTC value for SYSDATE on Oracle

I'm using:

SELECT CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE) FROM DUAL;

It's working fine for me.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you're planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.

Example:

function Circle(radius) {
    this.radius = radius;
}
Circle.prototype.getCircumference = function() {
    return Math.PI * 2 * this.radius;
};
Circle.prototype.getArea = function() {
    return Math.PI * this.radius * this.radius;
}

I am not a big fan of the third method, but it's really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];.

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

Calling Java from Python

If you're in Python 3, there's a fork of JPype called JPype1-py3

pip install JPype1-py3

This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version)

from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

Apache server keeps crashing, "caught SIGTERM, shutting down"

SIGTERM is used to restart Apache (provided that it's setup in init to auto-restart): http://httpd.apache.org/docs/2.2/stopping.html

The entries you see in the logs are almost certainly there because your provider used SIGTERM for that purpose. If it's truly crashing, not even serving static content, then that sounds like some sort of a thread/connection exhaustion issue. Perhaps a DoS that holds connections open?

Should definitely be something for your provider to investigate.

gradient descent using python and numpy

Below you can find my implementation of gradient descent for linear regression problem.

At first, you calculate gradient like X.T * (X * w - y) / N and update your current theta with this gradient simultaneously.

  • X: feature matrix
  • y: target values
  • w: weights/values
  • N: size of training set

Here is the python code:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random

def generateSample(N, variance=100):
    X = np.matrix(range(N)).T + 1
    Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
    return X, Y

def fitModel_gradient(x, y):
    N = len(x)
    w = np.zeros((x.shape[1], 1))
    eta = 0.0001

    maxIteration = 100000
    for i in range(maxIteration):
        error = x * w - y
        gradient = x.T * error / N
        w = w - eta * gradient
    return w

def plotModel(x, y, w):
    plt.plot(x[:,1], y, "x")
    plt.plot(x[:,1], x * w, "r-")
    plt.show()

def test(N, variance, modelFunction):
    X, Y = generateSample(N, variance)
    X = np.hstack([np.matrix(np.ones(len(X))).T, X])
    w = modelFunction(X, Y)
    plotModel(X, Y, w)


test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)

test1 test2 test2

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Get Image Height and Width as integer values?

getimagesize() returns an array containing the image properties.

list($width, $height) = getimagesize("path/to/image.jpg");

to just get the width and height or

list($width, $height, $type, $attr)

to get some more information.

What's the best way to build a string of delimited items in Java?

Use an approach based on java.lang.StringBuilder! ("A mutable sequence of characters. ")

Like you mentioned, all those string concatenations are creating Strings all over. StringBuilder won't do that.

Why StringBuilder instead of StringBuffer? From the StringBuilder javadoc:

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How to click or tap on a TextView text

You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).

holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // code during!

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // code before!

        }

        @Override
        public void afterTextChanged(Editable s) {
            // code after!

        }
    });

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

1.Close your project:Completely quit Xcode. 2.Go to your project location:there you will find two files in you root folder with varying extensions: Appname.xcodeproj and Appname.xcworkspace

Now open your project by Double clicking on file with the extensions xcworkspace.(***Appname.xcworkspace*)**

Yourproject will open in xcode. Now run your project again.

If you pay close attention when installing your pods,firebase makes it clear to open your project with your-project.xcworkspace after installing pods firebaseIOS Setup

 $ cd your-project directory
 $ pod init

Add to Podfile

pod 'Firebase/Core'

And finally:

    $ pod install
    $ open your-project.xcworkspace

Dont forget to add firebase to your AppDelegate

Adding an onclicklistener to listview (android)

You are doing

Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter

The o that you get back is not a String, but a prestationEco so you get a CCE when doing the (String)o

window.location.href not working

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Converting a view to Bitmap without displaying it in Android?

I used this just a few days ago:

fun generateBitmapFromView(view: View): Bitmap {
    val specWidth = View.MeasureSpec.makeMeasureSpec(1324, View.MeasureSpec.AT_MOST)
    val specHeight = View.MeasureSpec.makeMeasureSpec(521, View.MeasureSpec.AT_MOST)
    view.measure(specWidth, specHeight)
    val width = view.measuredWidth
    val height = view.measuredHeight
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(view.left, view.top, view.right, view.bottom)
    view.draw(canvas)
    return bitmap
}

This code is based in this gist

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

The code below can solve the NullPointerException.

@Id
@GeneratedValue
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
    return this.stockId;
}
public void setStockId(Integer stockId) {
    this.stockId = stockId;
}

If you add @Id, then you can declare some more like as above declared method.

Fastest way to compute entropy in Python

My favorite function for entropy is the following:

def entropy(labels):
    prob_dict = {x:labels.count(x)/len(labels) for x in labels}
    probs = np.array(list(prob_dict.values()))

    return - probs.dot(np.log2(probs))

I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.

Python not working in command prompt?

Just go with the command py. I'm running python 3.6.2 on windows 7 and it works just fine.
I removed all the python paths from the system directory and the paths don't show up when I run the command echo %path% in cmd. Python is still working fine.
I ran into this by accidentally pressing enter while typing python...

EDIT: I didn't mention that I installed python to a custom folder C:\Python\

Difference between readFile() and readFileSync()

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

Logical operator in a handlebars.js {{#if}} conditional

Yet another crooked solution for a ternary helper:

'?:' ( condition, first, second ) {
  return condition ? first : second;
}

<span>{{?: fooExists 'found it' 'nope, sorry'}}</span>

Or a simple coalesce helper:

'??' ( first, second ) {
  return first ? first : second;
}

<span>{{?? foo bar}}</span>

Since these characters don't have a special meaning in handlebars markup, you're free to use them for helper names.

What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

Store a closure as a variable in Swift

I've provide an example not sure if this is what you're after.

var completionHandler: (_ value: Float) -> ()

func printFloat(value: Float) {
    print(value)
}

completionHandler = printFloat

completionHandler(5)

It simply prints 5 using the completionHandler variable declared.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Find maximum value of a column and return the corresponding row values using Pandas

You can use:

print(df[df['Value']==df['Value'].max()])

How can I get the count of milliseconds since midnight for the current?

Use Calendar

Calendar.getInstance().get(Calendar.MILLISECOND);

or

Calendar c=Calendar.getInstance();
c.setTime(new Date()); /* whatever*/
//c.setTimeZone(...); if necessary
c.get(Calendar.MILLISECOND);

In practise though I think it will nearly always equal System.currentTimeMillis()%1000; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

Enable vertical scrolling on textarea

Here's your CSS

element{
  width: 200px;
  height: 300px;
  overflow-y: auto;
}

Convert list to tuple in Python

To add another alternative to tuple(l), as of Python >= 3.5 you can do:

t = *l,  # or t = (*l,) 

short, a bit faster but probably suffers from readability.

This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma ,.


P.s: The error you are receiving is due to masking of the name tuple i.e you assigned to the name tuple somewhere e.g tuple = (1, 2, 3).

Using del tuple you should be good to go.

Python 3 - Encode/Decode vs Bytes/Str

Neither is better than the other, they do exactly the same thing. However, using .encode() and .decode() is the more common way to do it. It is also compatible with Python 2.

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

CSS - make div's inherit a height

You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...

List the queries running on SQL Server

here is a query that will show any queries that are blocking. I am not entirely sure if it will just show slow queries:

SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, convert(char(12), l.name) login_name
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM      master..sysprocesses p
JOIN      master..sysdatabases d ON p.dbid =  d.dbid
JOIN      master..syslogins l ON p.sid = l.sid
WHERE     p.blocked = 0
AND       EXISTS (  SELECT 1
          FROM      master..sysprocesses p2
          WHERE     p2.blocked = p.spid )

keypress, ctrl+c (or some combo like that)

There is a plugin for Jquery called "Hotkeys" which allows you to bind to key down combinations.

Does this do what you are after?

Jquery HotKeys - Google Code

:first-child not working as expected

For that particular case you can use:

.detail_container > ul + h1{ 
    color: blue; 
}

But if you need that same selector on many cases, you should have a class for those, like BoltClock said.

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

GetElementByID - Multiple IDs

Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.

<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>

<script>

  document.getElementById('click').addEventListener('click', function(){
    doStuff();
  });

  function doStuff() {
    for(var i=1; i<=2; i++){
        var el = document.getElementById("hello" + i);
        el.style.display = 'none';
    }
  }

</script>

Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.

UDP vs TCP, how much faster is it?

The network setup is crucial for any measurements. It makes a huge difference, if you are communicating via sockets on your local machine or with the other end of the world.

Three things I want to add to the discussion:

  1. You can find here a very good article about TCP vs. UDP in the context of game development.
  2. Additionally, iperf (jperf enhance iperf with a GUI) is a very nice tool for answering your question yourself by measuring.
  3. I implemented a benchmark in Python (see this SO question). In average of 10^6 iterations the difference for sending 8 bytes is about 1-2 microseconds for UDP.

What is the most accurate way to retrieve a user's correct IP address in PHP?

i realize there are much better and more concise answers above, and this isnt a function nor the most graceful script around. In our case we needed to output both the spoofable x_forwarded_for and the more reliable remote_addr in a simplistic switch per-say. It needed to allow blanks for injecting into other functions if-none or if-singular (rather than just returning the preformatted function). It needed an "on or off" var with a per-switch customized label(s) for platform settings. It also needed a way for $ip to be dynamic depending on request so that it would take form of forwarded_for.

Also i didnt see anyone address isset() vs !empty() -- its possible to enter nothing for x_forwarded_for yet still trigger isset() truth resulting in blank var, a way to get around is to use && and combine both as conditions. Keep in mind you can spoof words like "PWNED" as x_forwarded_for so make sure you sterilize to a real ip syntax if your outputting somewhere protected or into DB.

Also also, you can test using google translate if you need a multi-proxy to see the array in x_forwarder_for. If you wanna spoof headers to test, check this out Chrome Client Header Spoof extension. This will default to just standard remote_addr while behind anon proxy.

I dunno any case where remote_addr could be empty, but its there as fallback just in case.

// proxybuster - attempts to un-hide originating IP if [reverse]proxy provides methods to do so
  $enableProxyBust = true;

if (($enableProxyBust == true) && (isset($_SERVER['REMOTE_ADDR'])) && (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
    $ip = end(array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']))));
    $ipProxy = $_SERVER['REMOTE_ADDR'];
    $ipProxy_label = ' behind proxy ';
} elseif (($enableProxyBust == true) && (isset($_SERVER['REMOTE_ADDR']))) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $ipProxy = '';
    $ipProxy_label = ' no proxy ';
} elseif (($enableProxyBust == false) && (isset($_SERVER['REMOTE_ADDR']))) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $ipProxy = '';
    $ipProxy_label = '';
} else {
    $ip = '';
    $ipProxy = '';
    $ipProxy_label = '';
}

To make these dynamic for use in function(s) or query/echo/views below, say for log gen or error reporting, use globals or just echo em in wherever you desire without making a ton of other conditions or static-schema-output functions.

function fooNow() {
    global $ip, $ipProxy, $ipProxy_label;
    // begin this actions such as log, error, query, or report
}

Thank you for all your great thoughts. Please let me know if this could be better, still kinda new to these headers :)

How to remove an app with active device admin enabled on Android?

Redmi/xiaomi user

Go to "Settings" -> "Password & security" -> "Privacy" -> "Special app access" -> "Device admin apps" and select the account which you want to uninstall.

Or Simply

go to setting -> Then search for Device admin apps -> click and select the account which you want to uninstall.

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

How to find which git branch I am on when my disk is mounted on other server

.git/HEAD contains the path of the current ref, the working directory is using as HEAD.

PHP - add 1 day to date format mm-dd-yyyy

Actually I wanted same alike thing, To get one year backward date, for a given date! :-)

With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!

Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!

$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');

Hopes this answer will help somebody too! :-)

Good luck guys!

How to align texts inside of an input?

Use the text-align property in your CSS:

input { 
    text-align: right; 
}

This will take effect in all the inputs of the page.
Otherwise, if you want to align the text of just one input, set the style inline:

<input type="text" style="text-align:right;"/> 

Codeigniter : calling a method of one controller from other

You can do like

$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));

Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();

You need to echo output in controller function instead of return.

How to run function in AngularJS controller on document ready?

Why not try with what angular docs mention https://docs.angularjs.org/api/ng/function/angular.element.

angular.element(callback)

I've used this inside my $onInit(){...} function.

 var self = this;

 angular.element(function () {
        var target = document.getElementsByClassName('unitSortingModule');
        target[0].addEventListener("touchstart", self.touchHandler, false);
        ...
    });

This worked for me.

Align two inline-blocks left and right on same line

Edit: 3 years has passed since I answered this question and I guess a more modern solution is needed, although the current one does the thing :)

1.Flexbox

It's by far the shortest and most flexible. Apply display: flex; to the parent container and adjust the placement of its children by justify-content: space-between; like this:

.header {
    display: flex;
    justify-content: space-between;
}

Can be seen online here - http://jsfiddle.net/skip405/NfeVh/1073/

Note however that flexbox support is IE10 and newer. If you need to support IE 9 or older, use the following solution:

2.You can use the text-align: justify technique here.

.header {
    background: #ccc; 
    text-align: justify; 

    /* ie 7*/  
    *width: 100%;  
    *-ms-text-justify: distribute-all-lines;
    *text-justify: distribute-all-lines;
}
 .header:after{
    content: '';
    display: inline-block;
    width: 100%;
    height: 0;
    font-size:0;
    line-height:0;
}

h1 {
    display: inline-block;
    margin-top: 0.321em; 

    /* ie 7*/ 
    *display: inline;
    *zoom: 1;
    *text-align: left; 
}

.nav {
    display: inline-block;
    vertical-align: baseline; 

    /* ie 7*/
    *display: inline;
    *zoom:1;
    *text-align: right;
}

The working example can be seen here: http://jsfiddle.net/skip405/NfeVh/4/. This code works from IE7 and above

If inline-block elements in HTML are not separated with space, this solution won't work - see example http://jsfiddle.net/NfeVh/1408/ . This might be a case when you insert content with Javascript.

If we don't care about IE7 simply omit the star-hack properties. The working example using your markup is here - http://jsfiddle.net/skip405/NfeVh/5/. I just added the header:after part and justified the content.

In order to solve the issue of the extra space that is inserted with the after pseudo-element one can do a trick of setting the font-size to 0 for the parent element and resetting it back to say 14px for the child elements. The working example of this trick can be seen here: http://jsfiddle.net/skip405/NfeVh/326/

Can I return the 'id' field after a LINQ insert?

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

How can I detect the touch event of an UIImageView?

First, you should place an UIButton and then either you can add a background image for this button, or you need to place an UIImageView over the button.

Or:

You can add the tap gesture to a UIImageView so that get the click action when tap on the UIImageView.

Xcode doesn't see my iOS device but iTunes does

Had the same problem. In my case it was my usb cord.

Can I extend a class using more than 1 class in PHP?

You cannot have a class that extends two base classes. You could not have.

// this is NOT allowed (for all you google speeders)
Matron extends Nurse, HumanEntity

You could however have a hierarchy as follows...

Matron extends Nurse    
Consultant extends Doctor

Nurse extends HumanEntity
Doctor extends HumanEntity

HumanEntity extends DatabaseTable
DatabaseTable extends AbstractTable

and so on.

SQL Server Group By Month

Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.

SELECT 
      SUM( case when DateDiff(m, PaymentDate, @start) = 0 
           then Amount else 0 end ) AS "Apr",
      SUM( case when DateDiff(m, PaymentDate, @start) = 1 
           then Amount else 0 end ) AS "May",
      SUM( case when DateDiff(m, PaymentDate, @start) = 2 
           then Amount else 0 end ) AS "June",
      SUM( case when DateDiff(m, PaymentDate, @start) = 3 
           then Amount else 0 end ) AS "July",
      SUM( case when DateDiff(m, PaymentDate, @start) = 4 
           then Amount else 0 end ) AS "Aug",
      SUM( case when DateDiff(m, PaymentDate, @start) = 5 
           then Amount else 0 end ) AS "Sep",
      SUM( case when DateDiff(m, PaymentDate, @start) = 6 
           then Amount else 0 end ) AS "Oct",
      SUM( case when DateDiff(m, PaymentDate, @start) = 7 
           then Amount else 0 end ) AS "Nov",
      SUM( case when DateDiff(m, PaymentDate, @start) = 8 
           then Amount else 0 end ) AS "Dec",
      SUM( case when DateDiff(m, PaymentDate, @start) = 9 
           then Amount else 0 end ) AS "Jan",
      SUM( case when DateDiff(m, PaymentDate, @start) = 10 
           then Amount else 0 end ) AS "Feb",
      SUM( case when DateDiff(m, PaymentDate, @start) = 11 
           then Amount else 0 end ) AS "Mar"
   FROM 
      Payments I
         JOIN Live L
            on I.LiveID = L.Record_Key
   WHERE 
          Year = 2010 
      AND UserID = 100

how to redirect to home page

document.location.href="/";

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

XAMPP - MySQL shutdown unexpectedly

What worked for me is:

  1. First I open Logs for MySql in XAMPP panel.
  2. At the end it says you are running another instance of mysqlid in port 3306
  3. I opened my task manager(Ctrl+Shift+Esc) then find mysqlid and End the task.

How do I merge my local uncommitted changes into another Git branch?

A shorter alternative to the previously mentioned stash approach would be:

Temporarily move the changes to a stash.

  1. git stash

Create and switch to a new branch and then pop the stash to it in just one step.

  1. git stash branch new_branch_name

Then just add and commit the changes to this new branch.

Codeigniter LIKE with wildcard(%)

I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes

Deep copy an array in Angular 2 + TypeScript

Simple:

let objCopy  = JSON.parse(JSON.stringify(obj));

This Also Works (Only for Arrays)

let objCopy2 = obj.slice()

Android notification is not showing

Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.

Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.

If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.

Insert some string into given string at given index in Python

Answer for Insert characters of string in other string al located positions

str1 = "ibuprofen"
str2 = "MEDICAL"
final_string=""
Value = 2
list2=[]
result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
count = 0

for letter in result:
    if count < len(result)-1:
        final_string = letter + str2[count]
        list2.append(final_string)
    elif ((len(result)-1)==count):
        list2.append(letter + str2[count:len(str2)])
        break
    count += 1

print(''.join(list2))

Node.js heap out of memory

i was struggling with this even after setting --max-old-space-size.

Then i realised need to put options --max-old-space-size before the karma script.

also best to specify both syntaxes --max-old-space-size and --max_old_space_size my script for karma :

node --max-old-space-size=8192 --optimize-for-size --max-executable-size=8192  --max_old_space_size=8192 --optimize_for_size --max_executable_size=8192 node_modules/karma/bin/karma start --single-run --max_new_space_size=8192   --prod --aot

reference https://github.com/angular/angular-cli/issues/1652

SSRS chart does not show all labels on Horizontal axis

It looks as though the horizontal axis (Category Group) labels have very long values - there may not be room to display them all. I suggest changing the labels to have shorter values.

You can set the sort order for the Category Groups in the Category Group Properties - Sorting section - this may have been previously set; if not, I suggest using this to sort as desired.

How to generate gcc debug symbol outside the build target?

NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.

Alternate approaches are

  1. Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
  2. Build a 2nd non-optimized version of the executable.

The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).

Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:

program: program.o version.o 

program.o: program.cpp program.h 

build_version.o: build_version.c    

build_version.c: 
    @echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
    @echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
    @echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
    @echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
    # TODO: Add compiler options and other build details

.TEMPORARY: build_version.c

After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS

VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer  [email protected]
VCS: COMMIT_DATE=2013-12-19

All that is left is to check-out the original code, re-compile without optimizations, and start debugging.

Fastest way to get the first object from a queryset in django?

Now, in Django 1.9 you have first() method for querysets.

YourModel.objects.all().first()

This is a better way than .get() or [0] because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()

Switch statement for greater-than/less-than

You can create a custom object with the criteria and the function corresponding to the criteria

var rules = [{ lowerLimit: 0,    upperLimit: 1000, action: function1 }, 
             { lowerLimit: 1000, upperLimit: 2000, action: function2 }, 
             { lowerLimit: 2000, upperLimit: 3000, action: function3 }];

Define functions for what you want to do in these cases (define function1, function2 etc)

And "evaluate" the rules

function applyRules(scrollLeft)
{
   for(var i=0; i>rules.length; i++)
   {
       var oneRule = rules[i];
       if(scrollLeft > oneRule.lowerLimit && scrollLeft < oneRule.upperLimit)
       {
          oneRule.action();
       }
   }
}

Note

I hate using 30 if statements

Many times if statements are easier to read and maintain. I would recommend the above only when you have a lot of conditions and a possibility of lot of growth in the future.

Update
As @Brad pointed out in the comments, if the conditions are mutually exclusive (only one of them can be true at a time), checking the upper limit should be sufficient:

if(scrollLeft < oneRule.upperLimit)

provided that the conditions are defined in ascending order (first the lowest one, 0 to 1000, and then 1000 to 2000 for example)

How do I (or can I) SELECT DISTINCT on multiple columns?

I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using

Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering

It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.

use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering

SELECT        GrondOfLucht
FROM            dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)

Copy a git repo without history

Use the following command:

git clone --depth <depth> -b <branch> <repo_url>

Where:

  • depth is the amount of commits you want to include. i.e. if you just want the latest commit use git clone --depth 1
  • branch is the name of the remote branch that you want to clone from. i.e. if you want the last 3 commits from master branch use git clone --depth 3 -b master
  • repo_url is the url of your repository

How to write a switch statement in Ruby

Since switch case always returns a single object, we can directly print its result:

puts case a
     when 0
        "It's zero"
     when 1
        "It's one"
     end

Check if element is in the list (contains)

std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

You can simply use:

int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
      //do whatever
}

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

Python debugging tips

PDB

You can use the pdb module, insert pdb.set_trace() anywhere and it will function as a breakpoint.

>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)

To continue execution use c (or cont or continue).

It is possible to execute arbitrary Python expressions using pdb. For example, if you find a mistake, you can correct the code, then type a type expression to have the same effect in the running code

ipdb is a version of pdb for IPython. It allows the use of pdb with all the IPython features including tab completion.

It is also possible to set pdb to automatically run on an uncaught exception.

Pydb was written to be an enhanced version of Pdb. Benefits?

Can pm2 run an 'npm start' script

I wrote shell script below (named start.sh). Because my package.json has prestart option. So I want to run npm start.

#!/bin/bash
cd /path/to/project
npm start

Then, start start.sh by pm2.

pm2 start start.sh --name appNameYouLike

Retrieving a Foreign Key value with django-rest-framework serializers

Just use a related field without setting many=True.

Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field.

The following should give you the output you need...

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.RelatedField(source='category', read_only=True)

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

Errors in pom.xml with dependencies (Missing artifact...)

I somehow had this issue after I lost internet connection. I was able to fix it by updating the Maven indexes in Eclipse and then selecting my project and updating the Snapshots/releases.

Py_Initialize fails - unable to load the file system codec

The core reason is quite simple: Python does not find its modules directory, so it can of course not load encodings, too

Python doc on embedding says "Py_Initialize() calculates the module search path based upon its best guess" ... "In particular, it looks for a directory named lib/pythonX.Y"

Yet, if the modules are installed in (just) lib - relative to the python binary - above guess is wrong.

Although docs says that PYTHONHOME and PYTHONPATH are regarded, we observed that this was not the case; their actual presence or content was completely irrelevant.

The only thing that had an effect was a call to Py_SetPath() with e.g. [path-to]\lib as argument before Py_Initialize().

Sure this is only an option for an embedding scenario where one has direct access and control over the code; with a ready-made solution, special steps may be necessary to solve the issue.

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

Oracle: how to INSERT if a row doesn't exist

You should use Merge: For example:

MERGE INTO employees e
    USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

or

MERGE INTO employees e
    USING hr_records h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

https://oracle-base.com/articles/9i/merge-statement