Programs & Examples On #Wsit

Web Services Interoperability Technologies.

Property [title] does not exist on this collection instance

You Should Used Collection keyword in Controller. Like Here..

public function ApiView(){
    return User::collection(Profile::all());
}

Here, User is Resource Name and Profile is Model Name. Thank You.

How can I commit files with git?

I don't know your system environment, but it seems, that you have typed:

git commit

And your default editor has been launched. In the worst case scenario (for you) it could have been vim :)

If you don't know how to quit vim, use :q.

If you have further problems, you could use

git commit -m 'Type your commit message here'

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

How to make a <ul> display in a horizontal row

Set the display property to inline for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.

Occurrences of substring in a string

Your lastIndex += findStr.length(); was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()).

Here is the fixed version :

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

    lastIndex = str.indexOf(findStr, lastIndex);

    if (lastIndex != -1) {
        count++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);

How do you push a Git tag to a branch using a refspec?

It is probably failing because 1.0.0 is an annotated tag. Perhaps you saw the following error message:

error: Trying to write non-commit object to branch refs/heads/master

Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.

git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master          # shorthand

There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).

git push production +1.0.0^{}:master

These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

For those who are looking for the error/warning UnhandledPromiseRejectionWarning outside of a testing environment, It could be probably because nobody in the code is taking care of the eventual error in a promise:

For instance, this code will show the warning reported in this question:

new Promise((resolve, reject) => {
  return reject('Error reason!');
});

(node:XXXX) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Error reason!

and adding the .catch() or handling the error should solve the warning/error

new Promise((resolve, reject) => {
  return reject('Error reason!');
}).catch(() => { /* do whatever you want here */ });

Or using the second parameter in the then function

new Promise((resolve, reject) => {
  return reject('Error reason!');
}).then(null, () => { /* do whatever you want here */ });

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.

From the Oracle 10g SQL Reference:

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

  • Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
  • The view must not contain any of the following constructs:
    • A set operator
    • a DISTINCT operator
    • An aggregate or analytic function
    • A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
    • A collection expression in a SELECT list
    • A subquery in a SELECT list
    • A subquery designated WITH READ ONLY
    • Joins, with some exceptions, as documented in Oracle Database Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

  • The DML statement must affect only one table underlying the join.
  • For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
  • For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
  • For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.

How do I programmatically get the GUID of an application in .NET 2.0

Try the following code. The value you are looking for is stored on a GuidAttribute instance attached to the Assembly

using System.Runtime.InteropServices;

static void Main(string[] args)
{
    var assembly = typeof(Program).Assembly;
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];
    var id = attribute.Value;
    Console.WriteLine(id);
}

Remove duplicates in the list using linq

var distinctItems = items.Distinct();

To match on only some of the properties, create a custom equality comparer, e.g.:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Then use it like this:

var distinctItems = items.Distinct(new DistinctItemComparer());

Email and phone Number Validation in android

For check email and phone number you need to do that

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
        }
    } else {
        check = false;
    }
    return check;
}

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;
}



String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number

}

Get records with max value for each group of grouped SQL results

If ID(and all coulmns) is needed from mytable

SELECT
    *
FROM
    mytable
WHERE
    id NOT IN (
        SELECT
            A.id
        FROM
            mytable AS A
        JOIN mytable AS B ON A. GROUP = B. GROUP
        AND A.age < B.age
    )

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

WCF Service Returning "Method Not Allowed"

I ran into this exact same issue today. I had installed IIS, but did not have the activate WCF Services Enabled under .net framework 4.6.

enter image description here

What is Func, how and when is it used

Func<T1,R> and the other predefined generic Func delegates (Func<T1,T2,R>, Func<T1,T2,T3,R> and others) are generic delegates that return the type of the last generic parameter.

If you have a function that needs to return different types, depending on the parameters, you can use a Func delegate, specifying the return type.

How can I create an array/list of dictionaries in python?

Dictionary:

dict = {'a':'a','b':'b','c':'c'}

array of dictionary

arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})

How to get "GET" request parameters in JavaScript?

The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.

function getUrlParameter(name) {
    var urlOld          = window.location.href.split('?');
    urlOld[1]           = urlOld[1] || '';
    var urlBase         = urlOld[0];
    var urlQuery        = urlOld[1].split('#');
    urlQuery[1]         = urlQuery[1] || '';
    var parametersString = urlQuery[0].split('&');
    if (parametersString.length === 1 && parametersString[0] === '') {
        parametersString = [];
    }
    // console.log(parametersString);
    var anchor          = urlQuery[1] || '';

    var urlParameters = {};
    jQuery.each(parametersString, function (idx, parameterString) {
        paramName   = parameterString.split('=')[0];
        paramValue  = parameterString.split('=')[1];
        urlParameters[paramName] = paramValue;
    });
    return urlParameters[name];
}

How to access first element of JSON object array?

After you parse it with Javascript, try this:

mandrill_events[0].event

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

iPhone is not available. Please reconnect the device

I am using an iPhone SE iOS 13.6.1 and Xcode 13.5 and I faced the same issue. While the iPhone is not available. Please reconnect the device warning window is open, I turned off the iPhone, reopened and rebuilt the Xcode project, Trusted in the iPhone and my problem was solved.

Shell - Write variable contents to a file

When you say "copy the contents of a variable", does that variable contain a file name, or does it contain a name of a file?

I'm assuming by your question that $var contains the contents you want to copy into the file:

$ echo "$var" > "$destdir"

This will echo the value of $var into a file called $destdir. Note the quotes. Very important to have "$var" enclosed in quotes. Also for "$destdir" if there's a space in the name. To append it:

$ echo "$var" >> "$destdir"

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Jquery asp.net Button Click Event via ajax

ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__doPostBack".

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

Use the following in your code file to generate the JavaScript that performs the PostBack. Using this method will ensure that the proper ClientID for the control is used.

protected string GetLoginPostBack()
{
    return Page.ClientScript.GetPostBackEventReference(btnLogin, string.Empty);
}

Then in the ASPX page add a javascript block.

<script language="javascript">
function btnLogin_Click() {
  <%= GetLoginPostBack() %>;
}
</script>

The final javascript will be rendered like this.

<script language="javascript">
function btnLogin_Click() {
  __doPostBack('btnLogin','');
}
</script>

Now you can use "btnLogin_Click()" from your javascript to submit the button click to the server.

Collision resolution in Java HashMap

First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

Although, from Java 8 , the linked lists are replaced with trees (O(log n))

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

For following Error:

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

Run following NPM command:

$ npm install [email protected]

Source Link

How to merge lists into a list of tuples?

In Python 2:

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

In Python 3:

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]

How do I escape double and single quotes in sed?

You need to use \" for escaping " character (\ escape the following character

sed -i 's/\"http://www.fubar.com\"/URL_FUBAR/g'

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

ES6 Class Multiple inheritance

This isn't really possible with the way prototypical inheritance works. Lets take a look at how inherited props work in js

var parent = {a: function() { console.log('ay'); }};
var child = Object.create(parent);
child.a() // first look in child instance, nope let's go to it's prototype
          // then look in parent, found! return the method

let's see what happens when you access a prop that doesn't exist:

child.b; // first look in child instance, nope let's go to it's prototype
         // then look in parent, nope let's go to it's prototype
         // then look in Object.prototype, nope let's go to it's prototype
         // then look at null, give up and return undefined

You can use mixins to get some of that functionality but you won't get late binding:

var a = {x: '1'};
var b = {y: '2'};
var c = createWithMixin([a, b]);
c.x; // 1
c.y; // 2
b.z = 3;
c.z; // undefined

vs

var a = {x: 1}
var o = Object.create(a);
o.x; // 1
a.y = 2;
o.y; // 2

How to pop an alert message box using PHP?

I have done it this way:

<?php 
$PHPtext = "Your PHP alert!";
?>

var JavaScriptAlert = <?php echo json_encode($PHPtext); ?>;
alert(JavaScriptAlert); // Your PHP alert!

Reporting Services export to Excel with Multiple Worksheets

The solution from Edward worked for me.

If you want the whole tablix on one sheet with a constant name, specify the PageName in the tablix's Properties. If you set the PageName in the tablix's Properties, you can not use data from the tablix's dataset in your expression.

If you want rows from the tablix grouped into sheets (or you want one sheet with a name based on the data), specify the PageName in the Group Header.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

It is generally expected that modules of code such as .cpp files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp would produce class.o which you could then link from multiple projects to using g++ main.cpp class.o.

We could use #include as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...

The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o files.

It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.

python requests get cookies

If you need the path and thedomain for each cookie, which get_dict() is not exposes, you can parse the cookies manually, for instance:

[
    {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
    for c in session.cookies
]

How do I replace text in a selection?

Some of the answers here haven't really helped.

People are showing you how to find stuff, but now how to replace it.

I just had a look, and it looks like it's Ctrl+H for replace, then you get the find dialog as well as a replace dialog. This worked for me.

How to get value of a div using javascript

Value is not a valid attribute of DIV

try this

var divElement = document.getElementById('demo');
alert( divElement .getAttribute('value'));

Store query result in a variable using in PL/pgSQL

Create Learning Table:

CREATE TABLE "public"."learning" (
    "api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
    "title" varchar(255) COLLATE "default"
);

Insert Data Learning Table:

INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');

Step: 01

CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
        learn_id INT,
        learn_title VARCHAR
) AS $$
BEGIN
    RETURN QUERY SELECT
        api_id,
        title
    FROM
        learning
    WHERE
        title = pattern ;
END ; $$ LANGUAGE 'plpgsql';

Step: 02

SELECT * FROM get_all('Google AI-01');

Step: 03

DROP FUNCTION get_all();

Demo: enter image description here

PHP function overloading

You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

For example:

function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
    }
}

