Programs & Examples On #Ontology

Ontology is a formal representation of knowledge as a set of concepts within a domain, and the relationships between those concepts. Those concepts and relationships create graph-structures and can be described by the lattice theory or other mathematical models.

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

Parsing XML with namespace in Python via 'ElementTree'

To get the namespace in its namespace format, e.g. {myNameSpace}, you can do the following:

root = tree.getroot()
ns = re.match(r'{.*}', root.tag).group(0)

This way, you can use it later on in your code to find nodes, e.g using string interpolation (Python 3).

link = root.find(f"{ns}link")

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

What are the differences between a program and an application?

My understanding is this:

  • A computer program is a set of instructions that can be executed on a computer.
  • An application is software that directly helps a user perform tasks.
  • The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications.

Browser detection in JavaScript?

var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

Which are more performant, CTE or temporary tables?

Late to the party, but...

The environment I work in is highly constrained, supporting some vendor products and providing "value-added" services like reporting. Due to policy and contract limitations, I am not usually allowed the luxury of separate table/data space and/or the ability to create permanent code [it gets a little better, depending upon the application].

IOW, I can't usually develop a stored procedure or UDFs or temp tables, etc. I pretty much have to do everything through MY application interface (Crystal Reports - add/link tables, set where clauses from w/in CR, etc.). One SMALL saving grace is that Crystal allows me to use COMMANDS (as well as SQL Expressions). Some things that aren't efficient through the regular add/link tables capability can be done by defining a SQL Command. I use CTEs through that and have gotten very good results "remotely". CTEs also help w/ report maintenance, not requiring that code be developed, handed to a DBA to compile, encrypt, transfer, install, and then require multiple-level testing. I can do CTEs through the local interface.

The down side of using CTEs w/ CR is, each report is separate. Each CTE must be maintained for each report. Where I can do SPs and UDFs, I can develop something that can be used by multiple reports, requiring only linking to the SP and passing parameters as if you were working on a regular table. CR is not really good at handling parameters into SQL Commands, so that aspect of the CR/CTE aspect can be lacking. In those cases, I usually try to define the CTE to return enough data (but not ALL data), and then use the record selection capabilities in CR to slice and dice that.

So... my vote is for CTEs (until I get my data space).

Convert CString to const char*

I recommendo to you use TtoC from ConvUnicode.h

const CString word= "hello";
const char* myFile = TtoC(path.GetString());

It is a macro to do conversions per Unicode

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

Gson: Is there an easier way to serialize a map

Default

The default Gson implementation of Map serialization uses toString() on the key:

Gson gson = new GsonBuilder()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will give:

{
  "java.awt.Point[x\u003d1,y\u003d2]": "a",
  "java.awt.Point[x\u003d3,y\u003d4]": "b"
}


Using enableComplexMapKeySerialization

If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:

Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will return:

[
  [
    {
      "x": 1,
      "y": 2
    },
    "a"
  ],
  [
    {
      "x": 3,
      "y": 4
    },
    "b"
  ]
]

More details can be found here.

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

With the use of the bootstrap 4 utilities you could horizontally center an element itself by setting the horizontal margins to 'auto'.

To set the horizontal margins to auto you can use mx-auto . The m refers to margin and the x will refer to the x-axis (left+right) and auto will refer to the setting. So this will set the left margin and the right margin to the 'auto' setting. Browsers will calculate the margin equally and center the element. The setting will only work on block elements so the display:block needs to be added and with the bootstrap utilities this is done by d-block.

<button type="submit" class="btn btn-primary mx-auto d-block">Submit</button>

You can consider all browsers to fully support auto margin settings according to this answer Browser support for margin: auto so it's safe to use.

The bootstrap 4 class text-center is also a very good solution, however it needs a parent wrapper element. The benefit of using auto margin is that it can be done directly on the button element itself.

In Java, how to find if first character in a string is upper case without regex

There is many ways to do that, but the simplest seems to be the following one:

boolean isUpperCase = Character.isUpperCase("My String".charAt(0));

How do I write data to csv file in columns and rows from a list in python?

>>> import csv
>>> with open('test.csv', 'wb') as f:
...     wtr = csv.writer(f, delimiter= ' ')
...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>

To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

How to resolve 'unrecognized selector sent to instance'?

How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."

Copying, or creating the .h solved it for me.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How do I dynamically assign properties to an object in TypeScript?

dynamically assign properties to an object in TypeScript.

to do that You just need to use typescript interfaces like so:

interface IValue {
    prop1: string;
    prop2: string;
}

interface IType {
    [code: string]: IValue;
}

you can use it like that

var obj: IType = {};
obj['code1'] = { 
    prop1: 'prop 1 value', 
    prop2: 'prop 2 value' 
};

Seeking useful Eclipse Java code templates

Hamcrest Test with Static Imports

Here's a template to generate @Test methods with necessary hamcrest imports, if you want to use the new features of JUnit 4.8.2 (assertThat, is, hasItems, etc...)

@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
    // Arrange
    ${staticImport:importStatic('org.hamcrest.MatcherAssert.*','org.hamcrest.Matchers.*')}${cursor} 
    // Act

    // Assert

}

I already used it many times, when writing test.

What is Arrange-Act-Assert?

How to get rid of punctuation using NLTK tokenizer?

Take a look at the other tokenizing options that nltk provides here. For example, you can define a tokenizer that picks out sequences of alphanumeric characters as tokens and drops everything else:

from nltk.tokenize import RegexpTokenizer

tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven miles to go, yet.  Onward!')

Output:

['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']

Converting an OpenCV Image to Black and White

Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:

1. Read a grayscale image

import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)

2. Convert grayscale image to binary

(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:

thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

3. Save to disk

cv2.imwrite('bw_image.png', im_bw)

What is stability in sorting algorithms and why is it important?

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

Background: a "stable" sorting algorithm keeps the items with the same sorting key in order. Suppose we have a list of 5-letter words:

peach
straw
apple
spork

If we sort the list by just the first letter of each word then a stable-sort would produce:

apple
peach
straw
spork

In an unstable sort algorithm, straw or spork may be interchanged, but in a stable one, they stay in the same relative positions (that is, since straw appears before spork in the input, it also appears before spork in the output).

We could sort the list of words using this algorithm: stable sorting by column 5, then 4, then 3, then 2, then 1. In the end, it will be correctly sorted. Convince yourself of that. (by the way, that algorithm is called radix sort)

Now to answer your question, suppose we have a list of first and last names. We are asked to sort "by last name, then by first". We could first sort (stable or unstable) by the first name, then stable sort by the last name. After these sorts, the list is primarily sorted by the last name. However, where last names are the same, the first names are sorted.

You can't stack unstable sorts in the same fashion.

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

Remote origin already exists on 'git push' to a new repository

if you want to create a new repository with the same project inside the github and the previous Remote is not allowing you to do that in that case First Delete That Repository on github then you simply need to delete the .git folder C:\Users\Shiva\AndroidStudioProjects\yourprojectname\.git delete that folder,(make sure you click on hidden file because this folder is hidden )

Also click on the minus(Remove button) from the android studio Setting->VersionControl click here for removing the Version control from android And then you will be able to create new Repository.

Launching an application (.EXE) from C#?

Use System.Diagnostics.Process.Start() method.

Check out this article on how to use it.

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

How to use MySQL dump from a remote machine

mysqldump -h [domain name/ip] -u [username] -p[password] [databasename] > [filename.sql]

Python - Convert a bytes array into JSON format

Your bytes object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes to str and replace the quotes. Another option is to use ast.literal_eval; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

output

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "LogoType": "png",
        "Ref": 164611595
    }
]

As Antti Haapala mentions in the comments, we can use ast.literal_eval to convert my_bytes_value to a Python list, once we've decoded it to a string.

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

Generally, this problem arises because someone has saved data by printing its Python repr instead of using the json module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.

HTML text input allow only numeric input

So simple....

// In a JavaScript function (can use HTML or PHP).

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

