Programs & Examples On #Iorderedenumerable

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Got to this answer ? probably the answers above are to long ...

just type in :

echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf

and restart your mac (thats it!)

restarting is annoying ? just use the command :

grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl

and restart IntelliJ IDEA

could not access the package manager. is the system running while installing android application

Once you see this error, wait for emulator to show lock screen. And then relaunch the app in your IDE and check the emulator again. It works for me always.

In Android studio, you can relaunch by clicking the green play button or ctrl + r.

Functional, Declarative, and Imperative Programming

At the time of writing this, the top voted answers on this page are imprecise and muddled on the declarative vs. imperative definition, including the answer that quotes Wikipedia. Some answers are conflating the terms in different ways.

Refer also to my explanation of why spreadsheet programming is declarative, regardless that the formulas mutate the cells.

Also, several answers claim that functional programming must be a subset of declarative. On that point it depends if we differentiate "function" from "procedure". Lets handle imperative vs. declarative first.

Definition of declarative expression

The only attribute that can possibly differentiate a declarative expression from an imperative expression is the referential transparency (RT) of its sub-expressions. All other attributes are either shared between both types of expressions, or derived from the RT.

A 100% declarative language (i.e. one in which every possible expression is RT) does not (among other RT requirements) allow the mutation of stored values, e.g. HTML and most of Haskell.

Definition of RT expression

RT is often referred to as having "no side-effects". The term effects does not have a precise definition, so some people don't agree that "no side-effects" is the same as RT. RT has a precise definition:

An expression e is referentially transparent if for all programs p every occurrence of e in p can be replaced with the result of evaluating e, without affecting the observable result of p.

Since every sub-expression is conceptually a function call, RT requires that the implementation of a function (i.e. the expression(s) inside the called function) may not access the mutable state that is external to the function (accessing the mutable local state is allowed). Put simply, the function (implementation) should be pure.

Definition of pure function

A pure function is often said to have "no side-effects". The term effects does not have a precise definition, so some people don't agree.

Pure functions have the following attributes.

  • the only observable output is the return value.
  • the only output dependency is the arguments.
  • arguments are fully determined before any output is generated.

Remember that RT applies to expressions (which includes function calls) and purity applies to (implementations of) functions.

An obscure example of impure functions that make RT expressions is concurrency, but this is because the purity is broken at the interrupt abstraction layer. You don't really need to know this. To make RT expressions, you call pure functions.

Derivative attributes of RT

Any other attribute cited for declarative programming, e.g. the citation from 1999 used by Wikipedia, either derives from RT, or is shared with imperative programming. Thus proving that my precise definition is correct.

Note, immutability of external values is a subset of the requirements for RT.

  • Declarative languages don't have looping control structures, e.g. for and while, because due to immutability, the loop condition would never change.

  • Declarative languages don't express control-flow other than nested function order (a.k.a logical dependencies), because due to immutability, other choices of evaluation order do not change the result (see below).

  • Declarative languages express logical "steps" (i.e. the nested RT function call order), but whether each function call is a higher level semantic (i.e. "what to do") is not a requirement of declarative programming. The distinction from imperative is that due to immutability (i.e. more generally RT), these "steps" cannot depend on mutable state, rather only the relational order of the expressed logic (i.e. the order of nesting of the function calls, a.k.a. sub-expressions).

For example, the HTML paragraph <p> cannot be displayed until the sub-expressions (i.e. tags) in the paragraph have been evaluated. There is no mutable state, only an order dependency due to the logical relationship of tag hierarchy (nesting of sub-expressions, which are analogously nested function calls).

  • Thus there is the derivative attribute of immutability (more generally RT), that declarative expressions, express only the logical relationships of the constituent parts (i.e. of the sub-expression function arguments) and not mutable state relationships.

Evaluation order

The choice of evaluation order of sub-expressions can only give a varying result when any of the function calls are not RT (i.e. the function is not pure), e.g. some mutable state external to a function is accessed within the function.

For example, given some nested expressions, e.g. f( g(a, b), h(c, d) ), eager and lazy evaluation of the function arguments will give the same results if the functions f, g, and h are pure.

Whereas, if the functions f, g, and h are not pure, then the choice of evaluation order can give a different result.

Note, nested expressions are conceptually nested functions, since expression operators are just function calls masquerading as unary prefix, unary postfix, or binary infix notation.

Tangentially, if all identifiers, e.g. a, b, c, d, are immutable everywhere, state external to the program cannot be accessed (i.e. I/O), and there is no abstraction layer breakage, then functions are always pure.

By the way, Haskell has a different syntax, f (g a b) (h c d).

Evaluation order details

A function is a state transition (not a mutable stored value) from the input to the output. For RT compositions of calls to pure functions, the order-of-execution of these state transitions is independent. The state transition of each function call is independent of the others, due to lack of side-effects and the principle that an RT function may be replaced by its cached value. To correct a popular misconception, pure monadic composition is always declarative and RT, in spite of the fact that Haskell's IO monad is arguably impure and thus imperative w.r.t. the World state external to the program (but in the sense of the caveat below, the side-effects are isolated).

Eager evaluation means the functions arguments are evaluated before the function is called, and lazy evaluation means the arguments are not evaluated until (and if) they are accessed within the function.

Definition: function parameters are declared at the function definition site, and function arguments are supplied at the function call site. Know the difference between parameter and argument.

Conceptually, all expressions are (a composition of) function calls, e.g. constants are functions without inputs, unary operators are functions with one input, binary infix operators are functions with two inputs, constructors are functions, and even control statements (e.g. if, for, while) can be modeled with functions. The order that these argument functions (do not confuse with nested function call order) are evaluated is not declared by the syntax, e.g. f( g() ) could eagerly evaluate g then f on g's result or it could evaluate f and only lazily evaluate g when its result is needed within f.

Caveat, no Turing complete language (i.e. that allows unbounded recursion) is perfectly declarative, e.g. lazy evaluation introduces memory and time indeterminism. But these side-effects due to the choice of evaluation order are limited to memory consumption, execution time, latency, non-termination, and external hysteresis thus external synchronization.

Functional programming

Because declarative programming cannot have loops, then the only way to iterate is functional recursion. It is in this sense that functional programming is related to declarative programming.

But functional programming is not limited to declarative programming. Functional composition can be contrasted with subtyping, especially with respect to the Expression Problem, where extension can be achieved by either adding subtypes or functional decomposition. Extension can be a mix of both methodologies.

Functional programming usually makes the function a first-class object, meaning the function type can appear in the grammar anywhere any other type may. The upshot is that functions can input and operate on functions, thus providing for separation-of-concerns by emphasizing function composition, i.e. separating the dependencies among the subcomputations of a deterministic computation.

For example, instead of writing a separate function (and employing recursion instead of loops if the function must also be declarative) for each of an infinite number of possible specialized actions that could be applied to each element of a collection, functional programming employs reusable iteration functions, e.g. map, fold, filter. These iteration functions input a first-class specialized action function. These iteration functions iterate the collection and call the input specialized action function for each element. These action functions are more concise because they no longer need to contain the looping statements to iterate the collection.

However, note that if a function is not pure, then it is really a procedure. We can perhaps argue that functional programming that uses impure functions, is really procedural programming. Thus if we agree that declarative expressions are RT, then we can say that procedural programming is not declarative programming, and thus we might argue that functional programming is always RT and must be a subset of declarative programming.

Parallelism

This functional composition with first-class functions can express the depth in the parallelism by separating out the independent function.

Brent’s Principle: computation with work w and depth d can be implemented in a p-processor PRAM in time O(max(w/p, d)).

Both concurrency and parallelism also require declarative programming, i.e. immutability and RT.

So where did this dangerous assumption that Parallelism == Concurrency come from? It’s a natural consequence of languages with side-effects: when your language has side-effects everywhere, then any time you try to do more than one thing at a time you essentially have non-determinism caused by the interleaving of the effects from each operation. So in side-effecty languages, the only way to get parallelism is concurrency; it’s therefore not surprising that we often see the two conflated.

FP evaluation order

Note the evaluation order also impacts the termination and performance side-effects of functional composition.

Eager (CBV) and lazy (CBN) are categorical duels[10], because they have reversed evaluation order, i.e. whether the outer or inner functions respectively are evaluated first. Imagine an upside-down tree, then eager evaluates from function tree branch tips up the branch hierarchy to the top-level function trunk; whereas, lazy evaluates from the trunk down to the branch tips. Eager doesn't have conjunctive products ("and", a/k/a categorical "products") and lazy doesn't have disjunctive coproducts ("or", a/k/a categorical "sums")[11].

Performance

  • Eager

As with non-termination, eager is too eager with conjunctive functional composition, i.e. compositional control structure does unnecessary work that isn't done with lazy. For example, eager eagerly and unnecessarily maps the entire list to booleans, when it is composed with a fold that terminates on the first true element.

This unnecessary work is the cause of the claimed "up to" an extra log n factor in the sequential time complexity of eager versus lazy, both with pure functions. A solution is to use functors (e.g. lists) with lazy constructors (i.e. eager with optional lazy products), because with eager the eagerness incorrectness originates from the inner function. This is because products are constructive types, i.e. inductive types with an initial algebra on an initial fixpoint[11]

  • Lazy

As with non-termination, lazy is too lazy with disjunctive functional composition, i.e. coinductive finality can occur later than necessary, resulting in both unnecessary work and non-determinism of the lateness that isn't the case with eager[10][11]. Examples of finality are state, timing, non-termination, and runtime exceptions. These are imperative side-effects, but even in a pure declarative language (e.g. Haskell), there is state in the imperative IO monad (note: not all monads are imperative!) implicit in space allocation, and timing is state relative to the imperative real world. Using lazy even with optional eager coproducts leaks "laziness" into inner coproducts, because with lazy the laziness incorrectness originates from the outer function (see the example in the Non-termination section, where == is an outer binary operator function). This is because coproducts are bounded by finality, i.e. coinductive types with a final algebra on an final object[11].