/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);

AngularJS - $http.post send data as json

Use JSON.stringify() to wrap your json

var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
    $http.post(url, parameter).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log(data);
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

Add swipe to delete UITableViewCell

swift 3

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if (editingStyle == UITableViewCellEditingStyle.delete) {

        arrayCityName.remove(at: indexPath.row)
        self.tableCityName.reloadData()
    }
}

Adding one day to a date

<?php

function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
    return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}

$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';

echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);

?>

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

Convert RGB to Black & White in OpenCV

I do something similar in one of my blog postings. A simple C++ example is shown.

The aim was to use the open source cvBlobsLib library for the detection of spot samples printed to microarray slides, but the images have to be converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.

Delete a row from a SQL Server table

As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....

    public static void deleteRow(string table, string columnName, string IDNumber)
    {
    try
    {
    using (SqlConnection con = new SqlConnection(Global.connectionString))
    {
         con.Open();
         using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
         {
               command.ExecuteNonQuery();
         }
         con.Close();
    }
    }
    catch (SystemException ex)
       {
       MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
       }
    }
 }

How to set dropdown arrow in spinner?

Basically one needs to create a custom background for a spinner. It should be something like this:

spinner_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <layer-list>

            <item>
                <color
                    android:color="@android:color/white"/>
            </item>

            <item>
                <bitmap
                    android:gravity="center_vertical|right"
                    android:src="@drawable/ic_arrow_drop_down_black_24dp"/>
            </item>

        </layer-list>

    </item>

</selector>

Then create a custom style for your spinner, where you specify the above selector as background:

<style name="Widget.App.Spinner" parent="@style/Widget.AppCompat.Spinner">
    <item name="overlapAnchor">true</item>
    <item name="android:background">@drawable/spinner_background</item>
</style>

And finally in your app theme you should override two attributes if you want it to be applied all across your app:

<item name="spinnerStyle">@style/Widget.App.Spinner</item>
<item name="android:spinnerStyle">@style/Widget.App.Spinner</item>

And that's pretty much it.

Using an if statement to check if a div is empty

also you can use this :


    if (! $('#leftmenu').children().length > 0 ) {
         // do something : e.x : remove a specific div
    }

I think it'll work for you !

jquery - return value using ajax result on success

Add async: false to your attributes list. This forces the javascript thread to wait until the return value is retrieved before moving on. Obviously, you wouldn't want to do this in every circumstance, but if a value is needed before proceeding, this will do it.

How do I "decompile" Java class files?

For OSX I recommend: jarzilla or JD-GUI

They both allow you to view jar,war,etc. file content and decompiles any class files inside of them.

Jarzilla: https://code.google.com/p/jarzilla/
JD-GUI: http://jd.benow.ca/

How can I list all foreign keys referencing a given table in SQL Server?

Determine primary keys and unique keys for all tables in a database...

This should list all the constraints and at the end you can put your filters

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('YOUR_TABLE_NAME') 
    or REFERENCE_TABLE_NAME  in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx

How much faster is C++ than C#?

C# may not be faster, but it makes YOU/ME faster. That's the most important measure for what I do. :)

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

Difference between null and empty ("") Java String

This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).

Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.

In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null string in java. The second example is akin to empty string.

What is the max size of VARCHAR2 in PL/SQL and SQL?

If you use UTF-8 encoding then one character can takes a various number of bytes (2 - 4). For PL/SQL the varchar2 limit is 32767 bytes, not characters. See how I increase a PL/SQL varchar2 variable of the 4000 character size:

SQL> set serveroutput on
SQL> l
  1  declare
  2    l_var varchar2(30000);
  3  begin
  4    l_var := rpad('A', 4000);
  5    dbms_output.put_line(length(l_var));
  6    l_var := l_var || rpad('B', 10000);
  7    dbms_output.put_line(length(l_var));
  8* end;
SQL> /
4000
14000

PL/SQL procedure successfully completed.

But you can't insert into your table the value of such variable:

SQL> ed
Wrote file afiedt.buf

  1  create table ttt (
  2    col1 varchar2(2000 char)
  3* )
SQL> /

Table created.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    l_var varchar2(30000);
  3  begin
  4      l_var := rpad('A', 4000);
  5      dbms_output.put_line(length(l_var));
  6      l_var := l_var || rpad('B', 10000);
  7      dbms_output.put_line(length(l_var));
  8      insert into ttt values (l_var);
  9* end;
SQL> /
4000
14000
declare
*
ERROR at line 1:
ORA-01461: can bind a LONG value only for insert into a LONG column
ORA-06512: at line 8

As a solution, you can try to split this variable's value into several parts (SUBSTR) and store them separately.

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

How to convert byte array to string and vice versa?

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

If you really must use a String to hold binary data then the safest way is to use Base64 encoding.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

How to concat two ArrayLists?

One ArrayList1 add to data,

mArrayList1.add(data);

and Second ArrayList2 to add other data,

mArrayList2.addAll(mArrayList1);

How to decode a Base64 string?

Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.

Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.

While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.

I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.

Base64decode("the answer to life the universe and everything") = 00101010

SQL Server 2005 How Create a Unique Constraint?

To create a UNIQUE constraint on one or multiple columns when the table is already created, use the following SQL:

ALTER TABLE TableName ADd UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)

To allow naming of a UNIQUE constraint for above query

ALTER TABLE TableName ADD CONSTRAINT un_constaint_name UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)

The query supported by MySQL / SQL Server / Oracle / MS Access.

Eclipse Problems View not showing Errors anymore

I experienced that problem with a MapReduce project. I closed the error window and never came back after doing what the other answers suggested.

Click on the bottom left -> Other -> Problems

enter image description here

How to set width of a div in percent in JavaScript?

testjs2

    $(document).ready(function() { 
      $("#form1").validate({ 
        rules: { 
          name: "required", //simple rule, converted to {required:true} 
          email: { //compound rule 
          required: true, 
          email: true 
        }, 
        url: { 
          url: true 
        }, 
        comment: { 
          required: true 
        } 
        }, 
        messages: { 
          comment: "Please enter a comment." 
        } 
      }); 
    }); 

    function()
    {
    var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
    if (ok)
    location="http://www.yahoo.com"
    else
    location="http://www.hotmail.com"
    }

    function changeWidth(){
    var e1 = document.getElementById("e1");
    e1.style.width = 400;
} 

  </script> 

  <style type="text/css"> 
    * { font-family: Verdana; font-size: 11px; line-height: 14px; } 
    .submit { margin-left: 125px; margin-top: 10px;} 
    .label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; } 
    .form-row { padding: 5px 0; clear: both; width: 700px; } 
    .label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; } 
    .input[type=text], textarea { width: 250px; float: left; } 
    .textarea { height: 50px; } 
  </style> 

  </head> 
  <body> 

    <form id="form1" method="post" action=""> 
      <div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div> 
      <div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div> 
      <div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div> 
      <div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div> 
      <div class="form-row"><input class="submit" type="submit" value="Submit"></div> 
      <input type="button" value="change width" onclick="changeWidth()"/>
      <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
    </form> 



  </body> 
</html> 

Image style height and width not taken in outlook mails

Put the width and height in separate attributes, with no unit:

<img style="margin: 0; border: 0; padding: 0; display: block;"
src="images/img.jpg" width="120" height="150">

Another Option:

<!--[if gte mso 9]>
<style type="text/css">
img.header { width: 600px; } /* or something like that */
</style>
<![endif]-->

Convert bytes to a string

If you should get the following by trying decode():

AttributeError: 'str' object has no attribute 'decode'

You can also specify the encoding type straight in a cast:

>>> my_byte_str
b'Hello World'

>>> str(my_byte_str, 'utf-8')
'Hello World'

Pip freeze vs. pip list

Look at the pip documentation, which describes the functionality of both as:

pip list

List installed packages, including editables.

pip freeze

Output installed packages in requirements format.

So there are two differences:

  1. Output format, freeze gives us the standard requirement format that may be used later with pip install -r to install requirements from.

  2. Output content, pip list include editables which pip freeze does not.

C# : Out of Memory exception