In your form input:

<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>

With input max. (These above allows for a 12-digit number)

Git undo local branch delete

First: back up your entire directory, including the .git directory.

Second: You can use git fsck --lost-found to obtain the ID of the lost commits.

Third: rebase or merge onto the lost commit.

Fourth: Always think twice before using -D or --force with git :)

You could also read this good discussion of how to recover from this kind of error.

EDIT: By the way, don't run git gc (or allow it to run by itself - i.e. don't run git fetch or anything similar) or you may lose your commits for ever.

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

How to create a connection string in asp.net c#

Add this connection string tag in web.config file:

<connectionStrings>
  <add name="itmall" 
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>

And use it like you mentioned. :)

constant pointer vs pointer on a constant value

The easiest way to understand the difference is to think of the different possibilities. There are two objects to consider, the pointer and the object pointed to (in this case 'a' is the name of the pointer, the object pointed to is unnamed, of type char). The possibilities are:

  1. nothing is const
  2. the pointer is const
  3. the object pointed to is const
  4. both the pointer and the pointed to object are const.

These different possibilities can be expressed in C as follows:

  1. char * a;
  2. char * const a;
  3. const char * a;
  4. const char * const a;

I hope this illustrates the possible differences

What is the most effective way for float and double comparison?

In terms of the scale of quantities:

If epsilon is the small fraction of the magnitude of quantity (i.e. relative value) in some certain physical sense and A and B types is comparable in the same sense, than I think, that the following is quite correct:

#include <limits>
#include <iomanip>
#include <iostream>

#include <cmath>
#include <cstdlib>
#include <cassert>

template< typename A, typename B >
inline
bool close_enough(A const & a, B const & b,
                  typename std::common_type< A, B >::type const & epsilon)
{
    using std::isless;
    assert(isless(0, epsilon)); // epsilon is a part of the whole quantity
    assert(isless(epsilon, 1));
    using std::abs;
    auto const delta = abs(a - b);
    auto const x = abs(a);
    auto const y = abs(b);
    // comparable generally and |a - b| < eps * (|a| + |b|) / 2
    return isless(epsilon * y, x) && isless(epsilon * x, y) && isless((delta + delta) / (x + y), epsilon);
}

int main()
{
    std::cout << std::boolalpha << close_enough(0.9, 1.0, 0.1) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0, 1.1, 0.1) << std::endl;
    std::cout << std::boolalpha << close_enough(1.1,    1.2,    0.01) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0001, 1.0002, 0.01) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0, 0.01, 0.1) << std::endl;
    return EXIT_SUCCESS;
}

iOS 7 status bar back to iOS 6 default style in iPhone app?

This is cross-posted from a blog post I wrote, but here is the full rundown on status bars, navigation bars, and container view controllers on iOS 7:

  1. There is no way to preserve the iOS 6 style status bar layout. The status bar will always overlap your application on iOS 7

  2. Do not confuse status bar appearance with status bar layout. The appearance (light or default) does not affect how the status bar is laid out (frame/height/overlap). It is important to note as well that the system status bar no longer has any background color. When the API refers to UIStatusBarStyleLightContent, they mean white text on a clear background. UIStatusBarStyleDefault is black text on a clear background.

  3. Status bar appearance is controlled along one of two mutually-exclusive basis paths: you can either set them programmatically in the traditional manner, or UIKit will update the appearance for you based on some new properties of UIViewController. The latter option is on by default. Check your app’s plist value for “ViewController-Based Status Bar Appearance” to see which one you’re using. If you set this value to YES, every top-level view controller in your app (other than a standard UIKit container view controller) needs to override preferredStatusBarStyle, returning either the default or the light style. If you edit the plist value to NO, then you can manage the status bar appearance using the familiar UIApplication methods.

  4. UINavigationController will alter the height of its UINavigationBar to either 44 points or 64 points, depending on a rather strange and undocumented set of constraints. If the UINavigationController detects that the top of its view’s frame is visually contiguous with its UIWindow’s top, then it draws its navigation bar with a height of 64 points. If its view’s top is not contiguous with the UIWindow’s top (even if off by only one point), then it draws its navigation bar in the “traditional” way with a height of 44 points. This logic is performed by UINavigationController even if it is several children down inside the view controller hierarchy of your application. There is no way to prevent this behavior.

  5. If you supply a custom navigation bar background image that is only 44 points (88 pixels) tall, and the UINavigationController’s view’s bounds matches the UIWindow’s bounds (as discussed in #4), the UINavigationController will draw your image in the frame (0,20,320,44), leaving 20 points of opaque black space above your custom image. This may confuse you into thinking you are a clever developer who bypassed rule #1, but you are mistaken. The navigation bar is still 64 points tall. Embedding a UINavigationController in a slide-to-reveal style view hierarchy makes this abundantly clear.

  6. Beware of the confusingly-named edgesForExtendedLayout property of UIViewController. Adjusting edgesForExtendedLayout does nothing in most cases. The only way UIKit uses this property is if you add a view controller to a UINavigationController, then the UINavigationController uses edgesForExtendedLayout to determine whether or not its child view controller should be visible underneath the navigation bar / status bar area. Setting edgesForExtendedLayout on the UINavigationController itself does nothing to alter whether or not the UINavigationController has a 44 or 64 point high navigation bar area. See #4 for that logic. Similar layout logic applies to the bottom of your view when using a toolbar or UITabBarController.

  7. If all you are trying to do is prevent your custom child view controller from underlapping the navigation bar when inside a UINavigationController, then set edgesForExtendedLayout to UIRectEdgeNone (or at least a mask that excludes UIRectEdgeTop). Set this value as early as possible in the life cycle of your view controller.

  8. UINavigationController and UITabBarController will also try to pad the contentInsets of table views and collection views in its subview hierarchy. It does this in a manner similar to the status bar logic from #4. There is a programmatic way of preventing this, by setting automaticallyAdjustsScrollViewInsets to NO for your table views and collection views (it defaults to YES). This posed some serious problems for Whisper and Riposte, since we use contentInset adjustments to control the layout of table views in response to toolbar and keyboard movements.

  9. To reiterate: there is no way to return to iOS 6 style status bar layout logic. In order to approximate this, you have to move all the view controllers of your app into a container view that is offset by 20 points from the top of the screen, leaving an intentionally black view behind the status bar to simulate the old appearance. This is the method we ended up using in Riposte and Whisper.

  10. Apple is pushing very hard to ensure that you don’t try to do #9. They want us to redesign all our apps to underlap the status bar. There are many cogent arguments, however, for both user experience and technical reasons, why this is not always a good idea. You should do what is best for your users and not simply follow the whimsy of the platform.

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

Check if date is a valid one

Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

It is badDate coming from your picker in this example

https://jsfiddle.net/xs8tvox9/

var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";

var splittedDate = badDate.split('-');

if (splittedDate.length == 3) {
  var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
  alert(d.isValid())
} else {
  //incorrectFormat
}

Efficient way to add spaces between characters in a string

The most efficient way is to take input make the logic and run

so the code is like this to make your own space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

but if you want to use what python give then use this code

need2 = input("Write a string:- ")

print(" ".join(need2))

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

Detecting an undefined object property

Also, the same things can be written shorter:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}

Function return value in PowerShell

With PowerShell 5 we now have the ability to create classes. Change your function into a class, and return will only return the object immediately preceding it. Here is a real simple example.

class test_class {
    [int]return_what() {
        Write-Output "Hello, World!"
        return 808979
    }
}
$tc = New-Object -TypeName test_class
$tc.return_what()

If this was a function the expected output would be

Hello World
808979

but as a class the only thing returned is the integer 808979. A class is sort of like a guarantee that it will only return the type declared or void.

Array String Declaration

As Tr?n Si Long suggested, use

String[] mStrings = new String[title.length];

And replace string concatation with proper parenthesis.

mStrings[i] = (urlbase + (title[i].replaceAll("[^a-zA-Z]", ""))).toLowerCase() + imgSel;