Lazy causes indeterminism in the design and debugging of functions for latency and space, the debugging of which is probably beyond the capabilities of the majority of programmers, because of the dissonance between the declared function hierarchy and the runtime order-of-evaluation. Lazy pure functions evaluated with eager, could potentially introduce previously unseen non-termination at runtime. Conversely, eager pure functions evaluated with lazy, could potentially introduce previously unseen space and latency indeterminism at runtime.

Non-termination

At compile-time, due to the Halting problem and mutual recursion in a Turing complete language, functions can't generally be guaranteed to terminate.

  • Eager

With eager but not lazy, for the conjunction of Head "and" Tail, if either Head or Tail doesn't terminate, then respectively either List( Head(), Tail() ).tail == Tail() or List( Head(), Tail() ).head == Head() is not true because the left-side doesn't, and right-side does, terminate.

Whereas, with lazy both sides terminate. Thus eager is too eager with conjunctive products, and non-terminates (including runtime exceptions) in those cases where it isn't necessary.

  • Lazy

With lazy but not eager, for the disjunction of 1 "or" 2, if f doesn't terminate, then List( f ? 1 : 2, 3 ).tail == (f ? List( 1, 3 ) : List( 2, 3 )).tail is not true because the left-side terminates, and right-side doesn't.

Whereas, with eager neither side terminates so the equality test is never reached. Thus lazy is too lazy with disjunctive coproducts, and in those cases fails to terminate (including runtime exceptions) after doing more work than eager would have.

[10] Declarative Continuations and Categorical Duality, Filinski, sections 2.5.4 A comparison of CBV and CBN, and 3.6.1 CBV and CBN in the SCL.

[11] Declarative Continuations and Categorical Duality, Filinski, sections 2.2.1 Products and coproducts, 2.2.2 Terminal and initial objects, 2.5.2 CBV with lazy products, and 2.5.3 CBN with eager coproducts.

CSS @font-face not working in ie

You could use the Google Font API. They say it works from IE 6 and up. (I've not tested this.)

Google’s serving infrastructure takes care of converting the font into a format compatible with any modern browser (including Internet Explorer 6 and up), ...

Getting XML Node text value with Java DOM

I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.

Add up a column of numbers at the Unix shell

I would use "du" instead.

$ cat files.txt | xargs du -c | tail -1
4480    total

If you just want the number:

cat files.txt | xargs du -c | tail -1 | awk '{print $1}'

Get value of a specific object property in C# without knowing the class behind

You can do it using dynamic instead of object:

dynamic item = AnyFunction(....);
string value = item.name;

Note that the Dynamic Language Runtime (DLR) has built-in caching mechanisms, so subsequent calls are very fast.

Not equal to != and !== in PHP

You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php

It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

Datetime BETWEEN statement not working in SQL Server

You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.

SELECT *
FROM [TableName]
WHERE
    (
        convert(datetime,convert(varchar,GETDATE(),1)) 

        between 

        convert(datetime,convert(varchar,[StartDate],1)) 

        and  

        convert(datetime,convert(varchar,[EndDate],1))
    )

Wpf control size to content?

For most controls, you set its height and width to Auto in the XAML, and it will size to fit its content.

In code, you set the width/height to double.NaN. For details, see FrameworkElement.Width, particularly the "remarks" section.

How do I check two or more conditions in one <c:if>?

If you are using JSP 2.0 and above It will come with the EL support: so that you can write in plain english and use and with empty operators to write your test:

<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">

Visual Studio: LINK : fatal error LNK1181: cannot open input file

For me the problem was a wrong include directory. I have no idea why this caused the error with the seemingly missing lib as the include directory only contains the header files. And the library directory had the correct path set.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:

<script type="text/javascript">
//<![CDATA[ 

your javascript code here

//]]>
</script>

Then everything worked perfectly!

Delete a row from a SQL Server table

private void button4_Click(object sender, EventArgs e)
{
    String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;

    SqlCommand sqlcom = new SqlCommand(st, myConnection);
    try
    {
        sqlcom.ExecuteNonQuery();
        MessageBox.Show("delete successful");
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}



private void button6_Click(object sender, EventArgs e)
{
    String st = "SELECT * FROM suppliers";

    SqlCommand sqlcom = new SqlCommand(st, myConnection);
    try
    {
        sqlcom.ExecuteNonQuery();
        SqlDataReader reader = sqlcom.ExecuteReader();
        DataTable datatable = new DataTable();
        datatable.Load(reader);
        dataGridView1.DataSource = datatable;
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How to run VBScript from command line without Cscript/Wscript

I am wondering why you cannot put this in a batch file. Example:

cd D:\VBS\
WSCript Converter.vbs

Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.

Is there a good jQuery Drag-and-drop file upload plugin?

If you're looking for one that doesn't rely on Flash then dropzonejs is a good shout. It supports multiple files and drag and drop.

http://www.dropzonejs.com/

Position Absolute + Scrolling

I ran into this situation and creating an extra div was impractical. I ended up just setting the full-height div to height: 10000%; overflow: hidden;

Clearly not the cleanest solution, but it works really fast.

Could not resolve '...' from state ''

I had a case where the error was thrown by a

$state.go('');

Which is obvious. I guess this can help someone in future.

Example JavaScript code to parse CSV data

I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.

    //
    //
    // CSV to object
    //
    //

    const new_line_char = '\n';
    const field_separator_char = ',';

    function parse_csv(csv_str) {

        var result = [];

        let line_end_index_moved = false;
        let line_start_index = 0;
        let line_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_str[csr_index];
        let found_new_line_char = get_new_line_char(csv_str);
        let in_quote = false;

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            csv_str = csv_str.split(found_new_line_char).join(new_line_char);
        }
        // Handle the last character is not \n
        if (csv_str[csv_str.length - 1] !== new_line_char) {
            csv_str += new_line_char;
        }

        while (csr_index < csv_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === new_line_char) {
                if (in_quote === false) {
                    if (line_end_index_moved && (line_start_index <= line_end_index)) {
                        result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
                        line_start_index = csr_index + 1;
                    } // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
                } // Else: just ignore because we are in a quote
            }
            csr_index++;
            cursor_val = csv_str[csr_index];
            line_end_index = csr_index;
            line_end_index_moved = true;
        }

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            let new_result = [];
            let curr_row;
            for (var i = 0; i < result.length; i++) {
                curr_row = [];
                for (var j = 0; j < result[i].length; j++) {
                    curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
                }
                new_result.push(curr_row);
            }
            result = new_result;
        }
        return result;
    }

    function parse_csv_line(csv_line_str) {

        var result = [];

        //let field_end_index_moved = false;
        let field_start_index = 0;
        let field_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_line_str[csr_index];
        let in_quote = false;

        // Pretend that the last char is the separator_char to complete the loop
        csv_line_str += field_separator_char;

        while (csr_index < csv_line_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === field_separator_char) {
                if (in_quote === false) {
                    if (field_start_index <= field_end_index) {
                        result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
                        field_start_index = csr_index + 1;
                    } // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
                } // Else: just ignore because we are in quote
            }
            csr_index++;
            cursor_val = csv_line_str[csr_index];
            field_end_index = csr_index;
            field_end_index_moved = true;
        }
        return result;
    }

    function parse_csv_field(csv_field_str) {
        with_quote = (csv_field_str[0] === '"');

        if (with_quote) {
            csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
            csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
        }
        return csv_field_str;
    }

    // Initial method: check the first newline character only
    function get_new_line_char(csv_str) {
        if (csv_str.indexOf('\r\n') > -1) {
            return '\r\n';
        } else {
            return '\n'
        }
    }

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

How to execute a function when page has fully loaded?

The onload property of the GlobalEventHandlers mixin is an event handler for the load event of a Window, XMLHttpRequest, element, etc., which fires when the resource has loaded.

So basically javascript already has onload method on window which get executed which page fully loaded including images...

You can do something:

var spinner = true;

window.onload = function() {
  //whatever you like to do now, for example hide the spinner in this case
  spinner = false;
};

How do I create a Bash alias?

In my .bashrc file the following lines were there by default:

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Hence, in my platform .bash_aliases is the file used for aliases by default (and the one I use). I'm not an OS X user, but I guess that if you open your .bashrc file, you'll be able to identify what's the file commonly used for aliases in your platform.

Grant SELECT on multiple tables oracle

my suggestion is...create role in oracle using

create role <role_name>;

then assign privileges to that role using

grant select on <table_name> to <role_name>;

then assign that group of privileges via that role to any user by using

grant  <role_name> to <user_name>...;

How to set up a cron job to run an executable every hour?

You can also use @hourly instant of 0 * * * *

Test if something is not undefined in JavaScript

response[0] is not defined, check if it is defined and then check for its property title.

if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
    //Do something
}

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

How to convert a string with Unicode encoding to a string of letters

Technically doing:

String myString = "\u0048\u0065\u006C\u006C\u006F World";

automatically converts it to "Hello World", so I assume you are reading in the string from some file. In order to convert it to "Hello" you'll have to parse the text into the separate unicode digits, (take the \uXXXX and just get XXXX) then do Integer.ParseInt(XXXX, 16) to get a hex value and then case that to char to get the actual character.

Edit: Some code to accomplish this:

String str = myString.split(" ")[0];
str = str.replace("\\","");
String[] arr = str.split("u");
String text = "";
for(int i = 1; i < arr.length; i++){
    int hexVal = Integer.parseInt(arr[i], 16);
    text += (char)hexVal;
}
// Text will now have Hello

jQuery check if attr = value

jQuery's attr method returns the value of the attribute:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

All you need is:

$('html').attr('lang') == 'fr-FR'

However, you might want to do a case-insensitive match:

$('html').attr('lang').toLowerCase() === 'fr-fr'

jQuery's val method returns the value of a form element.

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

do not forget to insert (or unCommanet) this line at the beginning of your pod file:

platform :iOS, '9.0'

that saves my day

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

In gradle-wrapper.properties I changed back from gradle-5.1.1 to distributionUrl=https://services.gradle.org/distributions/gradle-4.10.3-all.zip

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

UICollectionView cell selection and cell reuse

What I did to solve this was to make the changes in the customized cell. You have a custom cell called DataSetCell in its class you could do the following (the code is in swift)

override var isSelected: Bool {
    didSet {
        if isSelected {
            changeStuff
        } else {
            changeOtherStuff
        }
    }
}