As .Net progresses, so does their ability to add new 32-bit configurations that trips everyone up it seems.

If you are on .Net Framework 4.7.2 do the following:

Go to Project Properties

Build

Uncheck 'prefer 32-bit'

Cheers!

Can I change the fill color of an svg path with CSS?

It's possible to change the path fill color of the svg. See below for the CSS snippet:

  1. To apply the color for all the path: svg > path{ fill: red }

  2. To apply for the first d path: svg > path:nth-of-type(1){ fill: green }

  3. To apply for the second d path: svg > path:nth-of-type(2){ fill: green}

  4. To apply for the different d path, change only the path number:
    svg > path:nth-of-type(${path_number}){ fill: green}

  5. To support the CSS in Angular 2 to 8, use the encapsulation concept:

:host::ng-deep svg path:nth-of-type(1){
        fill:red;
    }

use std::fill to populate vector with increasing numbers

If you'd rather not use C++11 features, you can use std::generate:

#include <algorithm>
#include <iostream>
#include <vector>

struct Generator {
    Generator() : m_value( 0 ) { }
    int operator()() { return m_value++; }
    int m_value;
};

int main()
{
    std::vector<int> ivec( 10 );

    std::generate( ivec.begin(), ivec.end(), Generator() );

    std::vector<int>::const_iterator it, end = ivec.end();
    for ( it = ivec.begin(); it != end; ++it ) {
        std::cout << *it << std::endl;
    }
}

This program prints 0 to 9.

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

indexOf and lastIndexOf in PHP?

In php:

  • stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.

  • strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.

Sample code:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

Output: Fist index = 2 Last index = 13

How to remove the first and the last character of a string

Here you go

_x000D_
_x000D_
var yourString = "/installers/";_x000D_
var result = yourString.substring(1, yourString.length-1);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Or you can use .slice as suggested by Ankit Gupta

_x000D_
_x000D_
var yourString = "/installers/services/";_x000D_
_x000D_
var result = yourString.slice(1,-1);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Documentation for the slice and substring.

How do I capture SIGINT in Python?

Register your handler with signal.signal like this:

#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

Code adapted from here.

More documentation on signal can be found here.  

How to find difference between two columns data?

There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:

SELECT
    t1.previous
    ,t1.present
    ,(t1.present - t1.previous) as difference
FROM #TEMP1 t1

Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx

Convert JSON string to array of JSON objects in Javascript

I know a lot of people are saying use eval. the eval() js function will call the compiler, and that can offer a series of security risks. It is best to avoid its usage where possible. The parse function offers a more secure alternative.

Want custom title / image / description in facebook share link from a flash app

I actually have a similar problem. I have a page with multiple radio buttons; each button will set the title and description meta tags of the page, via JavaScript upon change.

For example, if users select the first button, the meta tags will say:

<meta name="title" content="First Title">
<meta name="description" content="First Description">

If the user select the second button, this changes the meta tags to:

<meta name="title" content="Second Title">
<meta name="description" content="Second Description">

... and so on. I have confirmed that the code is working fine via Firebug (i.e. I can see that those two tags were properly changed).

Apparently, Facebook Share only pulls in the title and description meta tags that are available upon page load. The changes to those two tags post page load are completely ignored.

Does anybody have any ideas on how to solve this? That is, to force Facebook to get the latest values that are change after the page loads.

Which Android IDE is better - Android Studio or Eclipse?

Working with Eclipse can be difficult at times, probably when debugging and designing layouts Eclipse sometimes get stuck and we have to restart Eclipse from time to time. Also you get problems with emulators.

Android studio was released very recently and this IDE is not yet heavily used by developers. Therefore, it may contain certain bugs.

This describes the difference between android android studio and eclipse project structure: Android Studio Project Structure (v.s. Eclipse Project Structure)

This teaches you how to use the android studio: http://www.infinum.co/the-capsized-eight/articles/android-studio-vs-eclipse-1-0

Check if a value exists in ArrayList

Just use .contains. For example, if you were checking if an ArrayList arr contains a value val, you would simply run arr.contains(val), which would return a boolean representing if the value is contained. For more information, see the docs for .contains.

JOIN queries vs multiple queries

The real question is: Do these records have a one-to-one relationship or a one-to-many relationship?

TLDR Answer:

If one-to-one, use a JOIN statement.

If one-to-many, use one (or many) SELECT statements with server-side code optimization.

Why and How To Use SELECT for Optimization

SELECT'ing (with multiple queries instead of joins) on large group of records based on a one-to-many relationship produces an optimal efficiency, as JOIN'ing has an exponential memory leak issue. Grab all of the data, then use a server-side scripting language to sort it out:

SELECT * FROM Address WHERE Personid IN(1,2,3);

Results:

Address.id : 1            // First person and their address
Address.Personid : 1
Address.City : "Boston"

Address.id : 2            // First person's second address
Address.Personid : 1
Address.City : "New York"

Address.id : 3            // Second person's address
Address.Personid : 2
Address.City : "Barcelona"

Here, I am getting all of the records, in one select statement. This is better than JOIN, which would be getting a small group of these records, one at a time, as a sub-component of another query. Then I parse it with server-side code that looks something like...

<?php
    foreach($addresses as $address) {
         $persons[$address['Personid']]->Address[] = $address;
    }
?>

When Not To Use JOIN for Optimization

JOIN'ing a large group of records based on a one-to-one relationship with one single record produces an optimal efficiency compared to multiple SELECT statements, one after the other, which simply get the next record type.

But JOIN is inefficient when getting records with a one-to-many relationship.

Example: The database Blogs has 3 tables of interest, Blogpost, Tag, and Comment.

SELECT * from BlogPost
LEFT JOIN Tag ON Tag.BlogPostid = BlogPost.id
LEFT JOIN Comment ON Comment.BlogPostid = BlogPost.id;

If there is 1 blogpost, 2 tags, and 2 comments, you will get results like:

Row1: tag1, comment1,
Row2: tag1, comment2,
Row3: tag2, comment1,
Row4: tag2, comment2,

Notice how each record is duplicated. Okay, so, 2 comments and 2 tags is 4 rows. What if we have 4 comments and 4 tags? You don't get 8 rows -- you get 16 rows:

Row1: tag1, comment1,
Row2: tag1, comment2,
Row3: tag1, comment3,
Row4: tag1, comment4,
Row5: tag2, comment1,
Row6: tag2, comment2,
Row7: tag2, comment3,
Row8: tag2, comment4,
Row9: tag3, comment1,
Row10: tag3, comment2,
Row11: tag3, comment3,
Row12: tag3, comment4,
Row13: tag4, comment1,
Row14: tag4, comment2,
Row15: tag4, comment3,
Row16: tag4, comment4,

Add more tables, more records, etc., and the problem will quickly inflate to hundreds of rows that are all full of mostly redundant data.

What do these duplicates cost you? Memory (in the SQL server and the code that tries to remove the duplicates) and networking resources (between SQL server and your code server).

Source: https://dev.mysql.com/doc/refman/8.0/en/nested-join-optimization.html ; https://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Cannot add or update a child row: a foreign key constraint fails

I had the same issue, and the reason was that I had a row in the first table before adding the foreign key.

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

How do I find the length/number of items present for an array?

If the array is statically allocated, use sizeof(array) / sizeof(array[0])

If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0]) (which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.

How to send email in ASP.NET C#

Just go through the below code.

SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);

smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "myIDPassword");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();

//Setting From , To and CC
mail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info@MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("[email protected]"));

smtpClient.Send(mail);

Use "ENTER" key on softkeyboard instead of clicking button

To avoid the focus advancing to the next editable field (if you have one) you might want to ignore the key-down events, but handle key-up events. I also prefer to filter first on the keyCode, assuming that it would be marginally more efficient. By the way, remember that returning true means that you have handled the event, so no other listener will. Anyway, here is my version.

ETFind.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (keyCode ==  KeyEvent.KEYCODE_DPAD_CENTER
        || keyCode ==  KeyEvent.KEYCODE_ENTER) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                // do nothing yet
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                        findForward();      
            } // is there any other option here?...

            // Regardless of what we did above,
            // we do not want to propagate the Enter key up
            // since it was our task to handle it.
            return true;

        } else {
            // it is not an Enter key - let others handle the event
            return false;
        }
    }

});

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

How do I make an HTML button not reload the page

In HTML:

<input type="submit" onclick="return false">

With jQuery, some similar variant, already mentioned.

How to add 30 minutes to a JavaScript Date object?

Just another option, which I wrote:

DP_DateExtensions Library

It's overkill if this is all the date processing that you need, but it will do what you want.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

values_of_objArray = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

private ValueId : number = 0 // this will be used for multi access like 
                             // update, deleting the obj with id.
private selectedObj : any;

private selectedValueObj(id: any) {
  this.ValueId = (id.srcElement || id.target).value;
  for (let i = 0; i < this.values_of_objArray.length; i++) {
    if (this.values_of_objArray[i].id == this.ValueId) {
      this.selectedObj = this.values_of_objArray[i];
    }
  }
}