Try this. If it's problem due to concatation, it will be resolved with proper brackets. Hope it helps.

Storing and Retrieving ArrayList values from hashmap

You can use like this(Though the random number generator logic is not upto the mark)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

OUTPUT

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

How do I share a global variable between c files?

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);

How to find my realm file?

I have taken this one step further. I have created a swift file called RealmFunctions and in it, I have created this function

    import RealmSwift
    func realmAndPath() -> Realm {
        if dev {
            // location of my desktop
            return try! Realm(path: "/Users/slynch/Desktop/TestRealm.realm")
        } else {
            return try! Realm()
        }
    }

Now in my main view controller, I have a global boolean variable called dev

var dev: Bool = true // when in development mode
var dev: Bool = false // when I want to run on my device or upload to app stor.

Now, all I have to do in my code is

let realm = realmAndPath()

So when in development mode, I can find my realm database on my desktop and can open in Realm Browser.

Nullable property to entity field, Entity Framework through Code First

In Ef .net core there are two options that you can do; first with data annotations:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Or with fluent api:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired(false)//optinal case
            .IsRequired()//required case
            ;
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

There are more details here

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

AngularJS ngClass conditional

Using ng-class inside ng-repeat

<table>
    <tbody>
            <tr ng-repeat="task in todos"
                ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
              'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
                <td>{{$index + 1}}</td>
                <td>{{task.name}}</td>
                <td>{{task.date|date:'yyyy-MM-dd'}}</td>
                <td>{{task.status}}</td>
            </tr>
    </tbody>
</table>

For each status in task.status a different class is used for the row.

How to read data when some numbers contain commas as thousand separator?

Not sure about how to have read.csv interpret it properly, but you can use gsub to replace "," with "", and then convert the string to numeric using as.numeric:

y <- c("1,200","20,000","100","12,111")
as.numeric(gsub(",", "", y))
# [1]  1200 20000 100 12111

This was also answered previously on R-Help (and in Q2 here).

Alternatively, you can pre-process the file, for instance with sed in unix.

How to pass a variable from Activity to Fragment, and pass it back?

To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.

On the newInstance function of your fragment you add the arguments you wanna send to it:

/**
 * Create a new instance of DetailsFragment, initialized to
 * show the text at 'index'.
 */
public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:

Bundle args = getArguments();
int index = args.getInt("index", 0);

If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.

Documentation tutorial:

http://developer.android.com/training/basics/fragments/communicating.html

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

Binding arrow keys in JS/jQuery

With coffee & Jquery

  $(document).on 'keydown', (e) ->
    switch e.which
      when 37 then console.log('left key')
      when 38 then console.log('up key')
      when 39 then console.log('right key')
      when 40 then console.log('down key')
    e.preventDefault()

Cocoa Autolayout: content hugging vs content compression resistance priority

Content Hugging and Content Compression Resistence Priorities work for elements which can calculate their size intrinsically depending upon the contents which are coming in.

From Apple docs:

enter image description here

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

What is the bit size of long on 64-bit Windows?

Microsoft has also defined UINT_PTR and INT_PTR for integers that are the same size as a pointer.

Here is a list of Microsoft specific types - it's part of their driver reference, but I believe it's valid for general programming as well.

How can I schedule a job to run a SQL query daily?

To do this in t-sql, you can use the following system stored procedures to schedule a daily job. This example schedules daily at 1:00 AM. See Microsoft help for details on syntax of the individual stored procedures and valid range of parameters.

DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);

SET @job_name = N'Some Title';
SET @description = N'Periodically do something';
SET @owner_login_name = N'login';
SET @database_name = N'Database_Name';

-- Delete job if it already exists:
IF EXISTS(SELECT job_id FROM msdb.dbo.sysjobs WHERE (name = @job_name))
BEGIN
    EXEC msdb.dbo.sp_delete_job
        @job_name = @job_name;
END

-- Create the job:
EXEC  msdb.dbo.sp_add_job
    @job_name=@job_name, 
    @enabled=1, 
    @notify_level_eventlog=0, 
    @notify_level_email=2, 
    @notify_level_netsend=2, 
    @notify_level_page=2, 
    @delete_level=0, 
    @description=@description, 
    @category_name=N'[Uncategorized (Local)]', 
    @owner_login_name=@owner_login_name;

-- Add server:
EXEC msdb.dbo.sp_add_jobserver @job_name=@job_name;

-- Add step to execute SQL:
EXEC msdb.dbo.sp_add_jobstep
    @job_name=@job_name,
    @step_name=N'Execute SQL', 
    @step_id=1, 
    @cmdexec_success_code=0, 
    @on_success_action=1, 
    @on_fail_action=2, 
    @retry_attempts=0, 
    @retry_interval=0, 
    @os_run_priority=0, 
    @subsystem=N'TSQL', 
    @command=N'EXEC my_stored_procedure; -- OR ANY SQL STATEMENT', 
    @database_name=@database_name, 
    @flags=0;

-- Update job to set start step:
EXEC msdb.dbo.sp_update_job
    @job_name=@job_name, 
    @enabled=1, 
    @start_step_id=1, 
    @notify_level_eventlog=0, 
    @notify_level_email=2, 
    @notify_level_netsend=2, 
    @notify_level_page=2, 
    @delete_level=0, 
    @description=@description, 
    @category_name=N'[Uncategorized (Local)]', 
    @owner_login_name=@owner_login_name, 
    @notify_email_operator_name=N'', 
    @notify_netsend_operator_name=N'', 
    @notify_page_operator_name=N'';

-- Schedule job:
EXEC msdb.dbo.sp_add_jobschedule
    @job_name=@job_name,
    @name=N'Daily',
    @enabled=1,
    @freq_type=4,
    @freq_interval=1, 
    @freq_subday_type=1, 
    @freq_subday_interval=0, 
    @freq_relative_interval=0, 
    @freq_recurrence_factor=1, 
    @active_start_date=20170101, --YYYYMMDD
    @active_end_date=99991231, --YYYYMMDD (this represents no end date)
    @active_start_time=010000, --HHMMSS
    @active_end_time=235959; --HHMMSS

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

SQL select only rows with max value on a column

None of these answers have worked for me.

This is what worked for me.

with score as (select max(score_up) from history)
select history.* from score, history where history.score_up = score.max

What's causing my java.net.SocketException: Connection reset?

I got this error when the text file I was trying to read contained a string that matched an antivirus signature on our firewall.

How to detect input type=file "change" for the same file?

Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)

onInputClick = (event) => {
    event.target.value = ''
}

<input type="file" onChange={onFileChanged} onClick={onInputClick} />

Using TypeScript

onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
    const element = event.target as HTMLInputElement
    element.value = ''
}

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

Since your integer array cannot contain a value larger than Integer.MAX_VALUE and smaller than Integer.MIN_VALUE your code works across all edge cases.

HttpClient not supporting PostAsJsonAsync method C#

PostAsJsonAsync is no longer in the System.Net.Http.dll (.NET 4.5.2). You can add a reference to System.Net.Http.Formatting.dll, but this actually belongs to an older version. I ran into problems with this on our TeamCity build server, these two wouldn't cooperate together.

Alternatively, you can replace PostAsJsonAsyncwith a PostAsync call, which is just part of new dll. Replace

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;

With:

var response = client.PostAsync("api/AgentCollection", new StringContent(
   new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;

Note that JavaScriptSerializer is in the namespace: System.Web.Script.Serialization.

You will have to add an assembly reference in your csproj: System.Web.Extensions.dll

See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836

How to update two tables in one statement in SQL Server 2005?

You can update two tables in one query.

UPDATE Table1, Table2 
SET Table1.LastName="DR. XXXXXX", Table2.WAprrs="start,stop" 
WHERE Table1.id=Table2.id AND Table1.id="010008";

How do I bottom-align grid elements in bootstrap fluid layout

You need to add some style for span6, smthg like that:

.row-fluid .span6 {
  display: table-cell;
  vertical-align: bottom;
  float: none;
}

and this is your fiddle: http://jsfiddle.net/sgB3T/

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

write newline into a file

the other answers should work. however I wanna mention

from java doc:

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

reading your method codes, you are about to write String to the file, what you were doing is convert String to raw bytes, then write so I think using FileWriter is not a bad idea.

And for the newline problem, Writer has method .write(String), which is convenient to use.

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

Checkout another branch when there are uncommitted changes on the current branch

You have two choices: stash your changes:

git stash

then later to get them back:

git stash apply

or put your changes on a branch so you can get the remote branch and then merge your changes onto it. That's one of the greatest things about git: you can make a branch, commit to it, then fetch other changes on to the branch you were on.

You say it doesn't make any sense, but you are only doing it so you can merge them at will after doing the pull. Obviously your other choice is to commit on your copy of the branch and then do the pull. The presumption is you either don't want to do that (in which case I am puzzled that you don't want a branch) or you are afraid of conflicts.

Error: vector does not name a type

use:

std::vector <Acard> playerHand;

everywhere qualify it by std::

or do:

using std::vector;

in your cpp file.

You have to do this because vector is defined in the std namespace and you do not tell your program to find it in std namespace, you need to tell that.

How do I access Configuration in any class in ASP.NET Core?

In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.

Read A Step by Step Guide for ASP.NET Core Configuration

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

Create new user in MySQL and give it full access to one database

In case the host part is omitted it defaults to the wildcard symbol %, allowing all hosts.

CREATE USER 'service-api';

GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'

SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

Finding element in XDocument?

The problem is that Elements only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants method:

var query = from c in xmlFile.Descendants("Band")

OS X cp command in Terminal - No such file or directory

On OS X Sierra 10.12, None of the above work. cd then drag and drop does not work. No spacing or other fixes work. I cannot cd into ~/Library Support using any technique that I can find. Is this a security feature?
I'm going to try disabling SIP and see if it makes a difference.

Plotting in a non-blocking way with Matplotlib

I figured out that the plt.pause(0.001) command is the only thing needed and nothing else.

plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.

Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.

The documentation of the plt.pause(interval) command states:

If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.

and this is pretty much exactly what we want. Try this code:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 51)               # x coordinates  
         
for z in range(10, 50):

    y = np.power(x, z/10)          # y coordinates of plot for animation

    plt.cla()                      # delete previous plot
    plt.axis([-50, 50, 0, 10000])  # set axis limits, to avoid rescaling
    plt.plot(x, y)                 # generate new plot
    plt.pause(0.1)                 # pause 0.1 sec, to force a plot redraw

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How can I get a process handle by its name in C++?

There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses, OpenProcess, EnumProcessModules, and GetModuleBaseName.

The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot to get a snapshot of the process list, walk over it with Process32First and Process32Next, which provides module name and process ID, until you find the one you want, and then call OpenProcess to get a handle.

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

:last is not part of the css spec, this is jQuery specific.

you should be looking for last-child

var first = div.querySelector('[move_id]:first-child');
var last  = div.querySelector('[move_id]:last-child');

How do I check whether a checkbox is checked in jQuery?

if($('#isAgeSelected').prop('checked')) {
    // do your action 
}

Delete all data in SQL Server database

As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

How to get the selected radio button’s value?

document.forms.your-form-name.elements.radio-button-name.value

How to return multiple objects from a Java method?

All possible solutions will be a kludge (like container objects, your HashMap idea, “multiple return values” as realized via arrays). I recommend regenerating the comma-separated list from the returned List. The code will end up being a lot cleaner.

CSS background-image not working

In addition to display:block OR display:inline-block

Try giving sufficient padding to your .btn-pToolName and make sure you have the correct values for background-position

To draw an Underline below the TextView in Android

underline a textview in android

5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML

  1. String html = "<u>Underline using Html.fromHtml()</u>"; textview.setText(Html.fromHtml(html));

But Html.fromHtml(String resource) was deprecated in API 24.

So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.

`implementation 'androidx.core:core:1.0.1'`
  1. String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"; //underline textview using HtmlCompat.fromHtml() method textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));

Using strings.xml,

  1. <string name="underline_text">1.3 &lt;u>Underline using HtmlCompat.fromHtml() and string resource&lt;/u></string>

textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));

using PaintFlags

  1. textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); textview2.setText("2. Underline using setPaintFlags()");

using SpannableString

`String content1 = "3.1 Underline using SpannableString";
        SpannableString spannableString1 = new SpannableString(content1);
        spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        textview31.setText(spannableString1);`

How to configure Glassfish Server in Eclipse manually

I had the same issue. Not able to install neither using Marketplace nor Servers tab.

Following is the alternative.

1) Help -> Install New Software

2) Use url : http://download.oracle.com/otn_software/oepe/12.1.3.6/luna/repository Above is the OEPE tool provided by oracle for EE development.

3) From all the suggestions, select glassfish tools.

4) Install it.

5) Restart eclipse.

Eclipse 4.4.2 Luna JDK : 1.8

Open files always in a new tab

Open in new Tab Solution:

  1. Open the command palette by: Cmd + Shift + K
  2. Open settings file by: Preferences: Open Settings (JSON)
  3. Under user setting, enable Tabs by: "workbench.editor.showTabs": true

How to shutdown a Spring Boot Application in a correct way?

All of the answers seem to be missing the fact that you may need to complete some portion of work in coordinated fashion during graceful shutdown (for example, in an enterprise application).

@PreDestroy allows you to execute shutdown code in the individual beans. Something more sophisticated would look like this:

@Component
public class ApplicationShutdown implements ApplicationListener<ContextClosedEvent> {
     @Autowired ... //various components and services

     @Override
     public void onApplicationEvent(ContextClosedEvent event) {
         service1.changeHeartBeatMessage(); // allows loadbalancers & clusters to prepare for the impending shutdown
         service2.deregisterQueueListeners();
         service3.finishProcessingTasksAtHand();
         service2.reportFailedTasks();
         service4.gracefullyShutdownNativeSystemProcessesThatMayHaveBeenLaunched(); 
         service1.eventLogGracefulShutdownComplete();
     }
}

Easiest way to convert month name to month number in JS ? (Jan = 01)

Here is a modified version of the chosen answer:

getMonth("Feb")
function getMonth(month) {
  d = new Date().toString().split(" ")
  d[1] = month
  d = new Date(d.join(' ')).getMonth()+1
  if(!isNaN(d)) {
    return d
  }
  return -1;
}

Bootstrap datepicker disabling past dates without current date

It depends on what format you put on the datepicker So first we gave it the format.

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){
        dd='0'+dd;
    } 
    if(mm<10){
        mm='0'+mm;
    } 
    var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want

Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )

    //Datetimepicker
    $(function () {
        $('#datetimepicker1').datetimepicker({
            minDate: today, //pass today's date
            daysOfWeekDisabled: [0],
            locale: 'es',
            inline: true,
            format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)
            sideBySide: true
        });
    });

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

Thanks for asking; the JDK does not seem to interact with the Windows registry.

However, the JRE does in certain instances.

Link: http://www.rgagnon.com/javadetails/java-0604.html

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

SQL WHERE ID IN (id1, id2, ..., idn)

Option 1 is the only good solution.

Why?

  • Option 2 does the same but you repeat the column name lots of times; additionally the SQL engine doesn't immediately know that you want to check if the value is one of the values in a fixed list. However, a good SQL engine could optimize it to have equal performance like with IN. There's still the readability issue though...

  • Option 3 is simply horrible performance-wise. It sends a query every loop and hammers the database with small queries. It also prevents it from using any optimizations for "value is one of those in a given list"

Something like 'contains any' for Java set?

Stream::anyMatch

Since Java 8 you could use Stream::anyMatch.

setA.stream().anyMatch(setB::contains)