What this does is that every time the cell is selected, deselected, initialized or get called from the reusable queue, that code will run and the changes will be made. Hope this helps you.

How to tell if JRE or JDK is installed

Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

How can I access and process nested objects, arrays or JSON?

This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.

_x000D_
_x000D_
const data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'foo'_x000D_
  }, {_x000D_
    id: 2,_x000D_
    name: 'bar'_x000D_
  }]_x000D_
};_x000D_
_x000D_
const {_x000D_
  items: [, {_x000D_
    name: secondName_x000D_
  }]_x000D_
} = data;_x000D_
_x000D_
console.log(secondName);
_x000D_
_x000D_
_x000D_

The above example creates a variable called secondName from the name key from an array called items, the lonely , says skip the first object in the array.

Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.

This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.

How to get row count using ResultSet in Java?

If you have access to the prepared statement that results in this resultset, you can use

connection.prepareStatement(sql, 
  ResultSet.TYPE_SCROLL_INSENSITIVE, 
  ResultSet.CONCUR_READ_ONLY);

This prepares your statement in a way that you can rewind the cursor. This is also documented in the ResultSet Javadoc

In general, however, forwarding and rewinding cursors may be quite inefficient for large result sets. Another option in SQL Server would be to calculate the total number of rows directly in your SQL statement:

SELECT my_table.*, count(*) over () total_rows
FROM my_table
WHERE ...

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

Make a link open a new window (not tab)

Browsers control a lot of this functionality but

<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>

will attempt to open yahoo.com in a new window.

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

What does --net=host option in Docker command really do?

The --net=host option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.

Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.

While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.

For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host.

Generally speaking, --net=host is only needed when you are running programs with very specific, unusual network needs.

Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.

How do I find the parent directory in C#?

No one has provided a solution that would work cross-form. I know it wasn't specifically asked but I am working in a linux environment where most of the solutions (as at the time I post this) would provide an error.

Hardcoding path separators (as well as other things) will give an error in anything but Windows systems.

In my original solution I used:

char filesep = Path.DirectorySeparatorChar;
string datapath = $"..{filesep}..{filesep}";

However after seeing some of the answers here I adjusted it to be:

string datapath = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).FullName; 

How do I output the results of a HiveQL query to CSV?

Just to cover more following steps after kicking off the query: INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select books from table;

In my case, the generated data under temp folder is in deflate format, and it looks like this:

$ ls
000000_0.deflate  
000001_0.deflate  
000002_0.deflate  
000003_0.deflate  
000004_0.deflate  
000005_0.deflate  
000006_0.deflate  
000007_0.deflate

Here's the command to unzip the deflate files and put everything into one csv file:

hadoop fs -text "file:///home/lvermeer/temp/*" > /home/lvermeer/result.csv

How can I stop redis-server?

if you did make install (e.g ubuntu) while installing redis then you can do:

redis-cli shutdown

as pointed by @yojimbo87 :)

Sample settings.xml

Here's the stock "settings.xml" with comments (complete/unchopped file at the bottom)

License:

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

Main docs and top:

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single
 |                 user, and is normally provided in
 |                 ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all
 |                 Maven users on a machine (assuming they're all using the
 |                 same Maven installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start
 | at getting the most out of your Maven installation. Where appropriate, the
 | default values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

Local repository, interactive mode, plugin groups:

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set
   | to false, maven will use a sensible default value, perhaps based on some
   | other setting, for the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when
   | executing a build. This will have an effect on artifact downloads,
   | artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when
   | resolving plugins by their prefix, i.e. when invoking a command line like
   | "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
   | already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

Proxies:

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to
   | the network. Unless otherwise specified (by system property or command-
   | line switch), the first proxy specification in this list marked as active
   | will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

Servers:

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used
   | within the system. Authentication profiles can be used whenever maven must
   | make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a
     | particular server, identified by a unique name within the system
     | (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR
     |       privateKey/passphrase, since these pairings are used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

Mirrors:

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote
   | repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving
   | certain artifacts. However, this repository may have problems with heavy
   | traffic at times, so people have mirrored it to several places.
   |
   | That repository definition will have a unique id, so we can create a
   | mirror reference for that repository, to be used as an alternate download
   | site. The mirror site will be the preferred server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository.
     | The repository that this mirror serves has an ID that matches the
     | mirrorOf element of this mirror. IDs are used for inheritance and direct
     | lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

Profiles (1/3):

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways,
   | and which can modify the build process. Profiles provided in the
   | settings.xml are intended to provide local machine-specific paths and
   | repository locations which allow the build to work in the local
   | environment.
   |
   | For example, if you have an integration testing plugin - like cactus -
   | that needs to know where your Tomcat instance is installed, you can
   | provide a variable here such that the variable is dereferenced during the
   | build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One
   | way - the activeProfiles section of this document (settings.xml) - will be
   | discussed later. Another way essentially relies on the detection of a
   | system property, either matching a particular value for the property, or
   | merely testing its existence. Profiles can also be activated by JDK
   | version prefix, where a value of '1.4' might activate a profile when the
   | build is executed on a JDK version of '1.4.2_07'. Finally, the list of
   | active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to
   |       specifying only artifact repositories, plugin repositories, and
   |       free-form properties to be used as configuration variables for
   |       plugins in the POM.
   |
   |-->

Profiles (2/3):

  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated
     | using one or more of the mechanisms described above. For inheritance
     | purposes, and to activate profiles via <activatedProfiles/> or the
     | command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a
     | consistent naming convention for profiles, such as 'env-dev',
     | 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
     | will make it more intuitive to understand what the set of introduced
     | profiles is attempting to accomplish, particularly when you only have a
     | list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and
     | provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

Profiles (3/3):

    <!--
     | Here is another profile, activated by the system property 'target-env'
     | with a value of 'dev', which provides a specific path to the Tomcat
     | instance. To use this, your plugin configuration might hypothetically
     | look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone
     |       set 'target-env' to anything, you could just leave off the
     |       <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

Bottom:

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

Complete file:


<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single
 |                 user, and is normally provided in
 |                 ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all
 |                 Maven users on a machine (assuming they're all using the
 |                 same Maven installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start
 | at getting the most out of your Maven installation. Where appropriate, the
 | default values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set
   | to false, maven will use a sensible default value, perhaps based on some
   | other setting, for the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when
   | executing a build. This will have an effect on artifact downloads,
   | artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when
   | resolving plugins by their prefix, i.e. when invoking a command line like
   | "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
   | already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to
   | the network. Unless otherwise specified (by system property or command-
   | line switch), the first proxy specification in this list marked as active
   | will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used
   | within the system. Authentication profiles can be used whenever maven must
   | make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a
     | particular server, identified by a unique name within the system
     | (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR
     |       privateKey/passphrase, since these pairings are used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote
   | repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving
   | certain artifacts. However, this repository may have problems with heavy
   | traffic at times, so people have mirrored it to several places.
   |
   | That repository definition will have a unique id, so we can create a
   | mirror reference for that repository, to be used as an alternate download
   | site. The mirror site will be the preferred server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository.
     | The repository that this mirror serves has an ID that matches the
     | mirrorOf element of this mirror. IDs are used for inheritance and direct
     | lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways,
   | and which can modify the build process. Profiles provided in the
   | settings.xml are intended to provide local machine-specific paths and
   | repository locations which allow the build to work in the local
   | environment.
   |
   | For example, if you have an integration testing plugin - like cactus -
   | that needs to know where your Tomcat instance is installed, you can
   | provide a variable here such that the variable is dereferenced during the
   | build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One
   | way - the activeProfiles section of this document (settings.xml) - will be
   | discussed later. Another way essentially relies on the detection of a
   | system property, either matching a particular value for the property, or
   | merely testing its existence. Profiles can also be activated by JDK
   | version prefix, where a value of '1.4' might activate a profile when the
   | build is executed on a JDK version of '1.4.2_07'. Finally, the list of
   | active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to
   |       specifying only artifact repositories, plugin repositories, and
   |       free-form properties to be used as configuration variables for
   |       plugins in the POM.
   |
   |-->

  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated
     | using one or more of the mechanisms described above. For inheritance
     | purposes, and to activate profiles via <activatedProfiles/> or the
     | command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a
     | consistent naming convention for profiles, such as 'env-dev',
     | 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
     | will make it more intuitive to understand what the set of introduced
     | profiles is attempting to accomplish, particularly when you only have a
     | list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and
     | provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env'
     | with a value of 'dev', which provides a specific path to the Tomcat
     | instance. To use this, your plugin configuration might hypothetically
     | look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone
     |       set 'target-env' to anything, you could just leave off the
     |       <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Error "res://ieframe.dll/acr_error.htm#"

In my case, cannot open some websites or after openned IE8 gave "cannot return to website error". After some visits to MS help sites like this and followed all the instructioms with no avail I saw what seems to me a tip.

In one of the MS websites they say to delete old Java versions using "control panel" and "add remove programs". I did just that but only saw one version of Java v.6u22. Then I got the idea of download the last version of Java from some days ago v.6u29 and voila... IE8 is working now and seems OK. I'm writing this in the hope this can help others.

How to use View.OnTouchListener instead of onClick

The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.

Here's a sample code:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            // Do what you want
            return true;
        }
        return false;
    }
});

How to get child process from parent process

ps -axf | grep parent_pid 

Above command prints respective processes generated from parent_pid, hope it helps. +++++++++++++++++++++++++++++++++++++++++++

root@root:~/chk_prgrm/lp#

 parent...18685

 child... 18686


root@root:~/chk_prgrm/lp# ps axf | grep frk

 18685 pts/45   R      0:11  |       \_ ./frk

 18686 pts/45   R      0:11  |       |   \_ ./frk

 18688 pts/45   S+     0:00  |       \_ grep frk

Why is the Java main method static?

Why public static void main(String[] args) ?

This is how Java Language is designed and Java Virtual Machine is designed and written.

Oracle Java Language Specification

Check out Chapter 12 Execution - Section 12.1.4 Invoke Test.main:

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either

public static void main(String[] args)

or

public static void main(String... args)

Oracle Java Virtual Machine Specification

Check out Chapter 2 Java Programming Language Concepts - Section 2.17 Execution:

The Java virtual machine starts execution by invoking the method main of some specified class and passing it a single argument, which is an array of strings. This causes the specified class to be loaded (§2.17.2), linked (§2.17.3) to other types that it uses, and initialized (§2.17.4). The method main must be declared public, static, and void.

Oracle OpenJDK Source

Download and extract the source jar and see how JVM is written, check out ../launcher/java.c, which contains native C code behind command java [-options] class [args...]:

/*
 * Get the application's main class.
 * ... ...
 */
if (jarfile != 0) {
    mainClassName = GetMainClassName(env, jarfile);

... ...

    mainClass = LoadClass(env, classname);
    if(mainClass == NULL) { /* exception occured */

... ...

/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                                   "([Ljava/lang/String;)V");

... ...

{    /* Make sure the main method is public */
    jint mods;
    jmethodID mid;
    jobject obj = (*env)->ToReflectedMethod(env, mainClass,
                                            mainID, JNI_TRUE);

... ...

/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
    ReportExceptionDescription(env);
    goto leave;
}

/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

... ...

"Unable to find remote helper for 'https'" during git clone

I was having this issue when using capistrano to deploy a rails app. The problem was that my user only had a jailed shell access in cpanel. Changing it to normal shell access fixed my problem.

How to set a Postgresql default value datestamp like 'YYYYMM'?

Why would you want to do this?

IMHO you should store the date as default type and if needed fetch it transforming to desired format.

You could get away with specifying column's format but with a view. I don't know other methods.

Edited:

Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:

create table sample_table ( id serial primary key, timestamp date); 

and than

create view v_example_table as select id, to_char(date, 'yyyymmmm');

And use v_example_table in your application.

Why is the Android emulator so slow? How can we speed up the Android emulator?

This is what has worked for me:

  • Setting AVD RAM to 512 MB
  • Setting SD card memory to 10 MB
  • Setting a large SD card memory size is one of the biggest causes of a slow AVD.

How to get the total number of rows of a GROUP BY query?

If you're willing to give up a hint of abstraction, then you could use a custom wrapper class which simply passes everything through to the PDO. Say, something like this: (Warning, code untested)

class SQLitePDOWrapper
{
    private $pdo;

    public function __construct( $dns, $uname = null, $pwd = null, $opts = null )
    {
        $this->pdo = new PDO( $dns, $unam, $pwd, $opts ); 
    }
    public function __call( $nm, $args )
    {
        $ret = call_user_func_array( array( $this->pdo, $nm ), $args );
        if( $ret instanceof PDOStatement )
        {
            return new StatementWrapper( $this, $ret, $args[ 0 ] ); 
               // I'm pretty sure args[ 0 ] will always be your query, 
               // even when binding
        }

        return $ret;
    }

}

class StatementWrapper
{
    private $pdo; private $stat; private $query;

    public function __construct( PDO $pdo, PDOStatement $stat, $query )
    {
        $this->pdo  = $pdo;
        $this->stat = $stat;
        this->query = $query;
    }

    public function rowCount()
    {
        if( strtolower( substr( $this->query, 0, 6 ) ) == 'select' )
        {
            // replace the select columns with a simple 'count(*)
            $res = $this->pdo->query( 
                     'SELECT COUNT(*)' . 
                          substr( $this->query, 
                              strpos( strtolower( $this->query ), 'from' ) ) 
                   )->fetch( PDO::FETCH_NUM );
            return $res[ 0 ];
        }
        return $this->stat->rowCount();
    }

    public function __call( $nm, $args )
    {
        return call_user_func_array( array( $this->stat, $nm ), $args );
    }
}

How to turn off caching on Firefox?

Have you tried to use CTRL-F5 to update the page?

css absolute position won't work with margin-left:auto margin-right: auto

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

MySQL: Cloning a MySQL database on the same MySql instance

If you have triggers in your original database, you can avoid the "Trigger already exists" error by piping a replacement before the import:

mysqldump -u olddbuser -p -d olddbname | sed "s/`olddbname`./`newdbname`./" | mysql -u newdbuser -p -D newdbname

Testing if a checkbox is checked with jQuery

Use .is(':checked') to determine whether or not it's checked, and then set your value accordingly.

More information here.

Are vectors passed to functions by value or by reference in C++

void foo(vector<int> test)

vector would be passed by value in this.

You have more ways to pass vectors depending on the context:-

1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.

2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

How do I apply a diff patch on Windows?

Just use:

patch -p0 < path-file.patch

remember execute this command only from the folder location where you created the patch.

iOS: how to perform a HTTP POST request?

Here is how POST HTTP request works for iOS 8+ using NSURLSession:

- (void)call_PostNetworkingAPI:(NSURL *)url withCompletionBlock:(void(^)(id object,NSError *error,NSURLResponse *response))completion
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;
    config.timeoutIntervalForRequest = 5.0f;
    config.timeoutIntervalForResource =10.0f;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
    NSMutableURLRequest *Req=[NSMutableURLRequest requestWithURL:url];
    [Req setHTTPMethod:@"POST"];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:Req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if (dict != nil) {
                completion(dict,error,response);
            }
        }else
        {
            completion(nil,error,response);
        }
    }];
    [task resume];

}

Hope this will satisfy your following requirement.

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

Get max and min value from array in JavaScript

use this and it works on both the static arrays and dynamically generated arrays.

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

I had the issue when I use trying to find max value from code below

$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
            newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
        });

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
            newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
        }

        getMaxValue = Math.max.apply(Math, array);

I was getting 'NAN' when I use

    var max_value = Math.max(12, 21, 23, 2323, 23);

with my code

Apply function to all elements of collection through LINQ

The idiomatic way to do this with LINQ is to process the collection and return a new collection mapped in the fashion you want. For example, to add a constant to every element, you'd want something like

var newNumbers = oldNumbers.Select(i => i + 8);

Doing this in a functional way instead of mutating the state of your existing collection frequently helps you separate distinct operations in a way that's both easier to read and easier for the compiler to reason about.

If you're in a situation where you actually want to apply an action to every element of a collection (an action with side effects that are unrelated to the actual contents of the collection) that's not really what LINQ is best suited for, although you could fake it with Select (or write your own IEnumerable extension method, as many people have.) It's probably best to stick with a foreach loop in that case.

How to use a Java8 lambda to sort a stream in reverse order?

You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order? by wrapping it in a lambda:

.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())

note that f2 is the first argument of Long.compare, not the second, so the result will be reversed.

Fake "click" to activate an onclick method

I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick handler.

I'd call the associated onclick method directly, if you're not using the event details.

How to avoid warning when introducing NAs by coercion

Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))
[1]  1  2 NA

This suppresses warnings.

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

Footnotes for tables in LaTeX

Use minipage environment. Here is an example:

\begin{minipage}{6cm}
\begin{tabular}{|l|c|c|}
    \hline
    A & 1 & 2 \footnote{This is a footnote.} \\
    \hline
    B & 2 & 1 \\
    \hline
    C & 3 & 3 \\
    \hline
\end{tabular}
\end{minipage}

Why use prefixes on member variables in C++ classes

I use m_ for member variables just to take advantage of Intellisense and related IDE-functionality. When I'm coding the implementation of a class I can type m_ and see the combobox with all m_ members grouped together.

But I could live without m_ 's without problem, of course. It's just my style of work.

Select <a> which href ends with some string

$('a[href$="ABC"]:first').attr('title');

This will return the title of the first link that has a URL which ends with "ABC".

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

This error comes when there is error in your query syntax check field names table name, mean check your query syntax.

Multiple cases in switch statement

You can leave out the newline which gives you:

case 1: case 2: case 3:
   break;

but I consider that bad style.

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

Line number is actually something static, so if you just want it for logging then it could be preprocessed with something like gulp. I've written a small gulp plugin that does exactly that:

var gulp = require('gulp');
var logLine = require('gulp-log-line');
gulp.task('log-line', function() {
    return gulp.src("file.js", {buffer : true})
    //Write here the loggers you use.
        .pipe(logLine(['console.log']))
        .pipe(gulp.dest('./build'))

})

gulp.task('default', ['log-line'])

This will attach the file name and line to all logs from console.log, so console.log(something) will become console.log('filePath:fileNumber', something). The advantage is that now you can concat your files, transpile them... and you will still get the line

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

Android : Check whether the phone is dual SIM

I have found these system properties on Samsung S8

SystemProperties.getInt("ro.multisim.simslotcount", 1) > 1

Also, according to the source: https://android.googlesource.com/platform/frameworks/base/+/master/telephony/java/com/android/internal/telephony/TelephonyProperties.java

getprop persist.radio.multisim.config returns "dsds" or "dsda" on multi sim.

I have tested this on Samsung S8 and it works

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

casting Object array to Integer array error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

SQL Server: Filter output of sp_who2

This is the solution for you: http://blogs.technet.com/b/wardpond/archive/2005/08/01/the-openrowset-trick-accessing-stored-procedure-output-in-a-select-statement.aspx

select * from openrowset ('SQLOLEDB', '192.168.x.x\DATA'; 'user'; 'password', 'sp_who') 

Scroll Element into View with Selenium

webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);

For more examples, go here. All in Russian, but Java code is cross-cultural :)

How can I generate a random number in a certain range?

You can use If Random. For example, this generates a random number between 75 to 100.

final int random = new Random().nextInt(26) + 75;

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

This is what got it working for me on Ubuntu 15.10 using the fish shell:

# ~/.config/fish/config.fish

set -g -x PATH /usr/local/bin $PATH
set -g -x GOPATH /usr/share/go

Then I had to change the permissions on the go folder (it was set to root)

sudo chown <name>:<name> -R /usr/share/go

Sending images using Http Post

Version 4.3.5 Updated Code

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntity has been deprecated. Please see the code below.

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

Is it possible to change the package name of an Android app on Google Play?

Nope, you cannot just change it, you would have to upload a new package as a new app. Have a look at the Google's app Talk, its name was changed to Hangouts, but the package name is still com.google.android.talk. Because it is not doable :) Cheers.

Cannot delete directory with Directory.Delete(path, true)

I resolved one possible instance of the stated problem when methods were async and coded like this:

// delete any existing update content folder for this update
if (await fileHelper.DirectoryExistsAsync(currentUpdateFolderPath))
       await fileHelper.DeleteDirectoryAsync(currentUpdateFolderPath);

With this:

bool exists = false;                
if (await fileHelper.DirectoryExistsAsync(currentUpdateFolderPath))
    exists = true;

// delete any existing update content folder for this update
if (exists)
    await fileHelper.DeleteDirectoryAsync(currentUpdateFolderPath);

Conclusion? There is some asynchronous aspect of getting rid of the handle used to check existence that Microsoft has not been able to speak to. It's as if the asynchronous method inside an if statement has the if statement acting like a using statement.

How can you integrate a custom file browser/uploader with CKEditor?

I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.

Directly below your ckeditor text area, enter the upload file like this >>>>

<form action="welcomeeditupload.asp" method="post" name="deletechecked">
    <div align="center">
        <br />
        <br />
        <label></label>
        <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
        <script type="text/javascript">
        //<![CDATA[
            CKEDITOR.replace( 'editor1',
            {
                filebrowserUploadUrl : 'updateimagedone.asp'
            });
        //]]>
        </script>
        <br />
        <br />
        <br />
        <input type="submit" value="Update">
    </div>
</form>

'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    if Request("CKEditorFuncNum")=1 then
        Set Upload = Server.CreateObject("Persits.Upload")
        Upload.OverwriteFiles = False
        Upload.SetMaxSize 5000000, True
        Upload.CodePage = 65001

        On Error Resume Next
        Upload.Save "d:\hosting\belaullach\senate\legislation"

        Dim picture
        For Each File in Upload.Files
            Ext = UCase(Right(File.Path, 3))
            If Ext <> "JPG" Then
                    If Ext <> "BMP" Then
                    Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
                    Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
                    End if
            Else
                File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
                f1=File.fileName
            End If
        Next
    End if

    fnm="/senate/legislation/"&f1
    imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
    'imgop="callFunction('1','"&fnm&"',"");"
    Response.write imgop
%>

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

anchor jumping by using javascript

I think it is much more simple solution:

window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"

This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.

When are static variables initialized?

Starting with the code from the other question:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.

Now back to initializing the class: obj is made a reference to a new real object, and we're done.

If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.

The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.

convert HTML ( having Javascript ) to PDF using JavaScript

You can do it using a jquery,

Use this code to link the button...

$(document).ready(function() {
    $("#button_id").click(function() {
        window.print();
        return false;
    });
});

This link may be also helpful: jQuery Print HTML Pdf Page Options Link

Passing arguments to JavaScript function from code-behind

 <head>
    <script type="text/javascript">

        function test(x, y) 
        {
            var cc = "";
            for (var i = 0; i < x.length; i++) 
            {
                cc += x[i]; 
            }
            cc += "\ny: " + y; 
            return cc;
        }

    </script>



</head>

<body>

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Button"   />

        <p>
             <asp:TextBox ID="TextBox1"  Name="TextBox1"  runat="server" AutoPostBack="True"  TextMode="MultiLine"></asp:TextBox>
        </p>



    </form>
</body>

protected void Page_Load(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format(" var y = test({0},{1}) ; ", xStr, yStr);
    script += String.Format("  document.getElementById(\"TextBox1\").value = y  ");

    this.Page.ClientScript.RegisterStartupScript(this.GetType(),  "testFunction", script, true);
  //  this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "testFunction", script, true); // different result
}




private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

How do you scroll up/down on the console of a Linux VM

VM Ubuntu on a Mac...fn + shift + up/down arrows

Twitter Bootstrap - how to center elements horizontally or vertically

for horizontaly centering you can have something like this:

.centering{
float:none;
margin:0 auto
}

 <div class="span8 centering"></div>

What is the difference between Linear search and Binary search?

binary search runs in O(logn) time whereas linear search runs in O(n) times thus binary search has better performance

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

How do I obtain a list of all schemas in a Sql Server database

You can also use the following query to get Schemas for a specific Database user:

select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name

How do I delete unpushed git commits?

I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)

git reset --hard origin

This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.

git reset --hard origin/<branch>

How to uncompress a tar.gz in another directory

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”:

Description in Photos format

How to process each output line in a loop?

You can do the following while read loop, that will be fed by the result of the grep command using the so called process substitution:

while IFS= read -r result
do
    #whatever with value $result
done < <(grep "xyz" abc.txt)

This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.


Note the usage of IFS= and read -r according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters). Without this option, any unescaped backslashes in the input will be discarded. You should almost always use the -r option with read.

In the scenario above IFS= prevents trimming of leading and trailing whitespace. Remove it if you want this effect.

Regarding the process substitution, it is explained in the bash hackers page:

Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

How do you get a directory listing in C?

Directory listing varies greatly according to the OS/platform under consideration. This is because, various Operating systems using their own internal system calls to achieve this.

A solution to this problem would be to look for a library which masks this problem and portable. Unfortunately, there is no solution that works on all platforms flawlessly.

On POSIX compatible systems, you could use the library to achieve this using the code posted by Clayton (which is referenced originally from the Advanced Programming under UNIX book by W. Richard Stevens). this solution will work under *NIX systems and would also work on Windows if you have Cygwin installed.

Alternatively, you could write a code to detect the underlying OS and then call the appropriate directory listing function which would hold the 'proper' way of listing the directory structure under that OS.

Loop through columns and add string lengths as new columns

You can use lapply to pass each column to str_length, then cbind it to your original data.frame...

library(stringr)

out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1

jQuery see if any or no checkboxes are selected

Rahul's answer is best fit for your question. Anyway, if you have a group of checkboxes to be checked and not all the checkbox in your form, you can go for it.

Put a classname for all the checkboxes you want to check, say for example, a classname test_check and now you can check if any of the checkbox is checked belonging to the group by:

$("#formID .test_check:checked").length > 0

If it returns true, assume that one or more checkboxes are checked having the classname test_check and none checked if returns false.

Hope it helps someone. Thanks :)-

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

How do I initialize a TypeScript Object with a JSON-Object?

Option #5: Using Typescript constructors and jQuery.extend

This seems to be the most maintainable method: add a constructor that takes as parameter the json structure, and extend the json object. That way you can parse a json structure into the whole application model.

There is no need to create interfaces, or listing properties in constructor.

export class Company
{
    Employees : Employee[];

    constructor( jsonData: any )
    {
        jQuery.extend( this, jsonData);

        // apply the same principle to linked objects:
        if ( jsonData.Employees )
            this.Employees = jQuery.map( jsonData.Employees , (emp) => {
                return new Employee ( emp );  });
    }

    calculateSalaries() : void { .... }
}

export class Employee
{
    name: string;
    salary: number;
    city: string;

    constructor( jsonData: any )
    {
        jQuery.extend( this, jsonData);

        // case where your object's property does not match the json's:
        this.city = jsonData.town;
    }
}

In your ajax callback where you receive a company to calculate salaries:

onReceiveCompany( jsonCompany : any ) 
{
   let newCompany = new Company( jsonCompany );

   // call the methods on your newCompany object ...
   newCompany.calculateSalaries()
}

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

How to use Fiddler to monitor WCF service

Just had this problem, what worked for me was to use localhost.fiddler:

 <endpoint address="http://localhost.fiddler/test/test.svc"
            binding="basicHttpBinding" 
            bindingConfiguration="customBinding" 
            contract="test" 
            name="customBinding"/>

find difference between two text files with one item per line

With GNU sed:

sed 's#[^^]#[&]#g;s#\^#\\^#g;s#^#/^#;s#$#$/d#' file1 | sed -f- file2

How it works:

The first sed produces an output like this:

/^[d][s][f]$/d
/^[s][d][f][s][d]$/d
/^[d][s][f][s][d][f]$/d

Then it is used as a sed script by the second sed.

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)

How to remove the arrow from a select element in Firefox

We've found a simple and decent way to do this. It's cross-browser,degradable, and doesn't break a form post. First set the select box's opacity to 0.

.select { 
    opacity : 0;
    width: 200px;
    height: 15px;
}

<select class='select'>
    <option value='foo'>bar</option>    
</select>

this is so you can still click on it

Then make div with the same dimensions as the select box. The div should lay under the select box as the background. Use { position: absolute } and z-index to achieve this.

.div {
    width: 200px;
    height: 15px;
    position: absolute;
    z-index: 0;
}

<div class='.div'>{the text of the the current selection updated by javascript}</div>
<select class='select'>
    <option value='foo'>bar</option>    
</select>

Update the div's innerHTML with javascript. Easypeasy with jQuery:

$('.select').click(function(event)) { 
    $('.div').html($('.select option:selected').val());
}

That's it! Just style your div instead of the select box. I haven't tested the above code so you'll probably need tweak it. But hopefully you get the gist.

I think this solution beats {-webkit-appearance: none;}. What browsers should do at the very most is dictate interaction with form elements, but definitely not how their initially displayed on the page as that breaks site design.

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

What does the 'standalone' directive mean in XML?

Markup declarations can affect the content of the document, as passed from an XML processor to an application; examples are attribute defaults and entity declarations. The standalone document declaration, which may appear as a component of the XML declaration, signals whether or not there are such declarations which appear external to the document entity or in parameter entities. [Definition: An external markup declaration is defined as a markup declaration occurring in the external subset or in a parameter entity (external or internal, the latter being included because non-validating processors are not required to read them).]

http://www.w3.org/TR/xml/#sec-rmd

How to resize an Image C#

Note: this will not work with ASP.Net Core because WebImage depends on System.Web, but on previous versions of ASP.Net I used this snippet many times and was useful.

String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg";
var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
{
      var thumbnail = new WebImage(stream).Resize(80, 80);
      thumbnail.Save(ThumbfullPath2, "jpg");
}

Detect rotation of Android phone in the browser with JavaScript

Worth noting that on my Epic 4G Touch I had to set up the webview to use WebChromeClient before any of the javascript android calls worked.

webView.setWebChromeClient(new WebChromeClient());

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

Emulate ggplot2 default color palette

These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link

Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!

p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
     fill  y count x ndensity ncount  density PANEL group ymin ymax xmin xmax