Now play with this.selectedObj which has the selected obj from the view.

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId"  
        (change)="selectedValueObj($event)" required>

  <option *ngFor="let Value of values_of_objArray"
          [value]="Value.id">{{Value.name}}</option>    
</select>

java.util.regex - importance of Pattern.compile()?

The compile() method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int) to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher() method, and the only way to get ahold of the Pattern object is through the compile() method. Then there's the find() method which, unlike matches(), is not duplicated in the String or Pattern classes.

The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches() method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:

for (String s : myStringList) {
    if ( s.matches("\\d+") ) {
        doSomething();
    }
}

...is exactly equivalent to this:

for (String s : myStringList) {
    if ( Pattern.compile("\\d+").matcher(s).matches() ) {
        doSomething();
    }
}

Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
    if ( m.reset(s).matches() ) {
        doSomething();
    }
}

If you're familiar with .NET regexes, you may be wondering if Java's compile() method is related to .NET's RegexOptions.Compiled modifier; the answer is no. Java's Pattern.compile() method is merely equivalent to .NET's Regex constructor. When you specify the Compiled option:

Regex r = new Regex(@"\d+", RegexOptions.Compiled); 

...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String) and one you create explicitly with Pattern#compile(String).

(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches(), not when you call a Regex constructor directly. ref)

Apply function to each column in a data frame observing each columns existing data type

building on @ltamar's answer:
Use summary and munge the output into something useful!

library(tidyr)
library(dplyr)

df %>% 
  summary %>% 
  data.frame %>%
  select(-Var1) %>%
  separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
  rename(column_name=Var2) %>%
  mutate(value=as.numeric(value),
         metric = trimws(metric,'both') 
  ) %>%  
  filter(!is.na(value)) -> metrics

It's not pretty and it is certainly not fast but it gets the job done!

RelativeLayout center vertical

        <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginHorizontal="5dp"
        android:layout_marginBottom="5dp"
        android:background="@drawable/default_button">

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:layout_marginStart="15dp"
            android:src="@drawable/google" />

        <Button
            android:id="@+id/btnGmailLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:paddingHorizontal="15dp"
            android:text="@string/gmail_login_button_text"
            android:textAllCaps="false"
            android:textColor="@color/black" />
    </RelativeLayout>

Headers and client library minor version mismatch

The root reason for this error is that PHP separated itself from the MySQL Client libraries some time ago. So what's happening (mainly on older compiles of linux) is that people will compile PHP against a given build of the MySQL Client (meaning the version of MySQL installed is irrelevant) and not upgrade (in CentOS this package is listed as mysqlclientXX, where XX represents the package number). This also allows the package maintainer to support lower versions of MySQL. It's a messy way to do it, but it was the only way given how PHP and MySQL use different licensing.

MySQLND solves the problem by using PHP's own native driver (the ND), which no longer relies on MySQL Client. It's also compiled for the version of PHP you're using. This is a better solution all around, if for no other reason that MySQLND is made to have PHP talk to MySQL.

If you can't install MySQLND you can actually safely ignore this error for the most part. It's just more of an FYI notice than anything. It just sounds scary.

Class has no initializers Swift

simply provide the init block for HomeCell class

it's work in my case

Horizontal scroll on overflow of table

The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

_x000D_
_x000D_
table {_x000D_
  display: block;_x000D_
  max-width: -moz-fit-content;_x000D_
  max-width: fit-content;_x000D_
  margin: 0 auto;_x000D_
  overflow-x: auto;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A centered table.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

WARNING: sanitizing unsafe style value url

I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.

First, write below code in the component file.

constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
}

Now in your html image tag, you can write like this.

<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />

You can write as per your requirement instead of item.imageUrl

I got a reference from this site.dynamic urls. Hope this solution will help you :)

How to update npm

Check your node version node -v and your npm version npm -v Then To update your npm, type this into your terminal : sudo npm install npm@latest -g

N.B: Debian Based OS{ubuntu or Linux mint}

Explanation of JSONB introduced by PostgreSQL

I was at the pgopen today benchmarks are way faster than mongodb, I believe it was around 500% faster for selects. Pretty much everything was faster at least by at 200% when contrasted with mongodb, than one exception right now is a update which requires completely rewriting the entire json column something mongodb handles better.

The gin indexing on on jsonb sounds amazing.

Also postgres will persist types of jsonb internally and basically match this with types such as numeric, text, boolean etc.

Joins will also be possible using jsonb

Add PLv8 for stored procedures and this will basically be a dream come true for node.js developers.

Being it's stored as binary jsonb will also strip all whitespace, change the ordering of properties and remove duplicate properties using the last occurance of the property.

Besides the index when querying against a jsonb column contrasted to a json column postgres doesn't have to actually run the functionality to convert the text to json on every row which will likely save a vast amount of time alone.

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

Prepend text to beginning of string

You could do it this way ..

_x000D_
_x000D_
var mystr = 'is my name.';_x000D_
mystr = mystr.replace (/^/,'John ');_x000D_
_x000D_
console.log(mystr);
_x000D_
_x000D_
_x000D_

disclaimer: http://xkcd.com/208/


Wait, forgot to escape a space.  Wheeeeee[taptaptap]eeeeee.

Regular expression field validation in jQuery

If you wanted to search some elements based on a regex, you can use the filter function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.

$("input:text")
    .filter(function() {
        return this.value.match(/[^\d]/);
    })
    .addClass("inputError")
;

Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id matches /[a-z]+_\d+/

$("[id]").filter(function() {
    return this.id.match(/[a-z]+_\d+/);
});

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

Python/Json:Expecting property name enclosed in double quotes

I've checked your JSON data

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

in http://jsonlint.com/ and the results were:

Error: Parse error on line 1:
{   'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'

modifying it to the following string solve the JSON error:

{
    "http://example.org/about": {
        "http://purl.org/dc/terms/title": [{
            "type": "literal",
            "value": "Anna's Homepage"
        }]
    }
}

Pandas read_csv from url

UPDATE: From pandas 0.19.2 you can now just pass read_csv() the url directly, although that will fail if it requires authentication.


For older pandas versions, or if you need authentication, or for any other HTTP-fault-tolerant reason:

Use pandas.read_csv with a file-like object as the first argument.

  • If you want to read the csv from a string, you can use io.StringIO.

  • For the URL https://github.com/cs109/2014_data/blob/master/countries.csv, you get html response, not raw csv; you should use the url given by the Raw link in the github page for getting raw csv response , which is https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv

Example:

import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))

Notes:

in Python 2.x, the string-buffer object was StringIO.StringIO

How can I get city name from a latitude and longitude point?

BigDataCloud also has a nice API for this, also for nodejs users.

they have API for client - free. But also for backend, using API_KEY (free according to quota).

Their GitHub page.

the code looks like:

const client = require('@bigdatacloudapi/client')(API_KEY);

async foo() {
    ...
    const location: string = await client.getReverseGeocode({
          latitude:'32.101786566878445', 
          longitude: '34.858965073072056'
    });
}

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

How to find where gem files are installed

if you are using rvm tool you can run this command to print gem path:

rvm gemdir

OR

echo $GEM_HOME

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file: '/usr/share/phpmyadmin/libraries/sql.lib.php'