Fatal error: Call to undefined function curl_init()

Don't have enough reputation to comment yet. Using Ubuntu and a simple:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart

Did NOT work for me.

For some reason curl.so was installed in a location not picked up by default. I checked the extension_dir in my php.ini and copied over the curl.so to my extension_dir

cp /usr/lib/php5/20090626/curl.so  /usr/local/lib/php/extensions/no-debug-non-zts-20090626

Hope this helps someone, adjust your path locations accordingly.

Linq code to select one item

Just to make someone's life easier, the linq query with lambda expression

(from x in Items where x.Id == 123 select x).FirstOrDefault();

does result in an SQL query with a select top (1) in it.

How to append one file to another in Linux from the shell?

cat can be the easy solution but that become very slow when we concat large files, find -print is to rescue you, though you have to use cat once.

amey@xps ~/work/python/tmp $ ls -lhtr
total 969M
-rw-r--r-- 1 amey amey 485M May 24 23:54 bigFile2.txt
-rw-r--r-- 1 amey amey 485M May 24 23:55 bigFile1.txt

 amey@xps ~/work/python/tmp $ time cat bigFile1.txt bigFile2.txt >> out.txt

real    0m3.084s
user    0m0.012s
sys     0m2.308s


amey@xps ~/work/python/tmp $ time find . -maxdepth 1 -type f -name 'bigFile*' -print0 | xargs -0 cat -- > outFile1

real    0m2.516s
user    0m0.028s
sys     0m2.204s

Where can I view Tomcat log files in Eclipse?

I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.

But, if you're after the catalina.out log file then follow the directions below:

  • In the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.

  • Click on "Open launch configuration". Click on the "Common" tab.

  • Towards the bottom of the screen you can check the "File" checkbox and then specify a file that can be used to log your console (catalina.out) output.

  • Finally, restart the Tomcat server.

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

Bring element to front using CSS

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Use one of those.

Reset IntelliJ UI to Default

Recent Versions

Window -> Restore Default Layout

(Thanks to Seven4X's answer)

Older Versions

You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.

It depends on the OS:

https://intellij-support.jetbrains.com/entries/23358108

Apple Cover-flow effect using jQuery or other library?

Check out momoflow: http://flow.momolog.info True coverflow effect, and performant on Webkit (Safari and Chrome) and Opera, ok on Firefox.

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

"Cannot GET /" with Connect on Node.js

The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

How to use wget in php?

I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.

http://php.net/manual/de/function.xml-parse.php

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.

I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.

For simplicity, here's your same code re-written with a function callback provided by the calling controller:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Now, $http actually already returns a $promise, so this can be re-written:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

How to get the pure text without HTML element using JavaScript?

You want to change the I am working in ABC company. to I am working in ABC company.. These are the same strings, so I don't see a reason to, but you can accomplish this by using the JavaScript innerHTML or textContent.

element.innerHTML is a property that defines the HTML inside an element. If you type element.innerHTML = "<strong>This is bold</strong>, it'll make the text "This is bold" bold text.

element.textContent, on the other hand, sets the text in an element. If you use element.textContent = "<strong>This is bold</strong>, The text "This is bold" will not be bold. The user will literally see the text "This is bold

In your case, you can use either one. I'll use .textContent. The code to change the <p> element is below.

function get_content(){
   document.getElementById("txt").textContent = "I am working in ABC company.";
}

<input type="button" onclick="get_content()" value="Get Content"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>

This, unfortunately, will not change it because it'll change it to the same exact text. You can chance that by changing the string "I am working in ABC company." to something else.

Eclipse error "ADB server didn't ACK, failed to start daemon"

Thanks, @jowett, I have solved my same problem, doing these steps

Step 1: CTRL+Shift+Esc to open the task manager, which has adb.exe process and end (kill) that process

Step 2: Now, close the eclipse, which is currently running on my computer.

Step 3: Again, restart eclipse then solved that problem.


For those using OS X

killall adb

For those using Windows

adb kill-server

should do the trick.

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

You could also create your own conversion function, inside which you can use exception blocks:

CREATE OR REPLACE FUNCTION convert_to_integer(v_input text)
RETURNS INTEGER AS $$
DECLARE v_int_value INTEGER DEFAULT NULL;
BEGIN
    BEGIN
        v_int_value := v_input::INTEGER;
    EXCEPTION WHEN OTHERS THEN
        RAISE NOTICE 'Invalid integer value: "%".  Returning NULL.', v_input;
        RETURN NULL;
    END;
RETURN v_int_value;
END;
$$ LANGUAGE plpgsql;

Testing:

=# select convert_to_integer('1234');
 convert_to_integer 
--------------------
               1234
(1 row)

=# select convert_to_integer('');
NOTICE:  Invalid integer value: "".  Returning NULL.
 convert_to_integer 
--------------------

(1 row)

=# select convert_to_integer('chicken');
NOTICE:  Invalid integer value: "chicken".  Returning NULL.
 convert_to_integer 
--------------------

(1 row)

Using Google maps API v3 how do I get LatLng with a given address?

If you need to do this on the backend you can use the following URL structure:

https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]

Sample PHP code using curl:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

$json = curl_exec($curl);

curl_close ($curl);

$obj = json_decode($json);

See additional documentation for more details and expected json response.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.

Is there a way to delete all the data from a topic or delete the topic before every run?

For brew users

If you're using brew like me and wasted a lot of time searching for the infamous kafka-logs folder, fear no more. (and please do let me know if that works for you and multiple different versions of Homebrew, Kafka etc :) )

You're probably going to find it under:

Location:

/usr/local/var/lib/kafka-logs


How to actually find that path

(this is also helpful for basically every app you install through brew)

1) brew services list

kafka started matbhz /Users/matbhz/Library/LaunchAgents/homebrew.mxcl.kafka.plist

2) Open and read that plist you found above

3) Find the line defining server.properties location open it, in my case:

  • /usr/local/etc/kafka/server.properties

4) Look for the log.dirs line:

log.dirs=/usr/local/var/lib/kafka-logs

5) Go to that location and delete the logs for the topics you wish

6) Restart Kafka with brew services restart kafka

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Windows service start failure: Cannot start service from the command line or debugger

Your code has nothing to do with the service installation, it is not the problem.

In order to test the service, you must install it as indicated.

For more information about installing your service : Installing and Uninstalling Services

How do I create a Java string from the contents of a file?

If you're looking for an alternative that doesn't involve a third-party library (e.g. Commons I/O), you can use the Scanner class:

private String readFile(String pathname) throws IOException {

    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int)file.length());        

    try (Scanner scanner = new Scanner(file)) {
        while(scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + System.lineSeparator());
        }
        return fileContents.toString();
    }
}

format a Date column in a Data Frame

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)

Matplotlib: "Unknown projection '3d'" error

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')

In fact as long as the Axes3D import is present the line

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')

as used by the OP also works. (checked with matplotlib version 1.3.1)

Best GUI designer for eclipse?

Here is a quite good but old comparison http://wiki.computerwoche.de/doku.php/programmierung/gui-builder_fuer_eclipse Window Builder Pro is now free at Google Web Toolkit

Redirect to external URL with return in laravel

For Laravel 8 you can also use

Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');

This also works with external URLs

See: https://austencam.com/posts/setting-up-an-m1-mac-for-laravel-development-with-homebrew-php-mysql-valet-and-redis

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

How to hide soft keyboard on android after clicking outside EditText?

Well I manage to somewhat solve the problem, I overrode the dispatchTouchEvent on my activity, there I am using the following to hide the keyboard.

 /**
 * Called to process touch screen events. 
 */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    switch (ev.getAction()){
        case MotionEvent.ACTION_DOWN:
            touchDownTime = SystemClock.elapsedRealtime();
            break;

        case MotionEvent.ACTION_UP:
            //to avoid drag events
            if (SystemClock.elapsedRealtime() - touchDownTime <= 150){  

                EditText[] textFields = this.getFields();
                if(textFields != null && textFields.length > 0){

                    boolean clickIsOutsideEditTexts = true;

                    for(EditText field : textFields){
                        if(isPointInsideView(ev.getRawX(), ev.getRawY(), field)){
                            clickIsOutsideEditTexts = false;
                            break;
                        }
                    }

                    if(clickIsOutsideEditTexts){
                        this.hideSoftKeyboard();
                    }               
                } else {
                    this.hideSoftKeyboard();
                }
            }
            break;
    }

    return super.dispatchTouchEvent(ev);
}