1 #F8766D  5     5 1        1      1 1.111111     1     1    0    5 0.55 1.45
2 #C49A00 47    47 2        1      1 1.111111     1     2    0   47 1.55 2.45
3 #53B400 41    41 3        1      1 1.111111     1     3    0   41 2.55 3.45
4 #00C094 11    11 4        1      1 1.111111     1     4    0   11 3.55 4.45
5 #00B6EB 33    33 5        1      1 1.111111     1     5    0   33 4.55 5.45
6 #A58AFF 35    35 6        1      1 1.111111     1     6    0   35 5.55 6.45
7 #FB61D7 62    62 7        1      1 1.111111     1     7    0   62 6.55 7.45

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

use Values either while creating variable X or while encoding as mentioned above

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')

dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Bash scripting missing ']'

add a space before the close bracket

How to change JAVA.HOME for Eclipse/ANT

Set environment variables

This is the part that I always forget. Because you’re installing Ant by hand, you also need to deal with setting environment variables by hand.

For Windows XP: To set environment variables on Windows XP, right click on My Computer and select Properties. Then go to the Advanced tab and click the Environment Variables button at the bottom.

For Windows 7: To set environment variables on Windows 7, right click on Computer and select Properties. Click on Advanced System Settings and click the Environment Variables button at the bottom.

The dialog for both Windows XP and Windows 7 is the same. Make sure you’re only working on system variables and not user variables.

The only environment variable that you absolutely need is JAVA_HOME, which tells Ant the location of your JRE. If you’ve installed the JDK, this is likely c:\Program Files\Java\jdk1.x.x\jre on Windows XP and c:\Program Files(x86)\Java\jdk1.x.x\jre on Windows 7. You’ll note that both have spaces in their paths, which causes a problem. You need to use the mangled name[3] instead of the complete name. So for Windows XP, use C:\Progra~1\Java\jdk1.x.x\jre and for Windows 7, use C:\Progra~2\Java\jdk1.6.0_26\jre if it’s installed in the Program Files(x86) folder (otherwise use the same as Windows XP).

That alone is enough to get Ant to work, but for convenience, it’s a good idea to add the Ant binary path to the PATH variable. This variable is a semicolon-delimited list of directories to search for executables. To be able to run ant in any directory, Windows needs to know both the location for the ant binary and for the java binary. You’ll need to add both of these to the end of the PATH variable. For Windows XP, you’ll likely add something like this:

;c:\java\ant\bin;C:\Progra~1\Java\jdk1.x.x\jre\bin

For Windows 7, it will look something like this:

;c:\java\ant\bin;C:\Progra~2\Java\jdk1.x.x\jre\bin

Done

Once you’ve done that and applied the changes, you’ll need to open a new command prompt to see if the variables are set properly. You should be able to simply run ant and see something like this:

Buildfile: build.xml does not exist!
Build failed

Print specific part of webpage

Try this awesome ink-html library

import print from 'ink-html'
// const print = require('ink-html').default

// js
print(window.querySelector('#printable'))
// Vue.js
print(this.$refs.printable.$el)

not finding android sdk (Unity)

These are the steps that eventually worked for me...

  • Install JDK jdk1.8.0_131 (yes, this specific version, not a later version) and set it as the JDK Path in Unity.

  • Delete android sdk tools folder : [android_sdk_root]/tools

  • Download SDK Tools v25.2.5 (this specific version) from http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  • Extract the tools folder in that archive to Android SDK root

  • Build your project

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config is a part of this package). For example, if you were using Gradle, you could write in a build.gradle:

dependencies {
    compile 'javax.servlet:jstl:1.2'
}

How to generate a random integer number from within a range

All the answers so far are mathematically wrong. Returning rand() % N does not uniformly give a number in the range [0, N) unless N divides the length of the interval into which rand() returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand() are independent: it's possible that they go 0, 1, 2, ..., which is uniform but not very random. The only assumption it seems reasonable to make is that rand() puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand() are nicely scattered.

This means that the only correct way of changing the range of rand() is to divide it into boxes; for example, if RAND_MAX == 11 and you want a range of 1..6, you should assign {0,1} to 1, {2,3} to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.

The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.

The correct way is to use integer arithmetic. That is, you want something like the following:

#include <stdlib.h> // For random(), RAND_MAX

// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
  unsigned long
    // max <= RAND_MAX < ULONG_MAX, so this is okay.
    num_bins = (unsigned long) max + 1,
    num_rand = (unsigned long) RAND_MAX + 1,
    bin_size = num_rand / num_bins,
    defect   = num_rand % num_bins;

  long x;
  do {
   x = random();
  }
  // This is carefully written not to overflow
  while (num_rand - defect <= (unsigned long)x);

  // Truncated division is intentional
  return x/bin_size;
}

The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random() rather than rand() as it has a better distribution (as noted by the man page for rand()).

If you want to get random values outside the default range [0, RAND_MAX], then you have to do something tricky. Perhaps the most expedient is to define a function random_extended() that pulls n bits (using random_at_most()) and returns in [0, 2**n), and then apply random_at_most() with random_extended() in place of random() (and 2**n - 1 in place of RAND_MAX) to pull a random value less than 2**n, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max] using min + random_at_most(max - min), including negative values.

How can you encode a string to Base64 in JavaScript?

From here:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

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

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

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

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

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

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

    while (i < input.length) {

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

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

        output = output + String.fromCharCode(chr1);

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

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

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

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}

Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.

submit form on click event using jquery

Why not simply use the submit button to run the code you want. If your function returns false, it will cancel the submission.

$("#testForm").submit(function() {
    /* Do Something */
    return false;
});

Check for a substring in a string in Oracle without LIKE

Databases are heavily optimized for common usage scenarios (and LIKE is one of those).

You won't find a faster way of doing your search if you want to stay on the DB-level.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I am developing an app to version 2.2, API version would in the 8th ... had the same error and the error told me it was to google maps API, all we did was change my ADV for my project API 2.2 and also for the API.

This worked for me and found the library API needed.

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

Broken references in Virtualenvs

I was facing the same issue after upgrading brew on my OSX Catalina.

After trying bunch of stuffs, I find the following is the best and easy solution.

At first, delete the virtual env. (Optional)

find myvirtualenv -type l -delete

then recreate a new virtualenv

virtualenv myvirtualenv

Reference: https://www.jeremycade.com/python/osx/homebrew/2015/03/02/fixing-virtualenv-after-a-python-upgrade/

How do I make jQuery wait for an Ajax call to finish before it returns?

It should wait until get request completed. After that I'll return get request body from where function is called.

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Where is body in a nodejs http.get response?

Needle module is also good, here is an example which uses needle module

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});

403 Forbidden vs 401 Unauthorized HTTP responses

A clear explanation from Daniel Irvine:

There's a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization. Receiving a 401 response is the server telling you, “you aren’t authenticated–either not authenticated at all or authenticated incorrectly–but please reauthenticate and try again.” To help you out, it will always include a WWW-Authenticate header that describes how to authenticate.

This is a response generally returned by your web server, not your web application.

It’s also something very temporary; the server is asking you to try again.

So, for authorization I use the 403 Forbidden response. It’s permanent, it’s tied to my application logic, and it’s a more concrete response than a 401.

Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”

In summary, a 401 Unauthorized response should be used for missing or bad authentication, and a 403 Forbidden response should be used afterwards, when the user is authenticated but isn’t authorized to perform the requested operation on the given resource.

Another nice pictorial format of how http status codes should be used.

enter image description here

How to increase the clickable area of a <a> tag button?

Just make the anchor display: block and width/height: 100%. Eg:

.button a {
    display: block;
    width: 100%;
    height: 100%;
}

jsFiddle: http://jsfiddle.net/4mHTa/

How correctly produce JSON by RESTful web service?

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

Bring element to front using CSS

Add z-index:-1 and position:relative to .content

_x000D_
_x000D_
#header {_x000D_
    background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
    background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
    height: 128px;_x000D_
}_x000D_
.content {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
    z-index: -1;_x000D_
    position:relative;_x000D_
}_x000D_
.td-main {_x000D_
    text-align: center;_x000D_
    padding: 80px 10px 80px 10px;_x000D_
    border: 1px solid #A02422;_x000D_
    background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
    <div id="header">_x000D_
        <div id="header-inner">_x000D_
            <table class="content">_x000D_
                <col width="400px" />_x000D_
                <tr>_x000D_
                    <td>_x000D_
                        <table class="content">_x000D_
                            <col width="400px" />_x000D_
                            <tr>_x000D_
                                <td>_x000D_
                                    <div class="logo-class"></div>_x000D_
                                </td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td id="menu"></td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                        <table class="content">_x000D_
                            <col width="120px" />_x000D_
                            <col width="160px" />_x000D_
                            <col width="120px" />_x000D_
                            <tr>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                    </td>_x000D_
                </tr>_x000D_
            </table>_x000D_
        </div>_x000D_
        <!-- header-inner -->_x000D_
    </div>_x000D_
    <!-- header -->_x000D_
</body>
_x000D_
_x000D_
_x000D_

How can I install a local gem?

If you create your gems with bundler:

# do this in the proper directory
bundle gem foobar

You can install them with rake after they are written:

# cd into your gem directory
rake install

Chances are, that your downloaded gem will know rake install, too.

How to call a method in MainActivity from another class?

Initialize it first

MainActivity mActivity= new MainActivity();

Then you can continue

mActivity.startChronometer();

React Router Pass Param to Component

if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route> props to your target component:

exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}

Generate ER Diagram from existing MySQL database, created for CakePHP

If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/

I use it quite often to create simple DB schemas for various apps I build.

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to remove element from array in forEach loop?

Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

_x000D_
_x000D_
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
  if (arr[i] === 'a') {_x000D_
    arr.splice(i, 1);_x000D_
  }_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
_x000D_
_x000D_

If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

How to use Tomcat 8 in Eclipse?

To add the Tomcat 9.0 (Tomcat build from the trunk) as a server in Eclipse.

Update the ServerInfo.properties file properties as below.

server.info=Apache Tomcat/@VERSION@
server.number=@VERSION_NUMBER@
server.built=@VERSION_BUILT@


server.info=Apache Tomcat/7.0.57
server.number=7.0.57.0
server.built=Nov 3 2014 08:39:16 UTC