Replace: (count($analyzed_sql_results['select_expr'] == 1)

With: (count($analyzed_sql_results['select_expr']) == 1

this worked for me

How can I create an Asynchronous function in Javascript?

This page walks you through the basics of creating an async javascript function.

Since ES2017, asynchronous javacript functions are much easier to write. You should also read more on Promises.

What's the fastest way to loop through an array in JavaScript?

If you want a faster for loop, define your variables outside the loop and use below syntax

  const iMax = lengthOftheLoop;
  var i = 0;
  for (; i < iMax; i++) {
    console.log("loop"+i);
  }

reference: https://medium.com/kbdev/voyage-to-the-most-efficient-loop-in-nodejs-and-a-bit-js-5961d4524c2e

Can I specify multiple users for myself in .gitconfig?

git aliases (and sections in git configs) to the rescue!

add an alias (from command line):

git config --global alias.identity '! git config user.name "$(git config user.$1.name)"; git config user.email "$(git config user.$1.email)"; :'

then, set, for example

git config --global user.github.name "your github username"
git config --global user.github.email [email protected]

and in a new or cloned repo you can run this command:

git identity github

This solution isn't automatic, but unsetting user and email in your global ~/.gitconfig and setting user.useConfigOnly to true would force git to remind you to set them manually in each new or cloned repo.

git config --global --unset user.name
git config --global --unset user.email
git config --global user.useConfigOnly true

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

Java 8 List<V> into Map<K, V>

It's possible to use streams to do this. To remove the need to explicitly use Collectors, it's possible to import toMap statically (as recommended by Effective Java, third edition).

import static java.util.stream.Collectors.toMap;

private static Map<String, Choice> nameMap(List<Choice> choices) {
    return choices.stream().collect(toMap(Choice::getName, it -> it));
}

How to use Tomcat 8 in Eclipse?

If you have untarred your own version of tomcat v8 with a root user into a custom directory (linux) then the default permissions on the TOMCATROOT/lib directory do not allow normal user access.

Eclipse will not be able to see the catalina.jar to check the version. So no amount of fiddling aorund with the server.properties will help!

just add chmod u+x lib/ to allow normal user access to the libs.

How do I find the PublicKeyToken for a particular dll?

As @CRice said you can use the below method to get a list of dependent assembly with publicKeyToken

public static int DependencyInfo(string args) 
{
    Console.WriteLine(Assembly.LoadFile(args).FullName);
    Console.WriteLine(Assembly.LoadFile(args).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false).SingleOrDefault());
    try {
        var assemblies = Assembly.LoadFile(args).GetReferencedAssemblies(); 

        if (assemblies.GetLength(0) > 0)
        {
            foreach (var assembly in assemblies)
            {
                Console.WriteLine(" - " + assembly.FullName + ", ProcessorArchitecture=" + assembly.ProcessorArchitecture);             
            }
            return 0;
        }
    }
    catch(Exception e) {
        Console.WriteLine("An exception occurred: {0}", e.Message);
        return 1;
    } 
    finally{}

    return 1;
}

i generally use it as a LinqPad script you can call it as

DependencyInfo("@c:\MyAssembly.dll"); from the code

How do I line up 3 divs on the same row?

I'm not sure how I ended up on this post but since most of the answers are using floats, absolute positioning, and other options which aren't optimal now a days, I figured I'd give a new answer that's more up to date on it's standards (float isn't really kosher anymore).

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction:row;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex: 1 1 0px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="column">Column 1</div>_x000D_
    <div class="column">Column 2<br>Column 2<br>Column 2<br>Column 2<br></div>_x000D_
    <div class="column">Column 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting Django admin url for an object

I had a similar issue where I would try to call reverse('admin_index') and was constantly getting django.core.urlresolvers.NoReverseMatch errors.

Turns out I had the old format admin urls in my urls.py file.

I had this in my urlpatterns:

(r'^admin/(.*)', admin.site.root),

which gets the admin screens working but is the deprecated way of doing it. I needed to change it to this:

(r'^admin/', include(admin.site.urls) ),

Once I did that, all the goodness that was promised in the Reversing Admin URLs docs started working.

Check if checkbox is NOT checked on click - jQuery

Do it like this

if (typeof $(this).attr("checked") == "undefined" )

// To check if checkbox is checked
if( $(this).attr("checked")=="checked")

How to lose margin/padding in UITextView?

For me (iOS 11 & Xcode 9.4.1) what worked magically was setting up textView.font property to UIFont.preferred(forTextStyle:UIFontTextStyle) style and also the first answer as mentioned by @Fattie. But the @Fattie answer did not work till I set the textView.font property else UITextView keeps behaving erratically.

Shuffle an array with python, randomize array item order with python

When dealing with regular Python lists, random.shuffle() will do the job just as the previous answers show.

But when it come to ndarray(numpy.array), random.shuffle seems to break the original ndarray. Here is an example:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

Just use: np.random.shuffle(a)

Like random.shuffle, np.random.shuffle shuffles the array in-place.

How to parse JSON data with jQuery / JavaScript?

Try following code, it works in my project:

//start ajax request
$.ajax({
    url: "data.json",
    //force to handle it as text
    dataType: "text",
    success: function(data) {

        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        //now json variable contains data in json format
        //let's display a few items
        for (var i=0;i<json.length;++i)
        {
            $('#results').append('<div class="name">'+json[i].name+'</>');
        }
    }
});

Could not establish secure channel for SSL/TLS with authority '*'

In case it helps anyone else, using the new Microsoft Web Service Reference Provider tool, which is for .NET Standard and .NET Core, I had to add the following lines to the binding definition as below:

binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport = new HttpTransportSecurity{ClientCredentialType = HttpClientCredentialType.Certificate};

This is effectively the same as Micha's answer but in code as there is no config file.

So to incorporate the binding with the instantiation of the web service I did this:

 System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
 binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
 binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Certificate;
 var client = new WebServiceClient(binding, GetWebServiceEndpointAddress());

Where WebServiceClient is the proper name of your web service as you defined it.

css divide width 100% to 3 column

I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:

HTML code:

<div id="container">
   <div id="col1"></div>
   <div id="col2"></div>
   <div id="col3"></div>
</div>

JS Code:

$(function(){
   var total = $("#container").width();
   $("#col1").css({width: Math.round(total/3)+"px"});
   $("#col2").css({width: Math.round(total/3)+"px"});
   $("#col3").css({width: Math.round(total/3)+"px"});
});

How to delete files recursively from an S3 bucket

In case using AWS-SKD for ruby V2.

s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
  next if obj.key == "foo/" 
  resp = s3.delete_object({
    bucket: bucket_name,
    key: obj.key,
  })
end

attention please, all "foo/*" under bucket will delete.

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

How to create a date and time picker in Android?

combined DatePicker and TimePicker in DialogFragment for Android

I created a library to do this. It also has customizable colors!

It's very simple to use.

First you create a listener:

private SlideDateTimeListener listener = new SlideDateTimeListener() {

    @Override
    public void onDateTimeSet(Date date)
    {
        // Do something with the date. This Date object contains
        // the date and time that the user has selected.
    }

    @Override
    public void onDateTimeCancel()
    {
        // Overriding onDateTimeCancel() is optional.
    }
};

Then you create and show the dialog:

new SlideDateTimePicker.Builder(getSupportFragmentManager())
    .setListener(listener)
    .setInitialDate(new Date())
    .build()
    .show();

I hope you find it useful.

How to convert latitude or longitude to meters?

If you want a simple solution then use the Haversine formula as outlined by the other comments. If you have an accuracy sensitive application keep in mind the Haversine formula does not guarantee an accuracy better then 0.5% as it is assuming the earth is a sphere. To consider that Earth is a oblate spheroid consider using Vincenty's formulae. Additionally, I'm not sure what radius we should use with the Haversine formula: {Equator: 6,378.137 km, Polar: 6,356.752 km, Volumetric: 6,371.0088 km}.

SQL Developer is returning only the date, not the time. How do I fix this?

From Tools > Preferences > Database > NLS Parameter and set Date Format as

DD-MON-RR HH:MI:SS

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date

Basic authentication with fetch?

A simple example for copy-pasting into Chrome console:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

Add event handler for body.onload by javascript within <body> part

Simply wrap the code you want to execute into the onload event of the window object:

window.onload = function(){ 
   // your code here
}

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

XSS prevention in JSP/Servlet web application

Managing XSS requires multiple validations, data from the client side.

  1. Input Validations (form validation) on the Server side. There are multiple ways of going about it. You can try JSR 303 bean validation(hibernate validator), or ESAPI Input Validation framework. Though I've not tried it myself (yet), there is an annotation that checks for safe html (@SafeHtml). You could in fact use Hibernate validator with Spring MVC for bean validations -> Ref
  2. Escaping URL requests - For all your HTTP requests, use some sort of XSS filter. I've used the following for our web app and it takes care of cleaning up the HTTP URL request - http://www.servletsuite.com/servlets/xssflt.htm
  3. Escaping data/html returned to the client (look above at @BalusC explanation).

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Android: set view style programmatically

I used views defined in XML in my composite ViewGroup, inflated them added to Viewgroup. This way I cannot dynamically change style but I can make some style customizations. My composite:

public class CalendarView extends LinearLayout {

private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;

private CalendarAdapter calendarAdapter;

public CalendarView(Context context) {
    super(context);

}

public CalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);

}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    init();
}

private void init() {
    mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
    mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);

    calendarAdapter = new CalendarAdapter(getContext());
    mCalendarGrid.setAdapter(calendarAdapter);
    mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}

}

and my view in xml where i can assign styles:

<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>

<GridView
    android:id="@+id/calendarContents"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:id="@+id/calendarFooter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    />

How to remove a column from an existing table?

This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.

  1. Put table in Design view (right click on table) like so:

enter image description here

  1. Right click on column in table's Design view and click "Delete Column"

enter image description here

As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

Upload Progress Bar in PHP

I'm sorry to say that to the best of my knowledge a pure PHP upload progress bar, or even a PHP/Javascript upload progress bar is not possible because of how PHP works. Your best bet is to use some form of Flash uploader.

AFAIK This is because your script is not executed until all the superglobals are populated, which includes $_FILES. By the time your PHP script gets called, the file is fully uploaded.

EDIT: This is no longer true. It was in 2010.

Why is pydot unable to find GraphViz's executables in Windows 8?