EDIT: The getFields() method is just a method that returns an array with the textfields in the view. To avoid creating this array on every touch, I created an static array called sFields, which is returned at the getFields() method. This array is initialized on the onStart() methods such as:

sFields = new EditText[] {mUserField, mPasswordField};


It is not perfect, The drag event time is only based on heuristics so sometimes it doesnt hide when performing long clics, and I also finished by creating a method to get all the editTexts per view; else the keyboard would hide and show when clicking other EditText.

Still, cleaner and shorter solutions are welcome

How to hide underbar in EditText

You can set the EditText to have a custom transparent drawable or just use

android:background="@android:color/transparent"

or

android:background="@null"

or Programmatically

editText.setBackgroundResource(android.R.color.transparent);

Determining the version of Java SDK on the Mac

Open a terminal and type: java -version, or javac -version.

If you have all the latest updates for Snow Leopard, you should be running JDK 1.6.0_20 at this moment (the same as Oracle's current JDK version).

Javascript equivalent of php's strtotime()?

There are few modules that provides similar behavior, but not exactly like PHP's strtotime. Among few alternatives I found date-util yields the best results.

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

How do you specify the Java compiler version in a pom.xml file?

Generally you don't want to value only the source version (javac -source 1.8 for example) but you want to value both the source and the target version (javac -source 1.8 -target 1.8 for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9).
Maven that wraps the javac command provides multiple ways to convey all these JVM standard options.

How to specify the JDK version?

Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties to specify the source and the target are equivalent.

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

and

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

are equivalent according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

<release> tag — new way to specify Java version in maven-compiler-plugin 3.6

You can use the release argument :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>9</release>
    </configuration>
</plugin>

You could also declare just the user property maven.compiler.release:

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time the last one will not be enough as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.

Which is the best way to specify the JDK version?

Java 8 and below

Neither maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin is better. It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Java 9 and later

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

Is Python faster and lighter than C++?

It's the same problem with managed and easy to use programming language as always - they are slow (and sometimes memory-eating).

These are languages to do control rather than processing. If I would have to write application to transform images and had to use Python too all the processing could be written in C++ and connected to Python via bindings while interface and process control would be definetely Python.

How can I clear previous output in Terminal in Mac OS X?

clear && printf '\e[3J'

clears out everything, and it works well on OS X as well. Very neat.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

bodyParser is deprecated express 4

In older versions of express, we had to use:

app.use(express.bodyparser()); 

because body-parser was a middleware between node and express. Now we have to use it like:

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

Powershell: convert string to number

I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.

function universalToDate
{
 param (
    $paramValue
  )
    $retVal=""


    if ($paramValue)
    {
        $epoch=[datetime]'1/1/1970'
        [long]$returnedLong = 0
        [bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
        if ($result -eq 1)
        {
            $val=$returnedLong/1000.0
            $retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
        }
    }
    else
    {
        $retVal=$null
    }
    return($retVal)
 }

Skipping every other element after the first

Alternatively, you could do:

for i in range(0, len(a), 2):
    #do something

The extended slice notation is much more concise, though.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

You should add namespace if you are not using it:

System.Windows.Forms.MessageBox.Show("Some text", "Some title", 
    System.Windows.Forms.MessageBoxButtons.OK, 
    System.Windows.Forms.MessageBoxIcon.Error);

Alternatively, you can add at the begining of your file:

using System.Windows.Forms

and then use (as stated in previous answers):

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

This is not an error message but a warning. It is very clearly explained in their website as :

This warning, i.e. not an error, message is reported when no SLF4J providers could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. Note that these providers must target slf4j-api 1.8 or later.

In the absence of a provider, SLF4J will default to a no-operation (NOP) logger provider.

https://www.slf4j.org/codes.html#StaticLoggerBinder

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

MySQL Workbench: How to keep the connection alive

in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection) enter image description here

SQL Server® 2016, 2017 and 2019 Express full download

Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.

Organizing a multiple-file Go project

Let's explorer how the go get repository_remote_url command manages the project structure under $GOPATH. If we do a go get github.com/gohugoio/hugo It will clone the repository under

$GOPATH/src/repository_remote/user_name/project_name


$GOPATH/src/github.com/gohugoio/hugo

This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under

  • Libraries (no executable binaries)
  • Single Project (contains only 1 executable binary)
  • Tooling Projects (contains multiple executable binaries)

Generally golang project files can be packaged under any design principles such as DDD, POD

Most of the available go projects follows this Package Oriented Design

Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal package those packages can't can communicate with each other


Libraries

  • Projects such as database drivers, qt can put under this category.
  • Some libraries such as color, now follows a flat structure without any other packages.
  • Most of these library projects manages a package called internal.
  • /internal package is mainly used to hide the implementation from other projects.
  • Don't have any executable binaries, so no files that contains the main func.

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              internal/
              other_pkg/

Single Project

  • Projects such as hugo, etcd has a single main func in root level and.
  • Target is to generate one single binary

Tooling Projects

  • Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
  • cmd/ package manages the number of binaries (tools) that we want to build

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              cmd/
                binary_one/
                   main.go
                binary_two/
                   main.go
                binary_three/
                   main.go
              other_pkg/

Genymotion error at start 'Unable to load virtualbox'

For Windows there are 2 installers. Did you use the bundle containing VirtualBox installer? It is call Windows 32/64 bits (with VirtualBox).

insert data into database with codeigniter

Try this in your model:

function order_summary_insert()
    $OrderLines=$this->input->post('orderlines');
    $CustomerName=$this->input->post('customer');
    $data = array(
        'OrderLines'=>$OrderLines,
        'CustomerName'=>$CustomerName
    );

    $this->db->insert('Customer_Orders',$data);
}

Try to use controller just to control the view and models always post your values in model. it makes easy to understand. Your controller will be:

function new_blank_order_summary() {
    $this->sales_model->order_summary_insert($data);
    $this->load->view('sales/new_blank_order_summary');
}

Populating a razor dropdownlist from a List<object> in MVC

  @Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
    Value = item.RecordID.ToString(),
    Text = item.Name.ToString(),
     Selected = "select" == item.RecordID.ToString()
}))

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

Mailto links do nothing in Chrome but work in Firefox?

The usual <a href="mailto:[email protected]"></a> should work, but remember you must have a default email program set on your computer. For ex, I'm using Ubuntu 14.04 and the default email is thunderbird, which works fine.

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

Batch Script to Run as Administrator

If all above answers is not to your liking you can use autoIT to run your file (or what ever file) as a specific user with their credentials.

Sample of a script that will run a program using that users privelages.

installAdmin()

Func installAdmin()
    ; Change the username and password to the appropriate values for your system.
    Local $sUserName = "xxxxx"
    Local $sPassword = "xxx"
    Local $sDirectory = "C:\ASD4VM\Download\"
    Local $sFiletoRun = "Inst_with_Privileges.bat"

    RunAsWait($sUserName, @ComputerName, $sPassword, 0, $sDirectory & $sFiletoRun)
EndFunc   ;==>Example

AutoIT can be found here. -> It uses a .ua3 format that is compiled to a .exe file that can be run.

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

How do I connect to this localhost from another computer on the same network?