Build the tomcat server from trunk and add the server as tomcat7 instance in Eclipse.

ServerInfo.properties file location : \tomcat\java\org\apache\catalina\util\ServerInfo.properties

HTTP POST using JSON in Java

It's probably easiest to use HttpURLConnection.

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

You'll use JSONObject or whatever to construct your JSON, but not to handle the network; you need to serialize it and then pass it to an HttpURLConnection to POST.

Run a controller function whenever a view is opened/shown

This is probably what you were looking for:

Ionic caches your views and thus your controllers by default (max of 10) http://ionicframework.com/docs/api/directive/ionView/

There are events you can hook onto to let your controller do certain things based on those ionic events. see here for an example: http://ionicframework.com/blog/navigating-the-changes/

SSH Key - Still asking for password and passphrase

I already had set a passphrase but for some reason it wouldn't recognize it anymore. So I just added the identity file to my keychain again using ssh-add -K and it stopped asking for my password.

Process with an ID #### is not running in visual studio professional 2013 update 3

@Kilanny your answer is correct. Most machines in 2015 are 64bit, so there's a lot of chances that you just need to enable the 64bit option under the Tools main navigation link menu. No need to configure other files or hard code ports. Besides, port assignment should be dynamic. This fix applies to 2013 With Update 3 and Visual Studio 2015 Community Edition.

Check the images below for a mini tutorial: (I'm just improving Kilanny's answer)

Visual Studio Tools Menu

Visual Studio Web Project Options

How to download image using requests

This might be easier than using requests. This is the only time I'll ever suggest not using requests to do HTTP stuff.

Two liner using urllib:

>>> import urllib
>>> urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

There is also a nice Python module named wget that is pretty easy to use. Found here.

This demonstrates the simplicity of the design:

>>> import wget
>>> url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3'
>>> filename = wget.download(url)
100% [................................................] 3841532 / 3841532>
>> filename
'razorback.mp3'

Enjoy.

Edit: You can also add an out parameter to specify a path.

>>> out_filepath = <output_filepath>    
>>> filename = wget.download(url, out=out_filepath)

Difference between signed / unsigned char

A signed char is a signed value which is typically smaller than, and is guaranteed not to be bigger than, a short. An unsigned char is an unsigned value which is typically smaller than, and is guaranteed not to be bigger than, a short. A type char without a signed or unsigned qualifier may behave as either a signed or unsigned char; this is usually implementation-defined, but there are a couple of cases where it is not:

  1. If, in the target platform's character set, any of the characters required by standard C would map to a code higher than the maximum `signed char`, then `char` must be unsigned.
  2. If `char` and `short` are the same size, then `char` must be signed.

Part of the reason there are two dialects of "C" (those where char is signed, and those where it is unsigned) is that there are some implementations where char must be unsigned, and others where it must be signed.

Is it possible to get the current spark context settings in PySpark?

For a complete overview of your Spark environment and configuration I found the following code snippets useful:

SparkContext:

for item in sorted(sc._conf.getAll()): print(item)

Hadoop Configuration:

hadoopConf = {}
iterator = sc._jsc.hadoopConfiguration().iterator()
while iterator.hasNext():
    prop = iterator.next()
    hadoopConf[prop.getKey()] = prop.getValue()
for item in sorted(hadoopConf.items()): print(item)

Environment variables:

import os
for item in sorted(os.environ.items()): print(item)

Error: "an object reference is required for the non-static field, method or property..."

Simply add static in the declaration of these two methods and the compile time error will disappear!

By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.

More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:

    className.classMethod(arguments)
rather than
    someInstanceVariable.classMethod(arguments)

A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like

   Math.Sqrt(2)
   Math.Cos(Math.PI)

without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)

How to downgrade python from 3.7 to 3.6

Here is a canonical summary which sums up different solutions for the variety of operating system Python runs on. What follows are possibilities for Microsoft Windows, Linux, macOS and Misc.

As mentioned those are just possibilities - by no means do I claim to have a complete list whatsoever.


Microsoft Windows

Option 1

In general, it's suggested to use virtual environments (I highly suggest looking at the official Python documentation). With this approach, you easily can set up project-specific Python versions (as well as libraries). Easily manageable and the best part: There are lots of tutorials on the internet on how to approach this:

1.) Open command prompt ("cmd") and enter pip install virtualenv.

2.) Install your desired Python version via https://www.python.org/downloads/release; Remember: Do not add to PATH!

3.) Type into the command prompt: virtualenv \path\to\env -p \path\to\python_install.exe, whereas \path\to\env shall be the path where your virtual environment is going to be and \path\to\python_install.exe the one where your freshly (presumably) installed Python version resides.

4.) Done! You now have a virtual environment set up! Now, to activate the virtual environment execute the batch file which is located inside the \path\to\env\Scripts\activate.bat. (cf. this website or an official Python guide)

Option 2

The basic option would be to uninstall the unwanted Python version and re-install the favored one from https://www.python.org/downloads/. To remove the "old" version go to Control Panel -> "Uninstall a program" -> Search for "Python" -> Right-click on the Python name -> Uninstall. Bear in mind that Python usually has a PATH variable stored, hence you should remove it as well - Check the following links for this:

Now double-check whether there are any remaining files where Python used to be stored. Usually, you can find all the Python files at either C:\Program Files (x86)\Pythonxx, C:\Users\username\AppData\Local\Programs\Pythonxx or C:\Pythonxx or all of them. You might have installed it in another directory - check where it once was.

Now after de-installing just re-install the wanted version by going to the download page and follow the usual installation process. I won't go into details on how to install Python.. Lastly, you might check which version is currently installed by opening the command prompt and typing python -V.

Option 3

This approach is pretty similar to the second one - you basically uninstall the old one and replace it by your favored version. The only thing that changes it the part regarding how to uninstall the unwanted Python distribution: Simply execute the Python3 installer you originally used to install Python (it's usually stored in your Python directory as mentioned above; for more assistance check out this). There you get an option to repair or uninstall, proceed by choosing uninstall, and follow the steps provided via the uninstaller.

No matter how you uninstall Python (there are many resources on this topic, for example this Stack Overflow question or a problem thread a user by the name of Vincent Tang posted on the Stack Exchange site Super User, etc.), just reinstall the wanted Python version by following the steps mentioned in Option 2.

Option 4

Option 4 deals with Anaconda. Please refer to this site on how to install Anaconda on Windows. Step 9 is important as you don't want to install it as your default Python - you want to run multiple versions of Python:

Choose whether to register Anaconda as your default Python. Unless you plan on installing and running multiple versions of Anaconda or multiple versions of Python, accept the default and leave this box checked.

Follow the official tutorial I linked above.

Once done you can create the following commands individually in the anaconda prompt: To overwrite the default python version system-wise use conda install python=3.6 or to create a virtual environment go ahead and use conda create -n $PYTHON36_ENV_NAME python=3.6 anaconda whereas $PYTHON36_ENV_NAME is the custom name you can set. Credit where credit is due - the user @CermakM from this thread strongly influenced this snippet.

In my research I encountered a bunch of useful Stack Overflow threads - you might check them out if you go the tough road with Anaconda:

Option 5

What follows isn't a downgrade in the classical sense - though for the sake of completeness I decided to mention this approach as well. On Windows you're also able to run multiple Python versions - an infamous thread on StackOverflow deals with this question, thus I politely refer you to there for further reading purposes.


Linux

Option 1

Pretty analog to the third option for Windows I highly suggest you use a virtual environment such as Anaconda. Anaconda - or short conda - is also available on Linux. Check the official installation documentation here. Once again this thread is highly suggested on how to overwrite a Python version, respectively how to specifically create an environment with your wanted Python version.

Option 2

Another highly suggested virtual environment is Pyenv. The user @Sawan Vaidya described in this Stack Overflow question on how to up-or downgrade a Python version with the help of Pyenv. You can either set a Python version globally or create a local environment - both explained in the mentioned thread.

Option 3

Another user, namely @Jeereddy, has suggested to use the software package management system Homebrew. He explained this option thoroughly in this current question:

$ brew unlink python
$ brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/e128fa1bce3377de32cbf11bd8e46f7334dfd7a6/Formula/python.rb
$ brew switch python 3.6.5

Option 5

No need to reinvent the wheel - this thread is filled with lots of beautiful running approaches such as the one by @Sidharth Taneja.

  1. Download your wanted Python version from https://www.python.org/downloads/release and install it as a normal package.
  2. Run cd /Library/Frameworks/Python.framework/Version
  3. Execute ls to list all installed Python versions
  4. Run sudo rm -rf 3.7, removing Python version 3.7 - can be repeated for whatever version(s) you want to delete
  5. Check python3 -v, it should display the version you originally wanted to have installed

Option 6

What a goldmine this thread is! As @nondetermistic has described in-depth (direct link to his post):

Install Python source code as it is like this:

#Taken Python 3.6 as an example
$ mkdir /home/<user>/python3.6
$ ./configure --prefix=/home/<user>/python3.6/
$ make altinstall

You're now able to either add the downloaded version (/home/<user>/python3.6/bin) to PATH as well as lib to LD_LIBRARY_PATH or just create a virtual environment by: /home/<user>/python3.6/bin/python3.6 -m venv env-python3.6. A very aesthetic and simple solution to run multiple Python versions on your system.


macOS

Option 1

Using pyenv with Homebrew - credit to @Shayan with his reply here:

1.) Installing pyenv with Homebrew:

brew update
brew install pyenv

2.) Cloning the GitHub repository to get latest pyenv version:

 git clone https://github.com/pyenv/pyenv.git ~/.pyenv

3.) Defining the environment variables as follows

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

4.) Restarting shell so PATH change works

exec "$SHELL"

5.) Checking the available Python versions

pyenv install --list

6.) Installing the wanted Python version, e.g. 3.6

pyenv install 3.6

7.) Setting it globally (you can also go ahead and only use it in a certain environment)

pyenv global 3.6

8.) Check the Python version the system is using - your wanted / downgraded version should be displayed here.

python3 --version

Option 2

Similar to previous approaches you can download Anaconda on macOS as well. For an installation guide click here. The usage is pretty much the same as I've already described in Option 4 of the Windows guide. Please check out above.