Tried all installation sequence as described in all solutions/posting/blogs, finally realized anaconda was not able to read the Environment variables. Closed Anaconda and Spyder. Then opened Anaconda in Administrator mode (on Windows 64 bit OS machine) and then opened Spyder. Script worked fine with PYDOT calls.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

A 'macroable' replacement to get the SQL query with the bindings.

  1. Add below macro function in AppServiceProvider boot() method.

    \Illuminate\Database\Query\Builder::macro('toRawSql', function(){
        return array_reduce($this->getBindings(), function($sql, $binding){
            return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
        }, $this->toSql());
    });
    
  2. Add an alias for the Eloquent Builder. (Laravel 5.4+)

    \Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
        return ($this->getQuery()->toRawSql());
    });
    
  3. Then debug as usual. (Laravel 5.4+)

    E.g. Query Builder

    \Log::debug(\DB::table('users')->limit(1)->toRawSql())
    

    E.g. Eloquent Builder

    \Log::debug(\App\User::limit(1)->toRawSql());
    

Note: from Laravel 5.1 to 5.3, Since Eloquent Builder doesn't make use of the Macroable trait, cannot add toRawSql an alias to the Eloquent Builder on the fly. Follow the below example to achieve the same.

E.g. Eloquent Builder (Laravel 5.1 - 5.3)

\Log::debug(\App\User::limit(1)->getQuery()->toRawSql());

Android Studio - local path doesn't exist

I managed to find a temporary workaround. Do all by yourself using command line :

// build apk
./gradlew assemble --daemon

// debug apk is unaligned so we need to align it
zipalign -f 4 app/build/apk/app-debug-unaligned.apk app/build/apk/app-debug.apk

// reinstall it using adb
adb install -r app/build/apk/app-debug.apk

This is temporary, but I hope they will fix this for 0.2.5

Edit : not fixed in 0.2.5

Edit2 : fixed for now by adding in my module.iml file (in facet/configuration) :

<option name="APK_PATH" value="/build/apk/appname-debug-unaligned.apk" />

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

DBMS_OUTPUT is not the best tool to debug, since most environments don't use it natively. If you want to capture the output of DBMS_OUTPUT however, you would simply use the DBMS_OUTPUT.get_line procedure.

Here is a small example:

SQL> create directory tmp as '/tmp/';

Directory created

SQL> CREATE OR REPLACE PROCEDURE write_log AS
  2     l_line VARCHAR2(255);
  3     l_done NUMBER;
  4     l_file utl_file.file_type;
  5  BEGIN
  6     l_file := utl_file.fopen('TMP', 'foo.log', 'A');
  7     LOOP
  8        EXIT WHEN l_done = 1;
  9        dbms_output.get_line(l_line, l_done);
 10        utl_file.put_line(l_file, l_line);
 11     END LOOP;
 12     utl_file.fflush(l_file);
 13     utl_file.fclose(l_file);
 14  END write_log;
 15  /

Procedure created

SQL> BEGIN
  2     dbms_output.enable(100000);
  3     -- write something to DBMS_OUTPUT
  4     dbms_output.put_line('this is a test');
  5     -- write the content of the buffer to a file
  6     write_log;
  7  END;
  8  /

PL/SQL procedure successfully completed

SQL> host cat /tmp/foo.log

this is a test

How to connect android wifi to adhoc wifi?

You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.

Execute Insert command and return inserted Id in Sql

Change the query to

"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"

This will return the last inserted ID which you can then get with ExecuteScalar

HintPath vs ReferencePath in Visual Studio

Look in the file Microsoft.Common.targets

The answer to the question is in the file Microsoft.Common.targets for your target framework version.

For .Net Framework version 4.0 (and 4.5 !) the AssemblySearchPaths-element is defined like this:

    <!--
    The SearchPaths property is set to find assemblies in the following order:

        (1) Files from current project - indicated by {CandidateAssemblyFiles}
        (2) $(ReferencePath) - the reference path property, which comes from the .USER file.
        (3) The hintpath from the referenced item itself, indicated by {HintPathFromItem}.
        (4) The directory of MSBuild's "target" runtime from GetFrameworkPath.
            The "target" runtime folder is the folder of the runtime that MSBuild is a part of.
        (5) Registered assembly folders, indicated by {Registry:*,*,*}
        (6) Legacy registered assembly folders, indicated by {AssemblyFolders}
        (7) Resolve to the GAC.
        (8) Treat the reference's Include as if it were a real file name.
        (9) Look in the application's output folder (like bin\debug)
    -->
<AssemblySearchPaths Condition=" '$(AssemblySearchPaths)' == ''">
  {CandidateAssemblyFiles};
  $(ReferencePath);
  {HintPathFromItem};
  {TargetFrameworkDirectory};
  {Registry:$(FrameworkRegistryBase),$(TargetFrameworkVersion),$(AssemblyFoldersSuffix)$(AssemblyFoldersExConditions)};
  {AssemblyFolders};
  {GAC};
  {RawFileName};
  $(OutDir)
</AssemblySearchPaths>

For .Net Framework 3.5 the definition is the same, but the comment is wrong. The 2.0 definition is slightly different, it uses $(OutputPath) instead of $(OutDir).

On my machine I have the following versions of the file Microsoft.Common.targets:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets

This is with Visual Studio 2008, 2010 and 2013 installed on Windows 7.

The fact that the output directory is searched can be a bit frustrating (as the original poster points out) because it may hide an incorrect HintPath. The solution builds OK on your local machine, but breaks when you build on in a clean folder structure (e.g. on the build machine).

Ignore python multiple return value

The best solution probably is to name things instead of returning meaningless tuples (unless there is some logic behind the order of the returned items). You can for example use a dictionary:

def func():
    return {'lat': 1, 'lng': 2}
    
latitude = func()['lat']

You could even use namedtuple if you want to add extra information about what you are returning (it's not just a dictionary, it's a pair of coordinates):

from collections import namedtuple 

Coordinates = namedtuple('Coordinates', ['lat', 'lng'])

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat

If the objects within your dictionary/tuple are strongly tied together then it may be a good idea to even define a class for it. That way you'll also be able to define more complex operations. A natural question that follows is: When should I be using classes in Python?

Most recent versions of python (= 3.7) have dataclasses which you can use to define classes with very few lines of code:

from dataclasses import dataclass

@dataclass
class Coordinates:
    lat: float = 0
    lng: float = 0

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat

The primary advantage of dataclasses over namedtuple is that its easier to extend, but there are other differences. Note that by default, dataclasses are mutable, but you can use @dataclass(frozen=True) instead of @dataclass to force them being immutable.

what's the default value of char?

The default value of a char primitive type is '\u0000'(null character) as stated in the Java Language Specification.

The shortcut for 'u0000' is '\0', So the null can be represented either by 'u0000' or '\0'.

The below Java program validates null representations using instance char field 'c'.

public class DefaultValueForchar {  
    char c;
    public static void main(String[] args) {
        char c0 = '\0';
        char cu0000 = '\u0000';
        DefaultValueForchar obj = new DefaultValueForchar();
        System.out.println(obj.c);
        System.out.println(c0);
        System.out.println(cu0000);
        System.out.println(c0==cu0000);
        System.out.println(obj.c==c0);
        System.out.println(obj.c==cu0000);
    }

}

output:

What is difference between monolithic and micro kernel?

Monolithic kernel

All the parts of a kernel like the Scheduler, File System, Memory Management, Networking Stacks, Device Drivers, etc., are maintained in one unit within the kernel in Monolithic Kernel

Advantages

•Faster processing

Disadvantages

•Crash Insecure •Porting Inflexibility •Kernel Size explosion

Examples •MS-DOS, Unix, Linux

Micro kernel

Only the very important parts like IPC(Inter process Communication), basic scheduler, basic memory handling, basic I/O primitives etc., are put into the kernel. Communication happen via message passing. Others are maintained as server processes in User Space

Advantages

•Crash Resistant, Portable, Smaller Size

Disadvantages

•Slower Processing due to additional Message Passing

Examples •Windows NT

Convert seconds value to hours minutes seconds?

With Java 8, you can easily achieve time in String format from long seconds like,

LocalTime.ofSecondOfDay(86399L)

Here, given value is max allowed to convert (upto 24 hours) and result will be

23:59:59

Pros : 1) No need to convert manually and to append 0 for single digit

Cons : work only for up to 24 hours

Why can't I use background image and color together?

To tint an image, you can use CSS3 background to stack images and a linear-gradient. In the example below, I use a linear-gradient with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.

background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;

Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.

Excellent documentation by Mozilla, here:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds

Tool for building the gradients:

http://www.colorzilla.com/gradient-editor/

Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

java build path problems

From the Package Explorer in Eclipse, you can right click the project, choose Build Path, Configure Build Path to get the build path dialog. From there you can remove the JRE reference for the 1.5 JRE and 'Add Library' to add a reference to your installed JRE.

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Using Regex:

import re

strip_unicode = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)")
print strip_unicode.sub('', u'6Â 918Â 417Â 712')