it may be that your firewalls are preventing you from accessing the localhost's webserver.
Put the IP addresses of both of your computers' internet security antivirus network security as safe IP addresses if required.
How to find the IP address of your windows PC: Start > (Run) type in: cmd (Enter)
(This opens the black box command prompt)
type in ipconfig (Enter)
Let's say your Apache or IIS webserver is installed on your PC: 192.168.0.3
and you want to access your webserver with your laptop. (laptop's IP is 192.168.0.5)
On your PC you type in: http://localhost/ inside your Firefox or Internet Eplorer browser to access your data on your webserver.
On your laptop you type in http://192.168.0.3/ to access your webserver on your PC.

For all these things to work you need have installed a webserver correctly (e.g. IIS, Apache, XAMP, WAMP etc).

If it does not work, try to ping your PC from your laptop:
Open up command propmt on your laptop: Start > cmd (Enter)
ping 192.168.1.3 (Enter)
If the pinging fails, then firewalls are blocking your connection or your network cabling is faulty. Restart your modem or network switch and your machines.
Close programs such as chat programs that are using your ports.
You can also try a diffrent port number: http:192.168.0.3:80 or http:192.168.0.3:81 or any random number at the end

AngularJS - Animate ng-view transitions

Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS

await vs Task.Wait - Deadlock?

Based on what I read from different sources:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

To wait for a single task to complete, you can call its Task.Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

This article is also a good read.

PHP Checking if the current date is before or after a set date

if (strtotime($date) > mktime(0,0,0)) should do the job.

PHP Get name of current directory

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__) 

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

You can use basename() to get the trailing part of the path :)

In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

Eg:

main.php
libs/common.php
libs/images/editor.php

In your common.php you need to use functions in editor.php, so you use

common.php:

require_once dirname(__FILE__) . '/images/editor.php';

main.php:

require_once libs/common.php

That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

How to handle button clicks using the XML onClick within Fragments

ButterKnife is probably the best solution for the clutter problem. It uses annotation processors to generate the so called "old method" boilerplate code.

But the onClick method can still be used, with a custom inflator.

How to use

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup cnt, Bundle state) {
    inflater = FragmentInflatorFactory.inflatorFor(inflater, this);
    return inflater.inflate(R.layout.fragment_main, cnt, false);
}

Implementation

public class FragmentInflatorFactory implements LayoutInflater.Factory {

    private static final int[] sWantedAttrs = { android.R.attr.onClick };

    private static final Method sOnCreateViewMethod;
    static {
        // We could duplicate its functionallity.. or just ignore its a protected method.
        try {
            Method method = LayoutInflater.class.getDeclaredMethod(
                    "onCreateView", String.class, AttributeSet.class);
            method.setAccessible(true);
            sOnCreateViewMethod = method;
        } catch (NoSuchMethodException e) {
            // Public API: Should not happen.
            throw new RuntimeException(e);
        }
    }

    private final LayoutInflater mInflator;
    private final Object mFragment;

    public FragmentInflatorFactory(LayoutInflater delegate, Object fragment) {
        if (delegate == null || fragment == null) {
            throw new NullPointerException();
        }
        mInflator = delegate;
        mFragment = fragment;
    }

    public static LayoutInflater inflatorFor(LayoutInflater original, Object fragment) {
        LayoutInflater inflator = original.cloneInContext(original.getContext());
        FragmentInflatorFactory factory = new FragmentInflatorFactory(inflator, fragment);
        inflator.setFactory(factory);
        return inflator;
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if ("fragment".equals(name)) {
            // Let the Activity ("private factory") handle it
            return null;
        }

        View view = null;

        if (name.indexOf('.') == -1) {
            try {
                view = (View) sOnCreateViewMethod.invoke(mInflator, name, attrs);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof ClassNotFoundException) {
                    return null;
                }
                throw new RuntimeException(e);
            }
        } else {
            try {
                view = mInflator.createView(name, null, attrs);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }

        TypedArray a = context.obtainStyledAttributes(attrs, sWantedAttrs);
        String methodName = a.getString(0);
        a.recycle();

        if (methodName != null) {
            view.setOnClickListener(new FragmentClickListener(mFragment, methodName));
        }
        return view;
    }

    private static class FragmentClickListener implements OnClickListener {

        private final Object mFragment;
        private final String mMethodName;
        private Method mMethod;

        public FragmentClickListener(Object fragment, String methodName) {
            mFragment = fragment;
            mMethodName = methodName;
        }

        @Override
        public void onClick(View v) {
            if (mMethod == null) {
                Class<?> clazz = mFragment.getClass();
                try {
                    mMethod = clazz.getMethod(mMethodName, View.class);
                } catch (NoSuchMethodException e) {
                    throw new IllegalStateException(
                            "Cannot find public method " + mMethodName + "(View) on "
                                    + clazz + " for onClick");
                }
            }

            try {
                mMethod.invoke(mFragment, v);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            }
        }
    }
}

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

When I added module: 'jsr305' as an additional exclude statement, it all worked out fine for me.

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'jsr305'

})

PowerShell script to return members of multiple security groups

If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:

$Groups = Get-ADGroup -Filter {Name -like "AB*"}

$rtn = @(); ForEach ($Group in $Groups) {
    $rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}

Then the results:

$rtn | ft -autosize

Is there a way to call a stored procedure with Dapper?

In the simple case you can do:

var user = cnn.Query<User>("spGetUser", new {Id = 1}, 
        commandType: CommandType.StoredProcedure).First();

If you want something more fancy, you can do:

 var p = new DynamicParameters();
 p.Add("@a", 11);
 p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
 p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

 cnn.Execute("spMagicProc", p, commandType: CommandType.StoredProcedure); 

 int b = p.Get<int>("@b");
 int c = p.Get<int>("@c"); 

Additionally you can use exec in a batch, but that is more clunky.

Delete data with foreign key in SQL Server table

So, you need to DELETE related rows from conflicted tables or more logical to UPDATE their FOREIGN KEY column to reference other PRIMARY KEY's from the parent table.

Also, you may want to read this article Don’t Delete – Just Don’t

How can I update window.location.hash without jumping the document?

I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:

if (history.pushState) {
    // IE10, Firefox, Chrome, etc.
    window.history.pushState(null, null, '#' + id);
} else {
    // IE9, IE8, etc
    window.location.hash = '#!' + id;
}

As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:

id = window.location.hash.replace(/^#!?/, '');

Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.

How to pad a string to a fixed length with spaces in Python?

You can use the ljust method on strings.

>>> name = 'John'
>>> name.ljust(15)
'John           '

Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]

Why can't I reference System.ComponentModel.DataAnnotations?

I upgraded from Silverlight 4 to Silverlight 5 and then I was having this issue. Although I had a reference to "System.ComponentModel.DataAnnotations" under "References" in my project, it had a yellow yield sign by it that indicated the previously referenced assembly could not be found. It turned out that the properties of the "System.ComponentModel.DataAnnotations" reference indicated "Specific Version = True", when I changed this to "Specific Version = False" it fixed the issue. Right click on the "System.ComponentModel.DataAnnotations" assembly under "References" and select "Properties" from the context menu. Check that the property value for "Specific Version = False".

It must have been referencing the old Silverlight 4 assembly which was no longer available after the upgrade to Silverlight 5.

how to make negative numbers into positive

Well, in mathematics to convert a negative number to a positive number you just need to multiple the negative number by -1;

Then your solution could be like this:

a = a * -1;

or shorter:

a *= -1;

How to extract the first two characters of a string in shell scripting?

You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed and awk and (almost) no one else offered solutions based on them, I offer you these:

echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'

and

echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'

The awk one ought to be fairly obvious, but here's an explanation of the sed one:

  • substitute "s/"
  • the group "()" of two of any characters ".." starting at the beginning of the line "^" and followed by any character "." repeated zero or more times "*" (the backslashes are needed to escape some of the special characters)
  • by "/" the contents of the first (and only, in this case) group (here the backslash is a special escape referring to a matching sub-expression)
  • done "/"

Programmatically find the number of cores on a machine

Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.

The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...

How to find the last day of the month from date?

If you use the Carbon API extension for PHP DateTime, you can get the last day of the month with:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 