Other options

In this case it's getting pretty repetitive. I kindly suggest you to check the following resources for further reading:


Misc

When writing this post I had the problem of not knowing where to draw the line. When looking up the operating systems Python currently supports you get a huge list, including the ones I mentioned, i.e. Linux, Microsoft Windows and macOS, though obviously different Linux distributions are single-handedly treated, e.g. CentOS, Arch Linux or Fedora should deserve a spot as well - or shall I make separate options for Windows 10, 7, etc.?

Due to the high degree of repetitiveness as far as modules like Homebrew, Conda or alike are concerned I decided to limit my list to the "main three" operating systems - distributions like Ubuntu (How do I downgrade my version of python from 3.7.5 to 3.6.5 on ubuntu), CentOS (How to downgrade python version on CentOS?) can be easily researched on Stack Overflow. Most often than not you can apply solutions from the Linux tab for said distributions. The same goes with Windows and macOS (versions).

How to dynamically change a web page's title?

But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes

How do I concatenate or merge arrays in Swift?

If you are not a big fan of operator overloading, or just more of a functional type:

// use flatMap
let result = [
    ["merge", "me"], 
    ["We", "shall", "unite"],
    ["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]

// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]

phpMyAdmin allow remote users

Just comment all lines in first Directory. Or you can remove these lines, but better to keep in case later you want to add some restrictions, you will uncomment.

#<Directory /usr/share/phpMyAdmin/>
#   <IfModule mod_authz_core.c>
#     # Apache 2.4
#     <RequireAny>
#       Require ip 127.0.0.1
#       Require ip ::1
#     </RequireAny>
#   </IfModule>
#   <IfModule !mod_authz_core.c>
#     # Apache 2.2
#     Order Deny,Allow
#     Deny from All
#     Allow from 127.0.0.1
#     Allow from ::1
#   </IfModule>
#</Directory>

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

Postgres manually alter sequence

This syntax isn't valid in any version of PostgreSQL:

ALTER SEQUENCE payments_id_seq LASTVALUE 22

This would work:

ALTER SEQUENCE payments_id_seq RESTART WITH 22;

And is equivalent to:

SELECT setval('payments_id_seq', 22, FALSE);

More in the current manual for ALTER SEQUENCE and sequence functions.

Note that setval() expects either (regclass, bigint) or (regclass, bigint, boolean). In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:

SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);

For repeated operations you might be interested in:

ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART;       -- without value

START [WITH] stores a default RESTART number, which is used for subsequent RESTART calls without value. You need Postgres 8.4 or later for the last part.

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Validate phone number with JavaScript

This reg ex is suitable for international phone numbers and multiple formats of mobile cell numbers.

Here is the regular expression: /^(+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/

Here is the JavaScript function

function isValidPhone(phoneNumber) {
    var found = phoneNumber.search(/^(\+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/);
    if(found > -1) {
        return true;
    }
    else {
        return false;
    }
}

This validates the following formats:

+44 07988-825 465 (with any combination of hyphens in place of space except that only a space must follow the +44)

+44 (0) 7988-825 465 (with any combination of hyphens in place of spaces except that no hyphen can exist directly before or after the (0) and the space before or after the (0) need not exist)

123 456-789 0123 (with any combination of hyphens in place of the spaces)

123-123 123 (with any combination of hyphens in place of the spaces)

123 123456 (Space can be replaced with a hyphen)

1234567890

No double spaces or double hyphens can exist for all formats.

Generating PDF files with JavaScript

Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.

To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.

With that said, it really isn't too hard to generate PDFs. Just read the spec.

How do I copy the contents of a String to the clipboard in C#?

WPF: System.Windows.Clipboard (PresentationCore.dll)

Winforms: System.Windows.Forms.Clipboard

Both have a static SetText method.

Get the decimal part from a double

Better Way -

        double value = 10.567;
        int result = (int)((value - (int)value) * 100);
        Console.WriteLine(result);

Output -

56

Defining a variable with or without export

It should be noted that you can export a variable and later change the value. The variable's changed value will be available to child processes. Once export has been set for a variable you must do export -n <var> to remove the property.

$ K=1
$ export K
$ K=2
$ bash -c 'echo ${K-unset}'
2
$ export -n K
$ bash -c 'echo ${K-unset}'
unset

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

From Now() to Current_timestamp in Postgresql

Here is what the MySQL docs say about NOW():

Returns the current date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

Now, you can certainly reduce your smart date to something less...

SELECT (
 date_part('year', NOW())::text
 || date_part('month', NOW())::text
 || date_part('day', NOW())::text
 || date_part('hour', NOW())::text
 || date_part('minute', NOW())::text
 || date_part('second', NOW())::text
)::float8 + foo;

But, that would be a really bad idea, what you need to understand is that times and dates are not stupid unformated numbers, they are their own type with their own set of functions and operators

So the MySQL time essentially lets you treat NOW() as a dumber type, or it overrides + to make a presumption that I can't find in the MySQL docs. Eitherway, you probably want to look at the date and interval types in pg.

What is the difference between a definition and a declaration?

A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

A definition can be used in the place of a declaration.

An identifier can be declared as often as you want. Thus, the following is legal in C and C++:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.


Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:

A declaration is a definition unless it [...] is a class name declaration [...].

3.1/3 then gives a few examples. Amongst them:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)

Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.

How to change lowercase chars to uppercase using the 'keyup' event?

Above answers are pretty good, just wanted to add short form for this

 <input type="text" name="input_text"  onKeyUP="this.value = this.value.toUpperCase();">

Writing MemoryStream to Response Object

I had the same problem and the only solution that worked was:

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(myMemoryStream.ToArray());
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
Response.End();

How do you append rows to a table using jQuery?

I'm assuming you want to add this row to the <tbody> element, and simply using append() on the <table> will insert the <tr> outside the <tbody>, with perhaps undesirable results.

$('a').click(function() {
   $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});

EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});, which was not present before.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function() {
       $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
    });
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
  <tbody>
    <tr>
      <td>test</td>
    </tr>
  </tbody>
</table>
</body>
</html>

How do I see if Wi-Fi is connected on Android?

ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
                  ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
    Toast.makeText(
        getApplicationContext(),
        "Please make sure, your network connection is ON ",
        Toast.LENGTH_LONG).show();
}
else {
    // Put your function() to go further;
}

VB.net Need Text Box to Only Accept Numbers

Dim ch(10) As Char
Dim len As Integer
len = TextBox1.Text.Length
ch = TextBox1.Text.ToCharArray()
For i = 0 To len - 1
    If Not IsNumeric(ch(i)) Then
        MsgBox("Value you insert is not numeric")
    End If
Next

Change tab bar tint color on iOS 7

After trying out all the suggested solutions, I couldn't find any very helpful.

I finally tried the following:

[self.tabBar setTintColor:[UIColor orangeColor]];

which worked out perfectly.

I only provided one image for every TabBarItem. Didn't even need a selectedImage.

I even used it inside the Child-ViewControllers to set different TintColors:

UIColor *theColorYouWish = ...;
if ([[self.parentViewController class] isSubclassOfClass:[UITabBarController class]]){
    UITabBarController *tbc = (UITabBarController *) self.parentViewController;
    [tbc.tabBar setTintColor:theColorYouWish];
}

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

We are doing the same thing. To support only TLS 1.2 and no SSL protocols, you can do this:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

SecurityProtocolType.Tls is only TLS 1.0, not all TLS versions.

As a side: If you want to check that your site does not allow SSL connections, you can do so here (I don't think this will be affected by the above setting, we had to edit the registry to force IIS to use TLS for incoming connections): https://www.ssllabs.com/ssltest/index.html

To disable SSL 2.0 and 3.0 in IIS, see this page: https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html

How to connect to MySQL Database?

You must to download MySQLConnection NET from here.

Then you need add MySql.Data.DLL to MSVisualStudio like this:

  1. Open menu project
  2. Add
  3. Reference
  4. Browse to C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
  5. Add MySql.Data.dll

If you want to know more visit: enter link description here

To use in the code you must import the library:

using MySql.Data.MySqlClient;

An example with connectio to Mysql database (NO SSL MODE) by means of Click event:

using System;
using System.Windows;
using MySql.Data.MySqlClient;


namespace Deportes_WPF
{

public partial class Login : Window
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string user;
    private string password;
    private string port;
    private string connectionString;
    private string sslM;

    public Login()
    {
        InitializeComponent();

        server = "server_name";
        database = "database_name";
        user = "user_id";
        password = "password";
        port = "3306";
        sslM = "none";

        connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

        connection = new MySqlConnection(connectionString);
    }

    private void conexion()
    {
        try
        {
            connection.Open();

            MessageBox.Show("successful connection");

            connection.Close();
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message + connectionString);
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        conexion();
    }
  }

}

Returning Promises from Vuex actions

TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.

For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.

But, there are EDGE CASES where returning a promise from your actions might be "necessary".

Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.

Dumb example

Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.

Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.

Height of an HTML select box (dropdown)

This is not a perfect solution but it sort of does work.

In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.

<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>

There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.

Get product id and product type in magento?

IN MAGENTO query in the database and fetch the result like. product id, product name and manufracturer with out using the product flat table use the eav catalog_product_entity and its attribute table product_id product_name manufacturer 1 | PRODUCTA | NOKIA 2 | PRODUCTB | SAMSUNG

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

For me the issue seems to have been caused by power failure. Restarting the server computer solved it.

Set a default font for whole iOS app?

To complete Sandy Chapman's answer, here is a solution in Objective-C (put this category anywhere you want to change UILabel Appearance):

@implementation UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR {
    self.font = [UIFont fontWithName:name size:self.font.pointSize];
}
@end

The interface file, should have this method declared publicly to be used later from places like your app delegate:

@interface UILabel (FontOverride)
  - (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR;
@end

Then, you can change the Appearance with:

[[UILabel appearance] setSubstituteFontName:@"SourceSansPro-Light"];

SELECT using 'CASE' in SQL

Change to:

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END
FROM FRUIT_TABLE;

How to completely remove a dialog on close

You can do use

$(dialogElement).empty();    
$(dialogElement).remove();