JAX-WS - Adding SOAP Headers

In jaxws-rt-2.2.10-ources.jar!\com\sun\xml\ws\transport\http\client\HttpTransportPipe.java:

public Packet process(Packet request) {
        Map<String, List<String>> userHeaders = (Map<String, List<String>>) request.invocationProperties.get(MessageContext.HTTP_REQUEST_HEADERS);
        if (userHeaders != null) {
            reqHeaders.putAll(userHeaders);

So, Map<String, List<String>> from requestContext with key MessageContext.HTTP_REQUEST_HEADERS will be copied to SOAP headers. Sample of Application Authentication with JAX-WS via headers

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY keys are processed special way in HttpTransportPipe.addBasicAuth(), adding standard basic authorization Authorization header.

See also Message Context in JAX-WS

how to add or embed CKEditor in php page

<?php require("ckeditor/ckeditor.php"); ?>

 <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
 <script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>

<textarea class="ckeditor" name="editor1"></textarea>

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

C# 4.0: Convert pdf to byte[] and vice versa

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Change drawable color programmatically

You could try a ColorMatrixColorFilter, since your key color is white:

// Assuming "color" is your target color
float r = Color.red(color) / 255f;
float g = Color.green(color) / 255f;
float b = Color.blue(color) / 255f;

ColorMatrix cm = new ColorMatrix(new float[] {
        // Change red channel
        r, 0, 0, 0, 0,
        // Change green channel
        0, g, 0, 0, 0,
        // Change blue channel
        0, 0, b, 0, 0,
        // Keep alpha channel
        0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
myDrawable.setColorFilter(cf);

How do you modify the web.config appSettings at runtime?

I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.

I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.

The project goals were very simple;

  1. get ASP.NET to communicate with ZooKeeper
  2. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.

Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;

ConfigurationManager.AppSettings.Add(key_name, data_value)

That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.

After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.

With a little trial and error, I found the following code would do exactly what I wanted;

ConfigurationManager.AppSettings.Set(key_name, data_value)

Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.

In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;

appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True

With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.

This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.

I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

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

UPDATE: The latest version of Android studio (2.x) made major improvements to the bundled emulator. It's responsive and has a whole bunch of features.

For those still interested: Try using Genymotion. You can download a version for Windows/Mac OS X/Linux after registering. A plugin for Eclipse is also available:

The installation of the plugin can be done by launching Eclipse and going to "Help / Install New Software" menu, then just add a new Update Site with the following URL: http://plugins.genymotion.com/eclipse. Follow the steps indicated by Eclipse.

This emulator is fast and responsive.

GenyMotion allows you to control various sensors of your device including the battery level, signal strength, and GPS. The latest version now also contains camera tools.

UIScrollView not scrolling

The idea of why scroll view is not scrolling because you set the content size for scrolling less than the size of the scroll view, which is wrong. You should set the content size bigger than the size of your scroll view to navigate through it while scrolling.

The same idea with zooming, you set the min and max value for zooming which will applied through zooming action.

welcome :)

Visual Studio Code always asking for git credentials

Solve the issue by following steps.

Uninstalled softwares Vscode and git and reinstalled the same. Changed the git repository clone url from ssh to https.

What is the difference between char * const and const char *?

const * char is invalid C code and is meaningless. Perhaps you meant to ask the difference between a const char * and a char const *, or possibly the difference between a const char * and a char * const?

See also:

How to set JAVA_HOME in Mac permanently?

If you are using fish shell. Then all the variables can be set in .config/fish/config.fish

vim .config/fish/config.fish

Add the following lines

set -g JAVA_HOME "your_path_to_jdk"

save and exit out of vim.

This should be setting your JAVA_HOME. Thanks

PostgreSQL: Why psql can't connect to server?

During fresh installation of postgresql. By default, user name and password is assigned as "postgres". The feature this RDBMS provides is to add role for new user and create database. If you are getting such errors:

  1. login in by default username:

    root@kalilinux:~# sudo -i -u postgres

  2. ype psql for interactive prompt

    postgres@kalilinux:~$ psql

  3. To quit from prompt use

    \q

  4. To create new user role

    postgres@kalilinux:~$ createuser --interactive

Now you are in interacive psql shell. Enjoy. Dont forget to login in from your username and type psql for shell.

How to install SignTool.exe for Windows 10

SignTool is available as part of the Windows SDK (which comes with Visual Studio Community 2015). Make sure to select the "ClickOnce Publishing Tools" from the feature list during the installation of Visual Studio 2015 to get the SignTool.

ClickOnce Publishing Tools

Once Visual Studio is installed you can run the signtool command from the Visual Studio Command Prompt.

By default (on Windows 10) the SignTool will be installed in:

  • C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Check your application is building successfully by running mvn clean install over your project and correct all the errors

Usually this error comes when you have dependencies which are not present on your classpath.

If you are using tomcat maven plugin then try deploying your war using following command

tomcat7:run-war-only

Querying a linked sql server

You can use:

SELECT * FROM [aa-db-dev01].[TestDB].[dbo].[users];

Histogram Matplotlib

I just realized that the hist documentation is explicit about what to do when you already have an np.histogram

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

The important part here is that your counts are simply the weights. If you do it like that, you don't need the bar function anymore

Determine number of pages in a PDF file

I've used the code above that solves the problem using regex and it works, but it's quite slow. It reads the entire file to determine the number of pages.

I used it in a web app and pages would sometimes list 20 or 30 PDFs at a time and in that circumstance the load time for the page went from a couple seconds to almost a minute due to the page counting method.

I don't know if the 3rd party libraries are much better, I would hope that they are and I've used pdflib in other scenarios with success.

Java2D: Increase the line width

What is Stroke:

The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

Note that the Stroke setting:

Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));

is setting the line width,since BasicStroke(float width):

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2) and Graphics2D.drawRect(int x, int y, int width, int height):

The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.

How do you install GLUT and OpenGL in Visual Studio 2012?

  1. Download and install Visual C++ Express.

  2. Download and extract "freeglut 2.8.0 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/

  3. Installation for Windows 32 bit:

(a) Copy all files from include/GL folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl folder.

(b) Copy all files from lib folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib folder.

(c) Copy freeglut.dll and paste into C:\windows\system32 folder.

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

How to save LogCat contents to file?

You are not getting the answer you are looking for, are you.

Two ways to do what you want:

  1. Right-click in the logcat messages window, choose select all. Then your save will be all logcat messages in that window (including the ones scrolled out of view).
  2. When focus is in logcat messages window, type control-A, this will select all messages. Then save etc. etc.

What's a .sh file?

Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.

CSS: auto height on containing div, 100% height on background div inside containing div

In 2018 a lot of browsers support the Flexbox and Grid which are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer).

In order to implement this with the Grid, it is enough to specify display: grid and grid-template-columns on the container. The grid-template-columns depends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto, which basically means that each of the columns will have auto width.

Full working example with Grid:

_x000D_
_x000D_
html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.grid-container {_x000D_
    display: grid;_x000D_
    grid-template-columns: auto auto auto;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.grid-item {_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title>Three Columns with Grid</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
    <div class="grid-container">_x000D_
        <div class="grid-item a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        </div>_x000D_
        <div class="grid-item b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        </div>_x000D_
        <div class="grid-item c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Another way would be to use the Flexbox by specifying display: flex on the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway).

Full working example using Flexbox:

_x000D_
_x000D_
html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.flex-container {_x000D_
    display: flex;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.flex-column {_x000D_
    padding: 20px;_x000D_
    width: 33.3333%;_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title>Three Columns with Flexbox</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
    <div class="flex-container">_x000D_
        <div class="flex-column a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        </div>_x000D_
        <div class="flex-column b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        </div>_x000D_
        <div class="flex-column c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by caniuse.com: Can I use grid, Can I use flex.

There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique, Faux Columns Technique, CSS Tabular Display Technique and there is also a Layering Technique.

I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons.

A solution for equally height-ed columns is the CSS Tabular Display Technique that means to use the display:table feature. It works for Firefox 2+, Safari 3+, Opera 9+ and IE8.

The code for the CSS Tabular Display:

_x000D_
_x000D_
#container {_x000D_
  display: table;_x000D_
  background-color: #CCC;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.col {_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
#col1 {_x000D_
  background-color: #0CC;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#col2 {_x000D_
  background-color: #9F9;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#col3 {_x000D_
  background-color: #699;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="rowWraper" class="row">_x000D_
    <div id="col1" class="col">_x000D_
      Column 1<br />Lorem ipsum<br />ipsum lorem_x000D_
    </div>_x000D_
    <div id="col2" class="col">_x000D_
      Column 2<br />Eco cologna duo est!_x000D_
    </div>_x000D_
    <div id="col3" class="col">_x000D_
      Column 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600px long word) or some div's who's width is greater than the table-cell's width.

The Faux Column Technique is the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution.

The OneTrueLayout Technique consists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottom of the same huge value and hiding the extent created by the padding with overflow: hidden applied to the content wraper. A simplified example would be:

Working example:

_x000D_
_x000D_
.wraper {_x000D_
    overflow: hidden; /* This is important */_x000D_
}_x000D_
_x000D_
.floatLeft {_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
.block {_x000D_
    padding-left: 20px;_x000D_
    padding-right: 20px;_x000D_
    padding-bottom: 30000px; /* This is important */_x000D_
    margin-bottom: -30000px; /* This is important */_x000D_
    width: 33.3333%;_x000D_
    box-sizing: border-box; /* This is so that the padding right and left does not affect the width */_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>OneTrueLayout</title>_x000D_
</head>_x000D_
<body>_x000D_
    <div class="wraper">_x000D_
        <div class="block floatLeft a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p>_x000D_
        </div>_x000D_
        <div class="block floatLeft b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p>_x000D_
        </div>_x000D_
        <div class="block floatLeft c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The Layering Technique must be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relative to it's css attribute collection. The children of this div are all imperatively position:absolute. The children must have top and bottom set to 0 and left-right dimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100px and the other one of 200px, considering that we want the 100px in the left side and the 200px in the right side, the left column must have {left: 0; right: 200px} and the right column {left: 100px; right: 0;}

In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid).

Other resources: link1, link2, link3, link4, link5 (important)

How to see full absolute path of a symlink

You can use awk with a system call readlink to get the equivalent of an ls output with full symlink paths. For example:

ls | awk '{printf("%s ->", $1); system("readlink -f " $1)}'

Will display e.g.

thin_repair ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_restore ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_rmap ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_trim ->/home/user/workspace/boot/usr/bin/pdata_tools
touch ->/home/user/workspace/boot/usr/bin/busybox
true ->/home/user/workspace/boot/usr/bin/busybox

How to clear gradle cache?

UPDATE

cleanBuildCache no longer works.

Android Gradle plugin now utilizes Gradle cache feature
https://guides.gradle.org/using-build-cache/

TO CLEAR CACHE

Clean the cache directory to avoid any hits from previous builds

 rm -rf $GRADLE_HOME/caches/build-cache-*

https://guides.gradle.org/using-build-cache/#caching_android_projects

Other digressions: see here (including edits).


=== OBSOLETE INFO ===

Newest solution using Gradle task:

cleanBuildCache

Available via Android plugin for Gradle, revision 2.3.0 (February 2017)

Dependencies:

  1. Gradle 3.3 or higher.
  2. Build Tools 25.0.0 or higher.

More info at:
https://developer.android.com/studio/build/build-cache.html#clear_the_build_cache

Background

Build cache
Stores certain outputs that the Android plugin generates when building your project (such as unpackaged AARs and pre-dexed remote dependencies). Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. Projects using Android plugin 2.3.0 and higher use the build cache by default. To learn more, read Improve Build Speed with Build Cache.

NOTE: The cleanBuildCache task is not available if you disable the build cache.


USAGE

Windows:

gradlew cleanBuildCache

Linux / Mac:

gradle cleanBuildCache

Android Studio / IntelliJ:

gradle tab (default on right) select and run the task or add it via the configuration window 

NOTE: gradle / gradlew are system specific files containing scripts. Please see the related system info how to execute the scripts:

How to read and write INI file with Python3?

contents in my backup_settings.ini file

[Settings]
year = 2020

python code for reading

import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year") 
print(year)

for writing or updating

from pathlib import Path
import configparser
myfile = Path('backup_settings.ini')  #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry 
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))

output

[Settings]
year = 2050
day = sunday

How to print all key and values from HashMap in Android?

HashMap <Integer,Integer> hm = new HashMap<Integer,Integer>();

Set<Integer> keys = hm.keySet();  //get all keys
for(Integer i: keys)
{
    System.out.println(hm.get(i));
}

How to show multiline text in a table cell

You want to use the CSS white-space:pre applied to the appropriate <td>. To do this to all table cells, for example:

td { white-space:pre }

Alternatively, if you can change your markup, you can use a <pre> tag around your content. By default web browsers use their user-agent stylesheet to apply the same white-space:pre rule to this element.

The PRE element tells visual user agents that the enclosed text is "preformatted". When handling preformatted text, visual user agents:

  • May leave white space intact.
  • May render text with a fixed-pitch font.
  • May disable automatic word wrap.
  • Must not disable bidirectional processing.

Awaiting multiple Tasks with different results

Forward Warning

Just a quick headsup to those visiting this and other similar threads looking for a way to parallelize EntityFramework using async+await+task tool-set: The pattern shown here is sound, however, when it comes to the special snowflake of EF you will not achieve parallel execution unless and until you use a separate (new) db-context-instance inside each and every *Async() call involved.

This sort of thing is necessary due to inherent design limitations of ef-db-contexts which forbid running multiple queries in parallel in the same ef-db-context instance.


Capitalizing on the answers already given, this is the way to make sure that you collect all values even in the case that one or more of the tasks results in an exception:

  public async Task<string> Foobar() {
    async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
        return DoSomething(await a, await b, await c);
    }

    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        if (carTask.Status == TaskStatus.RanToCompletion //triple
            && catTask.Status == TaskStatus.RanToCompletion //cache
            && houseTask.Status == TaskStatus.RanToCompletion) { //hits
            return Task.FromResult(DoSomething(catTask.Result, carTask.Result, houseTask.Result)); //fast-track
        }

        cat = await catTask;
        car = await carTask;
        house = await houseTask;
        //or Task.AwaitAll(carTask, catTask, houseTask);
        //or await Task.WhenAll(carTask, catTask, houseTask);
        //it depends on how you like exception handling better

        return Awaited(catTask, carTask, houseTask);
   }
 }

An alternative implementation that has more or less the same performance characteristics could be:

 public async Task<string> Foobar() {
    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        cat = catTask.Status == TaskStatus.RanToCompletion ? catTask.Result : (await catTask);
        car = carTask.Status == TaskStatus.RanToCompletion ? carTask.Result : (await carTask);
        house = houseTask.Status == TaskStatus.RanToCompletion ? houseTask.Result : (await houseTask);

        return DoSomething(cat, car, house);
     }
 }

How do I center align horizontal <UL> menu?

From http://pmob.co.uk/pob/centred-float.htm:

The premise is simple and basically just involves a widthless float wrapper that is floated to the left and then shifted off screen to the left width position:relative; left:-50%. Next the nested inner element is reversed and a relative position of +50% is applied. This has the effect of placing the element dead in the center. Relative positioning maintains the flow and allows other content to flow underneath.

Code

_x000D_
_x000D_
#buttons{
    float:right;
    position:relative;
    left:-50%;
    text-align:left;
}
#buttons ul{
    list-style:none;
    position:relative;
    left:50%;
}

#buttons li{float:left;position:relative;}/* ie needs position:relative here*/

#buttons a{
    text-decoration:none;
    margin:10px;
    background:red;
    float:left;
    border:2px outset blue;
    color:#fff;
    padding:2px 5px;
    text-align:center;
    white-space:nowrap;
}
#buttons a:hover{ border:2px inset blue;color:red;background:#f2f2f2;}
#content{overflow:hidden}/* hide horizontal scrollbar*/
_x000D_
<div id="buttons">
    <ul>
        <li><a href="#">Button 1</a></li>
        <li><a href="#">Button 2's a bit longer</a></li>
        <li><a href="#">Butt 3</a></li>
        <li><a href="#">Button 4</a></li>
    </ul>
</div>
_x000D_
_x000D_
_x000D_

Algorithm to generate all possible permutations of a list?

Here is the code in Python to print all possible permutations of a list:

def next_perm(arr):
    # Find non-increasing suffix
    i = len(arr) - 1
    while i > 0 and arr[i - 1] >= arr[i]:
        i -= 1
    if i <= 0:
        return False

    # Find successor to pivot
    j = len(arr) - 1
    while arr[j] <= arr[i - 1]:
        j -= 1
    arr[i - 1], arr[j] = arr[j], arr[i - 1]

    # Reverse suffix
    arr[i : ] = arr[len(arr) - 1 : i - 1 : -1]
    print arr
    return True

def all_perm(arr):
    a = next_perm(arr)
    while a:
        a = next_perm(arr)
    arr = raw_input()
    arr.split(' ')
    arr = map(int, arr)
    arr.sort()
    print arr
    all_perm(arr)

I have used a lexicographic order algorithm to get all possible permutations, but a recursive algorithm is more efficient. You can find the code for recursive algorithm here: Python recursion permutations

HTML Table width in percentage, table rows separated equally

Yes, you will need to specify the width for each cell, otherwise they will try to be "intelligent" about it and divide the 100% between whichever cells think they need it most. Cells with more content will take up more width than those with less.

To make sure you get equal width for each cell you need to make it clear. Either do it as you already have, or use CSS.

table.className td { width: 25%; }