Cannot find Dumpbin.exe

A little refresh as for the Visual Studio 2015.

DUMPBIN is being shipped within Common Tools for Visual C++, so be sure to select this feature in the process of installation of Visual Studio. The utility resides at:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\

It become available within Developer Command Prompt for VS 2015, which can be executed from Start Menu:

Visual Studio 2015 \ Visual Studio Tools \ Developer Command Prompt for VS2015

If you want to make it available in the regular command prompt, then add the utility's location to the PATH environment variable on your machine.

enter image description here

Portable way to check if directory exists [Windows/Linux, C]

Since I found that the above approved answer lacks some clarity and the op provides an incorrect solution that he/she will use. I therefore hope that the below example will help others. The solution is more or less portable as well.

/******************************************************************************
 * Checks to see if a directory exists. Note: This method only checks the
 * existence of the full path AND if path leaf is a dir.
 *
 * @return  >0 if dir exists AND is a dir,
 *           0 if dir does not exist OR exists but not a dir,
 *          <0 if an error occurred (errno is also set)
 *****************************************************************************/
int dirExists(const char* const path)
{
    struct stat info;

    int statRC = stat( path, &info );
    if( statRC != 0 )
    {
        if (errno == ENOENT)  { return 0; } // something along the path does not exist
        if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
        return -1;
    }

    return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I had a similar error while I was creating a custom modal.

const CustomModal = (visible, modalText, modalHeader) => {}

Problem was that I didn't wrap my values to curly brackets like this.

const CustomModal = ({visible, modalText, modalHeader}) => {}

If you have multiple values to pass to the component, you should use curly brackets around it.

Read file-contents into a string in C++

maybe not the most efficient, but reads data in one line:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

jQuery delete confirmation box

Try with this JSFiddle DEMO : http://jsfiddle.net/2yEtK/3/

Jquery Code:

$("a.removeRecord").live("click",function(event){
   event.stopPropagation();
   if(confirm("Do you want to delete?")) {
    this.click;
       alert("Ok");
   }
   else
   {
       alert("Cancel");
   }       
   event.preventDefault();

});

How do I split a string, breaking at a particular character?

This isn't as good as the destructuring answer, but seeing as this question was asked 12 years ago, I decided to give it an answer that also would have worked 12 years ago.

function Record(s) {
    var keys = ["name", "address", "address2", "city", "state", "zip"], values = s.split("~"), i
    for (i = 0; i<keys.length; i++) {
        this[keys[i]] = values[i]
    }
}

var record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')

record.name // contains john smith
record.address // contains 123 Street
record.address2 // contains Apt 4
record.city // contains New York
record.state // contains NY
record.zip // contains zip

Adding a right click menu to an item

If you are using Visual Studio, there is a GUI solution as well:

  1. From Toolbox add a ContextMenuStrip
  2. Select the context menu and add the right click items
  3. For each item set the click events to the corresponding functions
  4. Select the form / button / image / etc (any item) that the right click menu will be connected
  5. Set its ContextMenuStrip property to the menu you have created.

Update values from one column in same table to another in SQL Server

UPDATE `tbl_user` SET `name`=concat('tbl_user.first_name','tbl_user.last_name') WHERE student_roll>965

Creating default object from empty value in PHP?

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

How to modify values of JsonObject / JsonArray directly?

Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

Edittext change border color with shape.xml

i use as following for over come this matter

edittext_style.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
        android:color="#c8c8c8"/>
<corners android:radius="0dp" />

And applied as bellow

<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextName"
            android:background="@drawable/edit_text_style"/>

try like this..

File to byte[] in Java

Not only does the following way convert a java.io.File to a byte[], I also found it to be the fastest way to read in a file, when testing many different Java file reading methods against each other:

java.nio.file.Files.readAllBytes()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}

How to search a string in String array

At first shot, I could come up with something like this (but it's pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?

int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
    {
    if currentIndex > stringMaxIndex 
       return (-stringMaxIndex-1);
    else if var==arr[currentIndex] //or use any string comparison op or function
       return 0;
    else 
       return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
    }



    //calling code
    int index = findString(var, arr, 0, getMaxIndex(arr));

    if index == -1 printOnScreen("Not found");
    else printOnScreen("Found on index: " + index);

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

Is there an opposite of include? for Ruby Arrays?

Looking at Ruby only:

TL;DR

Use none? passing it a block with == for the comparison:

[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

Array#include? accepts one argument and uses == to check against each element in the array:

player = [1, 2, 3]
player.include?(1)
 #=> true

Enumerable#none? can also accept one argument in which case it uses === for the comparison. To get the opposing behaviour to include? we omit the parameter and pass it a block using == for the comparison.

player.none? { |n| 7 == n }
 #=> true 
!player.include?(7)    #notice the '!'
 #=> true

In the above example we can actually use:

player.none?(7)
 #=> true

That's because Integer#== and Integer#=== are equivalent. But consider:

player.include?(Integer)
 #=> false
player.none?(Integer)
 #=> false

none? returns false because Integer === 1 #=> true. But really a legit notinclude? method should return true. So as we did before:

player.none? { |e| Integer == e  }
 #=> true

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

I just fund another way to do the same workaround. Because of I hadn' t the possibility to click on the yellow triangle (even if I have admin role), when you go inside testflight, then iOS (under "Build") instead of yellow triangle click the version number, another page will open and you will find on top right something like add compliance information (sorry if I am not totally accurate but I have the italian version but it would be really easy to find). Then you can do the same even if you, like me, are not able to click on yellow triangle.

How to specify the port an ASP.NET Core application is hosted on?

Alternatively, you can specify port by running app via command line.

Simply run command:

dotnet run --server.urls http://localhost:5001

Note: Where 5001 is the port you want to run on.

How prevent CPU usage 100% because of worker process in iis

Diagnosing

In terms of diagnosing what App Pool is causing trouble, you can:

  1. Select the server
  2. Go to IIS > Worker Processes

Server Settings

This should bring up a menu like this so you can determine which App Pool is running amok.

Worker Processes

From there you can simply restart the the app pool and 9 times out of 10 that will fix any immediate issues you're having.

Treating

Unless you run some sort of controversial business, this is probably not a DDOS attack. It's likely that some code is just hanging because it couldn't get through to another server or got stuck in a loop or mis-allocated resources or your app pool just hasn't been recycled in a while.

You can deal with this problem programmatically without having to manually identify, log in, and recycle the app pool. Just configure the CPU property on your App Pool. You can have it kill (and automatically restart) your process anytime you reach a CPU threshold for a certain amount of time.

In your case, if you want it to restart at 80%, you can right click on the app pool and go to Advanced Settings and apply the following configurations:

App Pool Advanced Settings

NOTE: As kraken101 pointed out, different IIS GUIs have treated this differently over time. While the config value is always in 1/1000 of a %, sometimes the GUI takes the whole percent.

You can add this to your config section like this:

<applicationPools>
   <add name="DefaultAppPool">
     <cpu limit="80000" action="KillW3wp" resetInterval="00:01:00" />
   </add>
</applicationPools>

Alternatively, you could script it with Powershell's WebAdministration Module like this:
(*make sure web-scripting-tools is enabled)

Import-Module WebAdministration

$appPoolName = "DefaultAppPool"
$appPool = Get-Item "IIS:\AppPools\$appPoolName"
$appPool.cpu.limit = 80000
$appPool.cpu.action = "KillW3wp"
$appPool.cpu.resetInterval = "00:01:00"
$appPool | Set-Item

Preventing

The steps above will help fix some things once they've broken, but won't really solve any underlying issues you have.

Here are some resources on doing performance monitoring:

How to make a div center align in HTML

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.

How does inline Javascript (in HTML) work?

It looks suspicious because there is no apparent function that is being returned from!

It is an anonymous function that has been attached to the click event of the object.

why are you doing this, Steve?

Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)

Split by comma and strip whitespace in Python

import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.

Please try!

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'