Programs & Examples On #Relational algebra

Relational Algebra is an offshoot of first-order logic and of the algebra of sets that deals with relations (sets of tuples). In Computer Science, Relational Algebra is commonly used when dealing with databases. Operators in Relational Algebra use relations as operands and produce a relation as a result.

Difference between a theta join, equijoin and natural join

Theta Join: When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.

Equi Join: When you make a query for join using equality operator only, then that join query comes under Equi join.

Example:

> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID;
> SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show:
 _________________________________________________
| Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID |
|          |            |           |             |

Note: Equi join is also a theta join!

Natural Join: a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.

Note: here, the join result has only one column for each pair of same named columns.

Example

 SELECT * FROM Emp NATURAL JOIN Dept
This will show:
 _______________________________
| DeptID | Emp.Name | Dept.Name |
|        |          |           |

What are projection and selection?

Exactly.

Projection means choosing which columns (or expressions) the query shall return.

Selection means which rows are to be returned.

if the query is

select a, b, c from foobar where x=3;

then "a, b, c" is the projection part, "where x=3" the selection part.

What is the difference between Select and Project Operations

Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.

Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.

See more : Relational Algebra and its operations

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

How to convert all tables in database to one collation?

This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).

#!/bin/bash

# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
CHARSET="$2"
COLL="$3"

[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql

echo "USE $DB; SHOW TABLES;" | mysql -s | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
    done
)

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

Adding blank spaces to layout

The previous answers didn't work in my case. However, creating an empty item in the menu does.

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
  ...
  <item />
  ...
</menu>

Update MySQL using HTML Form and PHP

Try it this way. Put the table name in quotes (``). beside put variable '".$xyz."'.

So your sql query will be like:

$sql = mysql_query("UPDATE `anstalld` SET mandag = "'.$mandag.'" WHERE namn =".$name)or die(mysql_error());

C# - Create SQL Server table programmatically

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommend
{
    class sqlcreateapp
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Table Created Successfully...");
                conn.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
            }
            Console.ReadKey();
        }
    }
}

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

Visual Studio 2010 shortcut to find classes and methods?

Visual Studio 2010 has the "Navigate To" command, which might be what you are looking for. The default keyboard shortcut is CTRL + ,. Here is an overview of some of the options for navigating in Visual Studio 2010.

Reactive forms - disabled attribute

Only who are using reactive forms : For native HTML elements [attr.disabled] will work but for material elements we need to dynamically disable the element.

this.form.get('controlname').disable();

Otherwise it will show in console warning message.

Git: "Corrupt loose object"

Create a backup and clone the repository into a fresh directory

cp -R foo foo-backup
git clone git@url:foo foo-new

(optional) If you are working on a different branch than master, switch it.

cd foo-new
git checkout -b branch-name origin/branch-name

Sync changes excluding the .git directory

rsync -aP --exclude=.git foo-backup/ foo-new

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Typical error on Windows because the default user directory is C:\user\<your_user>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error.

To solve it, just double the backslashes: C:\\user\\<\your_user>...

Create a custom callback in JavaScript

Try:

function LoadData (callback)
{
    // ... Process whatever data
    callback (loadedData, currentObject);
}

Functions are first class in JavaScript; you can just pass them around.

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

How to send email attachments?

Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.

Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.

Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.

I've only tried this on Python 2, but I think it should work fine on 3 as well:

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    """
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["[email protected]", "[email protected]"]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(a_file.read(), Name=basename)

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename
        msg.attach(part)

    email = smtplib.SMTP('your-smtp-host-name.com')
    email.sendmail(from_email, to_email, msg.as_string())

I hope this helps! :-)

Updates were rejected because the tip of your current branch is behind its remote counterpart

the tip of your current branch is behind its remote counterpart means that there have been changes on the remote branch that you don’t have locally. and git tells you import new changes from REMOTE and merge it with your code and then push it to remote.

You can use this command to force changes to server with local repo ().

git push -f origin master

with -f tag you will override Remote Brach code with your code.

How do I find the location of Python module sources?

Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.

You would have to download the source code to the python standard library to get at it.

List names of all tables in a SQL Server 2012 schema

SQL Server 2005, 2008, 2012 or 2014:

SELECT * FROM information_schema.tables WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA = 'dbo'

For more details: How do I get list of all tables in a database using TSQL?

Set Focus After Last Character in Text Box

Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

It uses setSelectionRange if supported, else has a solid fallback.

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

Then you can just do:

input.putCursorAtEnd();

ActiveModel::ForbiddenAttributesError when creating new user

Alternatively you can use the Protected Attributes gem, however this defeats the purpose of requiring strong params. However if you're upgrading an older app, Protected Attributes does provide an easy pathway to upgrade until such time that you can refactor the attr_accessible to strong params.

is there a post render callback for Angular JS directive?

None of the solutions worked for me accept from using a timeout. This is because I was using a template that was dynamically being created during the postLink.

Note however, there can be a timeout of '0' as the timeout adds the function being called to the browser's queue which will occur after the angular rendering engine as this is already in the queue.

Refer to this: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

how to setup ssh keys for jenkins to publish via ssh

You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.

Generating the SSH Key Pair

On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:

On the Target Server

On the target server, you will need to place the content of the public key (id_rsa.pub per the above article) into the .ssh/authorized_keys file under the home directory of the user which Jenkins will be using for deployment.

In Jenkins

Using "Publish over SSH" Plugin

Ref: https://plugins.jenkins.io/publish-over-ssh/

Visit: Jenkins > Manage Jenkins > Configure System > Publish over SSH

  • If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
  • Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
  • Copy and paste the contents of the private key (id_rsa per the above article) into the "Key" field
  • Under "SSH Servers", "Add" a new server configuration for your target server.

Using Stored Global Credentials

Visit: Jenkins > Credentials > System > Global credentials (unrestricted) > Add Credentials

  • Kind: "SSH Username with private key"
  • Scope: "Global"
  • ID: [CREAT A UNIQUE ID FOR THIS KEY]
  • Description: [optionally, enter a decription]
  • Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
  • Private Key: [select "Enter directly"]
  • Key: [paste the contents of the private key (id_rsa per the above article)]
  • Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]

Get the current first responder without using a private API

This is good candidate for recursion! No need to add a category to UIView.

Usage (from your view controller):

UIView *firstResponder = [self findFirstResponder:[self view]];

Code:

// This is a recursive function
- (UIView *)findFirstResponder:(UIView *)view {

    if ([view isFirstResponder]) return view; // Base case

    for (UIView *subView in [view subviews]) {
        if ([self findFirstResponder:subView]) return subView; // Recursion
    }
    return nil;
}

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

Create XML file using java

package com.server;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


import org.w3c.dom.*;

import com.gwtext.client.data.XmlReader;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;  

public class XmlServlet extends HttpServlet
{ 

  NodeList list;
  Connection con=null;
  Statement st=null;
  ResultSet rs = null;
  String xmlString ;
  BufferedWriter bw;
  String displayTo;
  String displayFrom;
  String addressto;
  String addressFrom;
  Date send;
  String Subject;
  String body;
  String category;
  Document doc1;
  public void doGet(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{

    System.out.print("on server");  

  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  System.out.print("on server");
  try
  {


    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    //creating a new instance of a DOM to build a DOM tree.
    doc1 = docBuilder.newDocument();
    new XmlServlet().createXmlTree(doc1);

    System.out.print("on server");

  }
  catch(Exception e)
  {
  System.out.println(e.toString());
  }

   }

  public void createXmlTree(Document doc) throws Exception {
  //This method creates an element node

    System.out.println("ruchipaliwal111");

    try
    {

      System.out.println("ruchi111");
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
      st = con.createStatement();

      rs = st.executeQuery("select * from data");


      Element root = doc.createElement("message");
      doc.appendChild(root);

        while(rs.next())
        {



       displayTo=rs.getString(1).toString();
       System.out.println(displayTo+"getdataname");

       displayFrom=rs.getString(2).toString();
       System.out.println(displayFrom +"getdataname");

         addressto=rs.getString(3).toString();
         System.out.println(addressto +"getdataname");

       addressFrom=rs.getString(4).toString();
       System.out.println(addressFrom +"getdataname");

       send=rs.getDate(5);
       System.out.println(send +"getdataname");

       Subject=rs.getString(6).toString();
       System.out.println(Subject +"getdataname");

       body=rs.getString(7).toString();
       System.out.println(body+"getdataname");

      category=rs.getString(8).toString();
       System.out.println(category +"getdataname");


       //adding a node after the last child node of ssthe specified node.


        Element element1 = doc.createElement("Header");
        root.appendChild(element1);


        Element child1 = doc.createElement("To");
        element1.appendChild(child1);

        child1.setAttribute("displayNameTo",displayTo);
        child1.setAttribute("addressTo",addressto);

        Element child2 = doc.createElement("From");
        element1.appendChild(child2);

        child2.setAttribute("displayNameFrom",displayFrom);
        child2.setAttribute("addressFrom",addressFrom);

        Element child3 = doc.createElement("Send");
        element1.appendChild(child3);

        Text text2 = doc.createTextNode(send.toString());
        child3.appendChild(text2);

        Element child4 = doc.createElement("Subject");
        element1.appendChild(child4);

        Text text3 = doc.createTextNode(Subject);
        child4.appendChild(text3);

        Element child5 = doc.createElement("category");
        element1.appendChild(child5);

        Text text44 = doc.createTextNode(category);
        child5.appendChild(text44);


        Element element2 = doc.createElement("Body");
        root.appendChild(element2);

        Text text1 = doc.createTextNode(body);
        element2.appendChild(text1);

       /*
        Element child1 = doc.createElement("name");
        root.appendChild(child1);
        Text text = doc.createTextNode(getdataname);
        child1.appendChild(text);
        Element element = doc.createElement("address");
        root.appendChild(element);
        Text text1 = doc.createTextNode( getdataaddress);
        element.appendChild(text1); 
     */
      } 






//TransformerFactory instance is used to create Transformer objects. 
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer();

  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");


  // create string from xml tree
  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  DOMSource source = new DOMSource(doc);
  transformer.transform(source, result);

  xmlString = sw.toString();


  File file = new File("./war/ds/newxml.xml");
  bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
  bw.write(xmlString);
   }

    catch(Exception e)
    {
      System.out.print("after while loop exception"+e.toString());
    }

  bw.flush();
  bw.close();
  System.out.println("successfully done.....");
  }
}

Setting Authorization Header of HttpClient

As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices :( ), I put here a link towards the answer I made on a similar question :

https://stackoverflow.com/a/40707446/717372

Some sources on how to use HttpClient the right way:

Concatenate two JSON objects

If you'd rather copy the properties:

var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };


function jsonConcat(o1, o2) {
 for (var key in o2) {
  o1[key] = o2[key];
 }
 return o1;
}

var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);

Output of above code is{ value1: '1', value2: '4', value3: '3' }

How can I add a vertical scrollbar to my div automatically?

You have to add max-height property.

_x000D_
_x000D_
.ScrollStyle_x000D_
{_x000D_
    max-height: 150px;_x000D_
    overflow-y: scroll;_x000D_
}
_x000D_
<div class="ScrollStyle">_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Deleting all files from a folder using PHP?

 <?
//delete all files from folder  & sub folders
function listFolderFiles($dir)
{
    $ffs = scandir($dir);
    echo '<ol>';
    foreach ($ffs as $ff) {
        if ($ff != '.' && $ff != '..') {
            if (file_exists("$dir/$ff")) {
                unlink("$dir/$ff");
            }
            echo '<li>' . $ff;
            if (is_dir($dir . '/' . $ff)) {
                listFolderFiles($dir . '/' . $ff);
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
$arr = array(
    "folder1",
    "folder2"
);
for ($x = 0; $x < count($arr); $x++) {
    $mm = $arr[$x];
    listFolderFiles($mm);
}
//end
?> 

Create a directly-executable cross-platform GUI app using Python

An alternative tool to py2exe is bbfreeze which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.

How to go to each directory and execute a command?

I don't get the point with the formating of the file, since you only want to iterate through folders... Are you looking for something like this?

cd parent
find . -type d | while read d; do
   ls $d/
done

How to print star pattern in JavaScript in a very simple manner?

_x000D_
_x000D_
            /** --------------_x000D_
_x000D_
                    *_x000D_
                   **_x000D_
                  ***_x000D_
                 ****_x000D_
                *****_x000D_
               ******_x000D_
              *******_x000D_
             ********_x000D_
            *********_x000D_
_x000D_
_x000D_
            ----------------*/_x000D_
_x000D_
            let y = 10;_x000D_
            let x = 10;_x000D_
_x000D_
            let str = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i + j >= y){_x000D_
                        str = str.concat("*");_x000D_
                    }else{_x000D_
                        str = str.concat(" ")_x000D_
                    }_x000D_
                }_x000D_
                str = str.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str)_x000D_
_x000D_
_x000D_
            /**________________________x000D_
_x000D_
_x000D_
_x000D_
            *********_x000D_
             ********_x000D_
              *******_x000D_
               ******_x000D_
                *****_x000D_
                 ****_x000D_
                  ***_x000D_
                   **_x000D_
                    *_x000D_
_x000D_
_x000D_
             _______________________*/_x000D_
_x000D_
            let str2 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i <= j ){_x000D_
                        str2 = str2.concat("*");_x000D_
                    }else{_x000D_
                        str2 = str2.concat(" ")_x000D_
                    }_x000D_
                }_x000D_
                str2 = str2.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str2)_x000D_
_x000D_
_x000D_
            /**----------------------_x000D_
_x000D_
_x000D_
            *_x000D_
            **_x000D_
            ***_x000D_
            ****_x000D_
            *****_x000D_
            ******_x000D_
            *******_x000D_
            ********_x000D_
_x000D_
_x000D_
             -------------------------*/_x000D_
_x000D_
_x000D_
            let str3 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i >= j ){_x000D_
                        str3 = str3.concat("*");_x000D_
                    }_x000D_
                }_x000D_
                str3 = str3.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str3)_x000D_
_x000D_
            /**-------------------------_x000D_
_x000D_
_x000D_
             *********_x000D_
             ********_x000D_
             *******_x000D_
             ******_x000D_
             *****_x000D_
             ****_x000D_
             ***_x000D_
             **_x000D_
             *_x000D_
_x000D_
             ---------------------------*/_x000D_
            let str4 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if( j >= i ){_x000D_
                        str4 = str4.concat("*");_x000D_
                    }_x000D_
                }_x000D_
                str4 = str4.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str4)_x000D_
_x000D_
            /**--------------------_x000D_
             Diamond of Asterisks_x000D_
_x000D_
                 *_x000D_
                ***_x000D_
               *****_x000D_
              *******_x000D_
             *********_x000D_
              *******_x000D_
               *****_x000D_
                ***_x000D_
                 *_x000D_
_x000D_
_x000D_
             ---------------------*/_x000D_
_x000D_
            let str5 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i <= y / 2 && j >= (y / 2) - (i - 1) && j <= (y / 2) + (i - 1) ){_x000D_
                        str5 = str5.concat("*");_x000D_
                    }else if(i >= y / 2_x000D_
                      && j > ((y / 2) -  i) * (-1)_x000D_
                      && j < (y - ((y / 2) -  i) * (-1))){_x000D_
                        str5 = str5.concat("*");_x000D_
                    }_x000D_
                    else {_x000D_
                        str5 = str5.concat(" ");_x000D_
                    }_x000D_
                }_x000D_
                str5 = str5.concat("\n");_x000D_
            }_x000D_
_x000D_
            console.log(str5)
_x000D_
_x000D_
_x000D_

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

Call parent method from child class c#

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

In child add:

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

In parent add:

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

Reading NFC Tags with iPhone 6 / iOS 8

The only information currently available is that Apple Pay will be available in ios8, but that doesn't shed any light on whether RFID tags or rather NFC tags specifically will be able to be detected/read.

IMO it would be a shortsighted move not to allow that possibility, but really the money is in Apple Pay, not necessarily in allowing developers access to those features - we've seen it before with tethering, Bluetooth SPP, and diminished access to certain functions.

...but then again, it's been about 5 hours since the first announcement.

Using Environment Variables with Vue.js

In vue-cli version 3:

There are the three options for .env files: Either you can use .env or:

  • .env.test
  • .env.development
  • .env.production

You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

How do I check if an element is hidden in jQuery?

Try

content.style.display != 'none'

_x000D_
_x000D_
function toggle() {_x000D_
  $(content).toggle();_x000D_
  let visible= content.style.display != 'none'_x000D_
  console.log('visible:', visible);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button onclick="toggle()">Show/hide</button>_x000D_
<div id="content">ABC</div>
_x000D_
_x000D_
_x000D_

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

How do I upload a file with metadata using a REST web service?

If your file and its metadata creating one resource, its perfectly fine to upload them both in one request. Sample request would be :

POST https://target.com/myresources/resourcename HTTP/1.1

Accept: application/json

Content-Type: multipart/form-data; 

boundary=-----------------------------28947758029299

Host: target.com

-------------------------------28947758029299

Content-Disposition: form-data; name="application/json"

{"markers": [
        {
            "point":new GLatLng(40.266044,-74.718479), 
            "homeTeam":"Lawrence Library",
            "awayTeam":"LUGip",
            "markerImage":"images/red.png",
            "information": "Linux users group meets second Wednesday of each month.",
            "fixture":"Wednesday 7pm",
            "capacity":"",
            "previousScore":""
        },
        {
            "point":new GLatLng(40.211600,-74.695702),
            "homeTeam":"Hamilton Library",
            "awayTeam":"LUGip HW SIG",
            "markerImage":"images/white.png",
            "information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.",
            "fixture":"Tuesday 7pm",
            "capacity":"",
            "tv":""
        },
        {
            "point":new GLatLng(40.294535,-74.682012),
            "homeTeam":"Applebees",
            "awayTeam":"After LUPip Mtg Spot",
            "markerImage":"images/newcastle.png",
            "information": "Some of us go there after the main LUGip meeting, drink brews, and talk.",
            "fixture":"Wednesday whenever",
            "capacity":"2 to 4 pints",
            "tv":""
        },
] }

-------------------------------28947758029299

Content-Disposition: form-data; name="name"; filename="myfilename.pdf"

Content-Type: application/octet-stream

%PDF-1.4
%
2 0 obj
<</Length 57/Filter/FlateDecode>>stream
x+r
26S00SI2P0Qn
F
!i\
)%[email protected]
[
endstream
endobj
4 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R>>>>/Contents 2 0 R/Parent 3 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
3 0 obj
<</Type/Pages/Count 1/Kids[4 0 R]>>
endobj
5 0 obj
<</Type/Catalog/Pages 3 0 R>>
endobj
6 0 obj
<</Producer(iTextSharp 5.5.11 2000-2017 iText Group NV \(AGPL-version\))/CreationDate(D:20170630120636+02'00')/ModDate(D:20170630120636+02'00')>>
endobj
xref
0 7
0000000000 65535 f 
0000000250 00000 n 
0000000015 00000 n 
0000000338 00000 n 
0000000138 00000 n 
0000000389 00000 n 
0000000434 00000 n 
trailer
<</Size 7/Root 5 0 R/Info 6 0 R/ID [<c7c34272c2e618698de73f4e1a65a1b5><c7c34272c2e618698de73f4e1a65a1b5>]>>
%iText-5.5.11
startxref
597
%%EOF

-------------------------------28947758029299--

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

Change directory in Node.js command prompt

.help will show you all the options. Do .exit in this case

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

For those, who wonder how it goes in VS.

MSVC 2015 Update 1, cl.exe version 19.00.24215.1:

#include <iostream>

template<typename X, typename Y>
struct A
{
  template<typename Z>
  static void f()
  {
    std::cout << "from A::f():" << std::endl
      << __FUNCTION__ << std::endl
      << __func__ << std::endl
      << __FUNCSIG__ << std::endl;
  }
};

void main()
{
  std::cout << "from main():" << std::endl
    << __FUNCTION__ << std::endl
    << __func__ << std::endl
    << __FUNCSIG__ << std::endl << std::endl;

  A<int, float>::f<bool>();
}

output:

from main():
main
main
int __cdecl main(void)

from A::f():
A<int,float>::f
f
void __cdecl A<int,float>::f<bool>(void)

Using of __PRETTY_FUNCTION__ triggers undeclared identifier error, as expected.

How to obtain Telegram chat_id for a specific user?

You can just share the contact with your bot and, via /getUpdates, you get the "contact" object

How do I save a String to a text file using Java?

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}

Reading from text file until EOF repeats last line

The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.

What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.

I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.

  • 0

So add a prime read and move the loop's read to the end:

int x;

iFile >> x; // prime read here
while (!iFile.eof()) {
    cerr << x << endl;
    iFile >> x;
}

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

How can I get the actual video URL of a YouTube live stream?

Yes this is possible Since the question is update, this solution can only gives you the embed url not the HLS url, check @JAL answer. with the ressource search.list and the parameters:

* part: id
* channelId: UCURGpU4lj3dat246rysrWsw
* eventType: live
* type: video

Request :

GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCURGpU4lj3dat246rysrWsw&eventType=live&type=video&key={YOUR_API_KEY}

Result:

 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/enc3-yCp8APGcoiU_KH-mSKr4Yo\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "WVZpCdHq3Qg"
   }
  },

Then get the videoID value WVZpCdHq3Qg for example and add the value to this url:

https://www.youtube.com/embed/ + videoID
https://www.youtube.com/watch?v= + videoID

Cross compile Go on OSX?

Thanks to kind and patient help from golang-nuts, recipe is the following:

1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go thus to compile a compiler you need to issue make utility. Before doing this you need to know some caveats.

There is an issue about CGO library when cross compiling so it is needed to disable CGO library.

Compiling is done by changing location to source dir, since compiling has to be done in that folder

cd /usr/local/go/src

then compile the Go compiler:

sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean

You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.

If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.

2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:

GOOS=windows GOARCH=386 go build -o appname.exe appname.go

GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go

Change the GOOS and GOARCH to targets you wish to build.

If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.

Python unexpected EOF while parsing

I'm using the follow code to get Python 2 and 3 compatibility

if sys.version_info < (3, 0):
    input = raw_input

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

Why is a "GRANT USAGE" created the first time I grant a user privileges?

I was trying to find the meaning of GRANT USAGE on *.* TO and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password will be granted when you create the user with the following command (CREATE):

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; 

When you grant privilege with GRANT, new privilege s will be added on top of it.

How do I convert ticks to minutes?

TimeSpan.FromTicks(28000000000).TotalMinutes;

Setting a backgroundImage With React Inline Styles

Sometimes your SVG will be inlined by React so you need quotes around it:

     backgroundImage: `url("${Background}")`

otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.

How to center the elements in ConstraintLayout

you can use layout_constraintCircle for center view inside ConstraintLayout.

<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/mparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageButton
            android:id="@+id/btn_settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/ic_home_black_24dp"
            app:layout_constraintCircle="@id/mparent"
            app:layout_constraintCircleRadius="0dp"
            />
    </android.support.constraint.ConstraintLayout>

with constraintCircle to parent and zero radius you can make your view be center of parent.

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you have a new database and you make a fresh clean import, the problem may come from inserting data that contains a '0' incrementation and this would transform to '1' with AUTO_INCREMENT and cause this error.

My solution was to use in the sql import file.

SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';

How to link html pages in same or different folders?

For ASP.NET, this worked for me on development and deployment:

<a runat="server" href="~/Subfolder/TargetPage">TargetPage</a>

Using runat="server" and the href="~/" are the keys for going to the root.

WPF ListView - detect when selected item is clicked

I would also suggest deselecting an item after it has been clicked and use the MouseDoubleClick event

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    try {
        //Do your stuff here
        listBox.SelectedItem = null;
        listBox.SelectedIndex = -1;
    } catch (Exception ex) {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

How to remove item from list in C#?

Short answer:
Remove (from list results)

results.RemoveAll(r => r.ID == 2); will remove the item with ID 2 in results (in place).

Filter (without removing from original list results):

var filtered = result.Where(f => f.ID != 2); returns all items except the one with ID 2

Detailed answer:

I think .RemoveAll() is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.

If you have:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

and assigned some values to results as follows:

var results = new List<myClass> {
    new myClass { ID=1, FirstName="Bill", LastName="Smith" },   // results[0]
    new myClass { ID=2, FirstName="John", LastName="Wilson" },  // results[1]
    new myClass { ID=3, FirstName="Doug", LastName="Berg" },    // results[2]
    new myClass { ID=4, FirstName="Bill", LastName="Wilson" }   // results[3]
};

Then you can define a list of IDs to remove:

var removeList = new List<int>() { 2, 3 };

And simply use this to remove them:

results.RemoveAll(r => removeList.Any(a => a==r.ID));

It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList. Note that this happens in place, so there is no additional assigment required.

Of course, you can also use it on single items like:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.

A last thing to mention is that lists have an indexer, that is, they can also be accessed like a dynamic array, i.e. results[3] will give you the 4th element in the results list (because the first element has the index 0, the 2nd has index 1 etc).

So if you want to remove all entries where the first name is the same as in the 4th element of the results list, you can simply do it this way:

results.RemoveAll(r => results[3].FirstName == r.FirstName);

Note that afterwards, only John and Doug will remain in the list, Bill is removed (the first and last element in the example). Important is that the list will shrink automatically, so it has only 2 elements left - and hence the largest allowed index after executing RemoveAll in this example is 1
(which is results.Count() - 1).

Some Trivia: You can use this knowledge and create a local function

void myRemove()  { var last = results.Count() - 1; 
                   results.RemoveAll(r => results[last].FirstName == r.FirstName); }

What do you think will happen, if you call this function twice? Like

myRemove(); myRemove(); 

The first call will remove Bill at the first and last position, the second call will remove Doug and only John Wilson remains in the list.


DotNetFiddle: Run the demo

Note: Since C# Version 8, you can as well write results[^1] instead of var last = results.Count() - 1; and results[last]:

void myRemove() { results.RemoveAll(r => results[^1].FirstName == r.FirstName); }

So you would not need the local variable last anymore (see indices and ranges. For a list of all the new features in C#, look here).

How to know the size of the string in bytes?

System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);

Or

System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Python list / sublist selection -1 weirdness

I get consistent behaviour for both instances:

>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]

Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.

In other words, [0:10] doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).

Label encoding across multiple columns in scikit-learn

this does not directly answer your question (for which Naputipulu Jon and PriceHardman have fantastic replies)

However, for the purpose of a few classification tasks etc. you could use

pandas.get_dummies(input_df) 

this can input dataframe with categorical data and return a dataframe with binary values. variable values are encoded into column names in the resulting dataframe. more

linux shell script: split string, put them in an array then loop through them

sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
    echo ${a%%;*}
    a=${a#*;}
done

Git - deleted some files locally, how do I get them from a remote repository

Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:

 $ git reset <commit #>

 $ git checkout <file/path>

I hope this was helpful!!

How to use LINQ to select object with minimum or maximum property value

Solution with no extra packages:

var min = lst.OrderBy(i => i.StartDate).FirstOrDefault();
var max = lst.OrderBy(i => i.StartDate).LastOrDefault();

also you can wrap it into extension:

public static class LinqExtensions
{
    public static T MinBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
    {
        return source.OrderBy(propSelector).FirstOrDefault();
    }

    public static T MaxBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
    {
        return source.OrderBy(propSelector).LastOrDefault();
    }
}

and in this case:

var min = lst.MinBy(i => i.StartDate);
var max = lst.MaxBy(i => i.StartDate);

By the way... O(n^2) is not the best solution. Paul Betts gave fatster solution than my. But my is still LINQ solution and it's more simple and more short than other solutions here.

Unable to launch the IIS Express Web server

For a 2021 Solution in dotnet core, you can fix this error by right-clicking the project in Solution Explorer, and choosing 'Edit Project File'.

On the Debug Tab, at the bottom, you can directly configure the desired port and whether to use SSL or not.

enter image description here

Changes here need to be saved with Control+S. Once that's done, you can launch the project and confirm it fixed your issue, no having to delete IISFolders or anything else suggested here.

mysql server port number

default port of mysql is 3306

default pot of sql server is 1433

How to search in array of object in mongodb

Use $elemMatch to find the array of particular object

db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />
</sectionGroup>

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

What is the iPad user agent?

Mine says:

Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had a similar issue using the JAXB reference implementation and JBoss AS 7.1. I was able to write an integration test that confirmed JAXB worked outside of the JBoss environment (suggesting the problem might be the class loader in JBoss).

This is the code that was giving the error (i.e. not working):

private static final JAXBContext JC;

static {
    try {
        JC = JAXBContext.newInstance("org.foo.bar");
    } catch (Exception exp) {
        throw new RuntimeException(exp);
    }
}

and this is the code that worked (ValueSet is one of the classes marshaled from my XML).

private static final JAXBContext JC;

static {
    try {
        ClassLoader classLoader = ValueSet.class.getClassLoader();
        JC = JAXBContext.newInstance("org.foo.bar", classLoader);
    } catch (Exception exp) {
        throw new RuntimeException(exp);
    }
}

In some cases I got the Class nor any of its super class is known to this context. In other cases I also got an exception of org.foo.bar.ValueSet cannot be cast to org.foo.bar.ValueSet (similar to the issue described here: ClassCastException when casting to the same class).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

calling a java servlet from javascript

The code here will use AJAX to print text to an HTML5 document dynamically (Ajax code is similar to book Internet & WWW (Deitel)):

Javascript code:

var asyncRequest;    
function start(){
    try
    {
        asyncRequest = new XMLHttpRequest();
        asyncRequest.addEventListener("readystatechange", stateChange, false);
        asyncRequest.open('GET', '/Test', true);    //   /Test is url to Servlet!
        asyncRequest.send(null);
    }
    catch(exception)
   {
    alert("Request failed");
   }
}

function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
    {
    var text = document.getElementById("text");         //  text is an id of a 
    text.innerHTML = asyncRequest.responseText;         //  div in HTML document
    }
}

window.addEventListener("load", start(), false);

Servlet java code:

public class Test extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException{
        resp.setContentType("text/plain");
        resp.getWriter().println("Servlet wrote this! (Test.java)");
    }
}

HTML document

 <div id = "text"></div>

EDIT

I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.

How to "crop" a rectangular image into a square with CSS?

Using background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

Setting max-height for table cell contents

We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.

We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.

Jquery to change form action

Try this:

$('#button1').click(function(){
   $('#formId').attr('action', 'page1');
});


$('#button2').click(function(){
   $('#formId').attr('action', 'page2');
});

How to add images in select list?

I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.

Worket well for me. Hope it can help someone else.

Object passed as parameter to another class, by value or reference?

Assuming someTestObj is a class and not a struct, the object is passed by reference, which means that both obj and someTestObj refer to the same object. E.g. changing name in one will change it in the other. However, unlike if you passed it using the ref keyword, setting obj = somethingElse will not change someTestObj.

Reload parent window from child window

  top.frames.location.reload(false);

iPhone - Get Position of UIView within entire UIWindow

Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)
    }
}

Select a random sample of results from a query result

This in not a perfect answer but will get much better performance.

SELECT  *
FROM    (
    SELECT  *
    FROM    mytable sample (0.01)
    ORDER BY
            dbms_random.value
    )
WHERE rownum <= 1000

Sample will give you a percent of your actual table, if you really wanted a 1000 rows you would need to adjust that number. More often I just need an arbitrary number of rows anyway so I don't limit my results. On my database with 2 million rows I get 2 seconds vs 60 seconds.

select * from mytable sample (0.01)

mysqli or PDO - what are the pros and cons?

There's one thing to keep in mind.

Mysqli does not support fetch_assoc() function which would return the columns with keys representing column names. Of course it's possible to write your own function to do that, it's not even very long, but I had really hard time writing it (for non-believers: if it seems easy to you, try it on your own some time and don't cheat :) )

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

CSS selector for first element with class

You could use nth-of-type(1) but be sure that site doesn't need to support IE7 etc, if this is the case use jQuery to add body class then find element via IE7 body class then the element name, then add in the nth-child styling to it.

javascript - Create Simple Dynamic Array

With ES2015, this can be achieved concisely in a single expression using the Array.from method like so:

Array.from({ length: 10 }, (_, idx) => `${++idx}`)

The first argument to from is an array like object that provides a length property. The second argument is a map function that allows us to replace the default undefined values with their adjusted index values as you requested. Checkout the specification here

Calling functions in a DLL from C++

You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)

In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.

For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.

What is the equivalent of Java's System.out.println() in Javascript?

console.log().

Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.

Git: Find the most recent common ancestor of two branches

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

SQL Server Case Statement when IS NULL

In this situation you can use ISNULL() function instead of CASE expression

ISNULL(B.[STAT], C.[EVENT DATE]+10) AS [DATE]

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Android: Unable to add window. Permission denied for this window type

try this code working perfectly

int layout_parms;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 

    {  
         layout_parms = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;

    }

     else {

            layout_parms = WindowManager.LayoutParams.TYPE_PHONE;

    }

    yourparams = new WindowManager.LayoutParams(       
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            layout_parms,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

How to compare times in Python?

Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.

d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second

I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.

Set inputType for an EditText Programmatically?

To unhide password:

editText.setInputType(
      InputType.TYPE_CLASS_TEXT|
      InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);

To hide password again:

editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

Show ImageView programmatically

If you add to RelativeLayout, don't forget to set imageView's position. For instance:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
ImageView imageView = new ImageView(this); // initialize ImageView
imageView.setLayoutParams(lp);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.photo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.addView(imageView);

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

Missing Maven dependencies in Eclipse project

the whole project looked weird in eclipse, maven dependencies folder were missing, it showed some types as unknown, but I was able to build it successfully in maven. What fixed my issue was adding gen folder to source path on project build path.

Probably this is similar to this Android /FBReaderJ/gen already exists but is not a source folder. Convert to a source folder or rename it

How do I make a splash screen?

Create a Activity, let us Activity named 'A', then create a xml file called myscreen.xml, in that set a the splash screen image as background, and then use count down timer to navigate from one Activtity to another. To know how to use Count Down timer see my answer in this question TimerTask in Android?

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How to create a multi line body in C# System.Net.Mail.MailMessage

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

How to skip a iteration/loop in while-loop

While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.

What is the use of rt.jar file in java?

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I've just had the same issue but using sourcetree on windows Same steps for normal GIT on Windows as well. Following the following steps I was able to solve this issue.

  1. Obtain the server certificate tree This can be done using chrome. Navigate to be server address. Click on the padlock icon and view the certificates. Export all of the certificate chain as base64 encoded files (PEM) format.
  2. Add the certificates to the trust chain of your GIT trust config file Run "git config --list". find the "http.sslcainfo" configuration this shows where the certificate trust file is located. Copy all the certificates into the trust chain file including the "- -BEGIN- -" and the "- -END- -".
  3. Make sure you add the entire certificate Chain to the certificates file

This should solve your issue with the self-signed certificates and using GIT.

I tried using the "http.sslcapath" configuration but this did not work. Also if i did not include the whole chain in the certificates file then this would also fail. If anyone has pointers on these please let me know as the above has to be repeated for a new install.

If this is the system GIT then you can use the options in TOOLS -> options GIt tab to use the system GIT and this then solves the issue in sourcetree as well.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

What does the symbol \0 mean in a string-literal?

What is the length of str array, and with how much 0s it is ending?

Let's find out:

int main() {
  char str[] = "Hello\0";
  int length = sizeof str / sizeof str[0];
  // "sizeof array" is the bytes for the whole array (must use a real array, not
  // a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
  // to get the number of items in the array
  printf("array length: %d\n", length);
  printf("last 3 bytes: %02x %02x %02x\n",
         str[length - 3], str[length - 2], str[length - 1]);
  return 0;
}

Vue.js get selected option on @change

The changed value will be in event.target.value

_x000D_
_x000D_
const app = new Vue({_x000D_
  el: "#app",_x000D_
  data: function() {_x000D_
    return {_x000D_
      message: "Vue"_x000D_
    }_x000D_
  },_x000D_
  methods: {_x000D_
    onChange(event) {_x000D_
      console.log(event.target.value);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <select name="LeaveType" @change="onChange" class="form-control">_x000D_
   <option value="1">Annual Leave/ Off-Day</option>_x000D_
   <option value="2">On Demand Leave</option>_x000D_
</select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Give all permissions to a user on a PostgreSQL database

GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user;

How to remove last n characters from every element in the R vector

Here is an example of what I would do. I hope it's what you're looking for.

char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)

a should now contain:

  data data2
1 foo_ 1
2 bar_ 2
3   ap 3
4    b 4

how to return index of a sorted list?

You can use the python sorting functions' key parameter to sort the index array instead.

>>> s = [2, 3, 1, 4, 5, 3]
>>> sorted(range(len(s)), key=lambda k: s[k])
[2, 0, 1, 5, 3, 4]
>>> 

Recursively look for files with a specific extension

  1. There's a { missing after browsefolders ()
  2. All $in should be $suffix
  3. The line with cut gets you only the middle part of front.middle.extension. You should read up your shell manual on ${varname%%pattern} and friends.

I assume you do this as an exercise in shell scripting, otherwise the find solution already proposed is the way to go.

To check for proper shell syntax, without running a script, use sh -n scriptname.

Is there a git-merge --dry-run option?

As noted previously, pass in the --no-commit flag, but to avoid a fast-forward commit, also pass in --no-ff, like so:

$ git merge --no-commit --no-ff $BRANCH

To examine the staged changes:

$ git diff --cached

And you can undo the merge, even if it is a fast-forward merge:

$ git merge --abort

Filter LogCat to get only the messages from My Application in Android?

If you are using Eclipse, press the green + sign in the logCat window below and put your package name (com.example.yourappname) in the by Application Name box. Also, choose any name comfortable to you in Filter Name box and click ok. You will see only messages related to your application when the filter you just added is chosen from the left pane in the logCat.

Changing the text on a label

You can also define a textvariable when creating the Label, and change the textvariable to update the text in the label. Here's an example:

labelText = Stringvar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()

def updateDepositLabel(txt) # you may have to use *args in some cases
    labelText.set(txt)

There's no need to update the text in depositLabel manually. Tk does that for you.

how to enable sqlite3 for php?

The SQLite3 PDO driver is named SQLite, not SQLite3, so you can do:

new SQLite("database");

For a SQLite2 database:

new SQLite2("database");

How do I check if a given Python string is a substring of another one?

Try using in like this:

>>> x = 'hello'
>>> y = 'll'
>>> y in x
True

What throws an IOException in Java?

In general, I/O means Input or Output. Those methods throw the IOException whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.

Here are some cases which result in IOException.

  • Reading from a closed inputstream
  • Try to access a file on the Internet without a network connection

Is __init__.py not required for packages in Python 3.3+

Overview

@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py file. This is called a namespace package in contrast to a regular package which does have an __init__.py file (empty or not empty).

However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py files regardless.

Namespace package use case

To demonstrate the difference between the two types of python packages, lets look at the following example:

google_pubsub/              <- Package 1
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            pubsub/         <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                foo.py

google_storage/             <- Package 2
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            storage/        <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                bar.py

google_pubsub and google_storage are separate packages but they share the same namespace google/cloud. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/ and cloud/. This should be the only use case for creating namespace packages, otherwise, there is no need for it.

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub and google_storage, the Python interpreter will be able to find them.

This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path with an __init__.py file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py traps to watch out for.

Summary

  • Only skip __init__.py files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.
  • Keep on adding empty __init__py to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy and pytest require empty __init__.py files to interpret the code structure accordingly. This can lead to weird errors if not done with care.

Resources

My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:

How to set focus on an input field after rendering?

Ben Carp solution in typescript

React 16.8 + Functional component - useFocus hook

export const useFocus = (): [React.MutableRefObject<HTMLInputElement>, VoidFunction] => {
  const htmlElRef = React.useRef<HTMLInputElement>(null);
  const setFocus = React.useCallback(() => {
    if (htmlElRef.current) htmlElRef.current.focus();
  }, [htmlElRef]);

  return React.useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};

Simple way to calculate median with MySQL

Knowing exact row count you can use this query:

SELECT <value> AS VAL FROM <table> ORDER BY VAL LIMIT 1 OFFSET <half>

Where <half> = ceiling(<size> / 2.0) - 1

jQuery Date Picker - disable past dates

Use the "minDate" option to restrict the earliest allowed date. The value "0" means today (0 days from today):

    $(document).ready(function () {
        $("#txtdate").datepicker({
            minDate: 0,
            // ...
        });
    });

Docs here: http://api.jqueryui.com/datepicker/#option-minDate

Can I use a case/switch statement with two variables?

Yes you can also do:

    switch (true) {

     case (var1 === true && var2 === true) :
       //do something
       break;
     case (var1 === false && var2 === false) :
       //do something
       break;

      default:

    }

This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.

WARNING: Can't verify CSRF token authenticity rails

The best way to do this is actually just use <%= form_authenticity_token.to_s %> to print out the token directly in your rails code. You dont need to use javascript to search the dom for the csrf token as other posts mention. just add the headers option as below;

$.ajax({
  type: 'post',
  data: $(this).sortable('serialize'),
  headers: {
    'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
  },
  complete: function(request){},
  url: "<%= sort_widget_images_path(@widget) %>"
})

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

How to navigate a few folders up?

You can use ..\path to go one level up, ..\..\path to go two levels up from path.

You can use Path class too.

C# Path class

JPA Native Query select and cast object

The accepted answer is incorrect.

createNativeQuery will always return a Query:

public Query createNativeQuery(String sqlString, Class resultClass);

Calling getResultList on a Query returns List:

List getResultList()

When assigning (or casting) to List<MyEntity>, an unchecked assignment warning is produced.

Whereas, createQuery will return a TypedQuery:

public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

Calling getResultList on a TypedQuery returns List<X>.

List<X> getResultList();

This is properly typed and will not give a warning.

With createNativeQuery, using ObjectMapper seems to be the only way to get rid of the warning. Personally, I choose to suppress the warning, as I see this as a deficiency in the library and not something I should have to worry about.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

How can I take an UIImage and give it a black border?

You could manipulate the image itself, but a much better way is to simply add a UIView that contains the UIImageView, and change the background to black. Then set the size of that container view to a little bit larger than the UIImageView.

Delete the first three rows of a dataframe in pandas

df = df.iloc[n:]

n drops the first n rows.

Copy all values in a column to a new column in a pandas dataframe

Here is your dataframe:

import pandas as pd
df = pd.DataFrame({
    'A': ['a.1', 'a.2', 'a.3'],
    'B': ['b.1', 'b.2', 'b.3'],
    'C': ['c.1', 'c.2', 'c.3']})

Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.

It says:

A DataFrame can be enlarged on either axis via .loc.

So what you need to do is simply one of these two:

df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']

How to set text size of textview dynamically for different screens

You should use the resource folders such as

values-ldpi
values-mdpi
values-hdpi

And write the text size in 'dimensions.xml' file for each range.

And in the java code you can set the text size with

textView.setTextSize(getResources().getDimension(R.dimen.textsize));

Sample dimensions.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="textsize">15sp</dimen>
</resources>

How to add a linked source folder in Android Studio?

While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?

Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7

How to change TextField's height and width?

use contentPadding, it will reduce the textbox or dropdown list height

InputDecorator(
                  decoration: InputDecoration(
                      errorStyle: TextStyle(
                          color: Colors.redAccent, fontSize: 16.0),
                      hintText: 'Please select expense',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(1.0),
                      ),
                      contentPadding: EdgeInsets.all(8)),//Add this edge option
                  child: DropdownButton(
                    isExpanded: true,
                    isDense: true,
                    itemHeight: 50.0,

                    hint: Text(
                        'Please choose a location'), // Not necessary for Option 1
                    value: _selectedLocation,
                    onChanged: (newValue) {
                      setState(() {
                        _selectedLocation = newValue;
                      });
                    },
                    items: citys.map((location) {
                      return DropdownMenuItem(
                        child: new Text(location.name),
                        value: location.id,
                      );
                    }).toList(),
                  ),
                ),

No module named serial

it may be very old post, but I would like to share my experience. I had the same issue when I used Pycharm and I installed the package from Project Interpreter page in the Project Settings/Preferences... That fixed the issue, please check below link: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html?_ga=2.41088674.1813230270.1594526819-1842497340.1594080707

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

How to deal with persistent storage (e.g. databases) in Docker

There are several levels of managing persistent data, depending on your needs:

  • Store it on your host
    • Use the flag -v host-path:container-path to persist container directory data to a host directory.
    • Backups/restores happen by running a backup/restore container (such as tutumcloud/dockup) mounted to the same directory.
  • Create a data container and mount its volumes to your application container
    • Create a container that exports a data volume, use --volumes-from to mount that data into your application container.
    • Backup/restore the same as the above solution.
  • Use a Docker volume plugin that backs an external/third-party service
    • Docker volume plugins allow your datasource to come from anywhere - NFS, AWS (S3, EFS, and EBS)
    • Depending on the plugin/service, you can attach single or multiple containers to a single volume.
    • Depending on the service, backups/restores may be automated for you.
    • While this can be cumbersome to do manually, some orchestration solutions - such as Rancher - have it baked in and simple to use.
    • Convoy is the easiest solution for doing this manually.

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

What's the most efficient way to test two integer ranges for overlap?

I suppose the question was about the fastest, not the shortest code. The fastest version have to avoid branches, so we can write something like this:

for simple case:

static inline bool check_ov1(int x1, int x2, int y1, int y2){
    // insetead of x1 < y2 && y1 < x2
    return (bool)(((unsigned int)((y1-x2)&(x1-y2))) >> (sizeof(int)*8-1));
};

or, for this case:

static inline bool check_ov2(int x1, int x2, int y1, int y2){
    // insetead of x1 <= y2 && y1 <= x2
    return (bool)((((unsigned int)((x2-y1)|(y2-x1))) >> (sizeof(int)*8-1))^1);
};

How to set Linux environment variables with Ansible

For persistently setting environment variables, you can use one of the existing roles over at Ansible Galaxy. I recommend weareinteractive.environment.

Using ansible-galaxy:

$ ansible-galaxy install weareinteractive.environment

Using requirements.yml:

- src: franklinkim.environment

Then in your playbook:

- hosts: all
  sudo: yes
  roles:
    - role: franklinkim.environment
      environment_config:
        NODE_ENV: staging
        DATABASE_NAME: staging

Reading data from XML

Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.

check null,empty or undefined angularjs

if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){

console.log("test is not defined");
}
else{
console.log("test is defined ",$scope.test); 
}

How to use hex() without 0x in Python?

>>> format(3735928559, 'x')
'deadbeef'

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

For what it's worth, I had the issue as well in IE11:

  • I was not in Enterprise mode.
  • The "Display intranet sites in Compatibility View" was checked.
  • I had all the <!DOCTYPE html> and IE=Edge settings mentioned in the question
  • The meta header was indeed the 1st element in the <head> element

After a while, I found out that:

  • the User Agent header sent to the server was IE7 but...
  • the JavaScript value was IE11!

HTTP Header:

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E) but

JavaScript:

window.navigator.userAgent === 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'

So I ended up doing the check on the client side.

And BTW, meanwhile, checking the user agent is no longer recommended. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent (but there might be a good case)

ImportError: Couldn't import Django

The problem is related to this error: Execution Policy Change

Start virtualenv by running the following command:

Command Line C: \ Users \ Name \ yourdjangofilesname > myvenv \ Scripts \ activate

NOTE: On Windows 10, you may receive an error by Windows PowerShell that the implementation of these scenarios is disabled on this system. In this case, open another Windows PowerShell with the "Run as Administrator" option. After that, try typing the following commands before starting your virtual environment:

C:\WINDOWS\system32> set-executionpolicy remotesigned

Execution Policy Change: The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at http://go.microsoft.com/fwlink/?LinkID=135170.

Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A

After selection Y(es), close the Powershell admin window, and then go back to the Powershell Window(where you got the error) and run the command again.

> myenv\Scripts\activate and then python manage.py runserver 8085 ,

(8085 or any number if you want to change its default port to work on otherwise you dont need to point out anything. )

DateTime.TryParseExact() rejecting valid formats

Try:

 DateTime.TryParseExact(txtStartDate.Text, formats, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out startDate)

How to select the first element with a specific attribute using XPath

As an explanation to Jonathan Fingland's answer:

  • multiple conditions in the same predicate ([position()=1 and @location='US']) must be true as a whole
  • multiple conditions in consecutive predicates ([position()=1][@location='US']) must be true one after another
  • this implies that [position()=1][@location='US'] != [@location='US'][position()=1]
    while [position()=1 and @location='US'] == [@location='US' and position()=1]
  • hint: a lone [position()=1] can be abbreviated to [1]

You can build complex expressions in predicates with the Boolean operators "and" and "or", and with the Boolean XPath functions not(), true() and false(). Plus you can wrap sub-expressions in parentheses.

MySQL Cannot Add Foreign Key Constraint

Please ensure that both the tables are in InnoDB format. Even if one is in MyISAM format, then, foreign key constraint wont work.

Also, another thing is that, both the fields should be of the same type. If one is INT, then the other should also be INT. If one is VARCHAR, the other should also be VARCHAR, etc.

Read a javascript cookie by name

document.cookie="MYBIGCOOKIE=1";

Your cookies would look like:

"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"

first of all read all cookies:

var read_cookies = document.cookie;

then split all cookies with ";":

var split_read_cookie = read_cookies.split(";");

then use for loop to read each value. Into loop each value split again with "=":

for (i=0;i<split_read_cookie.length;i++){
    var value=split_read_cookie[i];
    value=value.split("=");
    if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
        alert('it is 1');
    }
}

How to get an HTML element's style values in javascript?

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc).

Also, the IE element.currentStyle will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.

I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:

function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  // W3C standard way:
  if (defaultView && defaultView.getComputedStyle) {
    // sanitize property name to css notation
    // (hypen separated words eg. font-Size)
    styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  } else if (el.currentStyle) { // IE
    // sanitize property name to camelCase
    styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
      return letter.toUpperCase();
    });
    value = el.currentStyle[styleProp];
    // convert other units to pixels on IE
    if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
      return (function(value) {
        var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
        el.runtimeStyle.left = el.currentStyle.left;
        el.style.left = value || 0;
        value = el.style.pixelLeft + "px";
        el.style.left = oldLeft;
        el.runtimeStyle.left = oldRsLeft;
        return value;
      })(value);
    }
    return value;
  }
}

The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.

I'm currently working on an article in the subject, you can follow the changes I make to this function here.

Numpy: Creating a complex array from 2 real ones?

This seems to do what you want:

numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)

Here is another solution:

# The ellipsis is equivalent here to ":,:,:"...
numpy.vectorize(complex)(Data[...,0], Data[...,1])

And yet another simpler solution:

Data[...,0] + 1j * Data[...,1]

PS: If you want to save memory (no intermediate array):

result = 1j*Data[...,1]; result += Data[...,0]

devS' solution below is also fast.

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

Compare given date with today

One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,

//  input
$var = "2016-11-09 00:00:00.0";

//  check if date is today or in the future
if ( time() <= strtotime($var) ) 
{
    //  This seems right, but if it's ONLY date you are after
    //  then the code might treat $var as past depending on
    //  the time.
}

The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:

//  plain date string
$input = "2016-11-09";

Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.

To fix this, you can simply code, like this:

if (date("Y-m-d") <= $input)
{
    echo "Input date is equal to or greater than today.";
}

Android Studio installation on Windows 7 fails, no JDK found

In case you had it running but Now it doesn't Launch.
I deleted the C:\Users\<NAME>\.AndroidStudio<version>\ folder and it worked.

What's the valid way to include an image with no src?

I personally use an about:blank src and deal with the broken image icon by setting the opacity of the img element to 0.

AngularJs $http.post() does not send data

I've been using the accepted answer's code (Felipe's code) for a while and it's been working great (thanks, Felipe!).

However, recently I discovered that it has issues with empty objects or arrays. For example, when submitting this object:

{
    A: 1,
    B: {
        a: [ ],
    },
    C: [ ],
    D: "2"
}

PHP doesn't seem to see B and C at all. It gets this:

[
    "A" => "1",
    "B" => "2"
]

A look at the actual request in Chrome shows this:

A: 1
:
D: 2

I wrote an alternative code snippet. It seems to work well with my use-cases but I haven't tested it extensively so use with caution.

I used TypeScript because I like strong typing but it would be easy to convert to pure JS:

angular.module("MyModule").config([ "$httpProvider", function($httpProvider: ng.IHttpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

    function phpize(obj: Object | any[], depth: number = 1): string[] {
        var arr: string[] = [ ];
        angular.forEach(obj, (value: any, key: string) => {
            if (angular.isObject(value) || angular.isArray(value)) {
                var arrInner: string[] = phpize(value, depth + 1);
                var tmpKey: string;
                var encodedKey = encodeURIComponent(key);
                if (depth == 1) tmpKey = encodedKey;
                else tmpKey = `[${encodedKey}]`;
                if (arrInner.length == 0) {
                    arr.push(`${tmpKey}=`);
                }
                else {
                    arr = arr.concat(arrInner.map(inner => `${tmpKey}${inner}`));
                }
            }
            else {
                var encodedKey = encodeURIComponent(key);
                var encodedValue;
                if (angular.isUndefined(value) || value === null) encodedValue = "";
                else encodedValue = encodeURIComponent(value);

                if (depth == 1) {
                    arr.push(`${encodedKey}=${encodedValue}`);
                }
                else {
                    arr.push(`[${encodedKey}]=${encodedValue}`);
                }
            }
        });
        return arr;
    }

    // Override $http service's default transformRequest
    (<any>$httpProvider.defaults).transformRequest = [ function(data: any) {
        if (!angular.isObject(data) || data.toString() == "[object File]") return data;
        return phpize(data).join("&");
    } ];
} ]);

It's less efficient than Felipe's code but I don't think it matters much since it should be immediate compared to the overall overhead of the HTTP request itself.

Now PHP shows:

[
    "A" => "1",
    "B" => [
        "a" => ""
    ],
    "C" => "",
    "D" => "2"
]

As far as I know it's not possible to get PHP to recognize that B.a and C are empty arrays, but at least the keys appear, which is important when there's code that relies on the a certain structure even when its essentially empty inside.

Also note that it converts undefineds and nulls to empty strings.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.

Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:

  1. Edit the hosts file

    $ sudo nano -w /etc/hosts
    
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    
    127.0.0.1 myserver.myhome.com myserver
    
    192.168.1.150 myserver.myhome.com myserver
    
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    ::1 myserver.myhome.com myserver
    
  2. Edit httpd.conf

    $ sudo nano -w /etc/apache2/httpd.conf
    
    ServerName myserver.myhome.com
    
  3. Edit network

    $ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
    
  4. Verify

    $ hostname
    
    (output) myserver.myhome.com
    
    $ hostname -f
    
    (output) myserver.myhome.com
    
  5. Restart Apache

    $ sudo /etc/init.d/apache2 restart
    

It appeared the difference was including myserver.myhome.com to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.

Getting Checkbox Value in ASP.NET MVC 4

Use only this

$("input[type=checkbox]").change(function () {
    if ($(this).prop("checked")) {
        $(this).val(true);
    } else {
        $(this).val(false);
    }
});

Uncaught TypeError: Cannot read property 'value' of null

Easier and more succinct with || ...:

$(document).ready(function(){


  var str = ((document.getElementById("cal_preview")||{}).value)||"";
  var str1 = ((document.getElementById("year")||{}).value)||"";
  var str2 = ((document.getElementById("holiday")||{}).value)||"";
  var str3 = ((document.getElementById("cal_option")||{}).value)||"";


    if (str=="" && str1=="" && str2=="" && str3=="" )
      {
        document.getElementById("calendar_preview").innerHTML="";
          return;
        } 
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.onreadystatechange=function()
      {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText;
          }
      }

    var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(); 


});

did you register the component correctly? For recursive components, make sure to provide the "name" option

I had this error and discovered the issue was because the name of the component was identical to the name of a prop.

import Control from '@/Control.vue';
export default {
    name: 'Question',
    components: {
        Control
    },
    props: ['Control', 'source'],

I was using file components. I changed the Control.vue to InputControl.vue and this warning disappeared.

Attempt to write a readonly database - Django w/ SELinux error

This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1) tool can be used to diagnose SELinux denials from the log:

(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc:  denied  { write }
      for  pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
      scontext=system_u:system_r:httpd_t:s0
      tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
      tclass=file permissive=0
    Was caused by:
    The boolean httpd_unified was set incorrectly. 
    Description:
    Allow httpd to unified

    Allow access by executing:
    # setsebool -P httpd_unified 1

Sure enough, running sudo setsebool -P httpd_unified 1 resolved the issue.

Looking into what httpd_unified is for, I came across a fedora-selinux-list post which explains:

This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.

So turning on httpd_unified lets you circumvent the default behaviour that prevents multiple httpd instances on the same server - all running as user apache - messing with each others' stuff.

In my case, I am only running one httpd, so it was fine for me to turn on httpd_unified. If you cannot do this, I suppose some more fine-grained labelling is needed.

What is difference between @RequestBody and @RequestParam?

It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.

How do I look inside a Python object?

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

HTTP test server accepting GET/POST requests

I am not sure if anyone would take this much pain to test GET and POST calls. I took Python Flask module and wrote a function that does something similar to what @Robert shared.

from flask import Flask, request
app = Flask(__name__)

@app.route('/method', methods=['GET', 'POST'])
@app.route('/method/<wish>', methods=['GET', 'POST'])
def method_used(wish=None):
    if request.method == 'GET':
        if wish:
            if wish in dir(request):
                ans = None
                s = "ans = str(request.%s)" % wish
                exec s
                return ans
            else:
                return 'This wish is not available. The following are the available wishes: %s' % [method for method in dir(request) if '_' not in method]
        else:
            return 'This is just a GET method'
    else:
        return "You are using POST"

When I run this, this follows:

C:\Python27\python.exe E:/Arindam/Projects/Flask_Practice/first.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 581-155-269
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now lets try some calls. I am using the browser.

http://127.0.0.1:5000/method

This is just a GET method

http://127.0.0.1:5000/method/NotCorrect

This wish is not available. The following are the available wishes: ['application', 'args', 'authorization', 'blueprint', 'charset', 'close', 'cookies', 'data', 'date', 'endpoint', 'environ', 'files', 'form', 'headers', 'host', 'json', 'method', 'mimetype', 'module', 'path', 'pragma', 'range', 'referrer', 'scheme', 'shallow', 'stream', 'url', 'values']

http://127.0.0.1:5000/method/environ

{'wsgi.multiprocess': False, 'HTTP_COOKIE': 'csrftoken=YFKYYZl3DtqEJJBwUlap28bLG1T4Cyuq', 'SERVER_SOFTWARE': 'Werkzeug/0.12.2', 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/method/environ', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'werkzeug.server.shutdown': , 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'HTTP_CONNECTION': 'keep-alive', 'SERVER_NAME': '127.0.0.1', 'REMOTE_PORT': 49569, 'wsgi.url_scheme': 'http', 'SERVER_PORT': '5000', 'werkzeug.request': , 'wsgi.input': , 'HTTP_HOST': '127.0.0.1:5000', 'wsgi.multithread': False, 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8', 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.errors': ', mode 'w' at 0x0000000002042150>, 'REMOTE_ADDR': '127.0.0.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch, br'}

dispatch_after - GCD in Swift?

In Swift 3.0

Dispatch queues

  DispatchQueue(label: "test").async {
        //long running Background Task
        for obj in 0...1000 {
            print("async \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.async(execute: { 
            print("UI update on main queue")
        })

    }

    DispatchQueue(label: "m").sync {
        //long running Background Task
        for obj in 0...1000 {
            print("sync \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.sync(execute: {
            print("UI update on main queue")
        })
    }

Dispatch after 5 seconds

    DispatchQueue.main.after(when: DispatchTime.now() + 5) {
        print("Dispatch after 5 sec")
    }

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

Asp Net Web API 2.1 get client IP address

It's better to cast it to HttpContextBase, this way you can mock and test it more easily

public string GetUserIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
        if (ctx != null)
        {
            return ctx.Request.UserHostAddress;
        }
    }

    return null;
}

How do I get a file extension in PHP?

You can try also this (it works on PHP 5.* and 7):

$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip

Tip: it returns an empty string if the file doesn't have an extension

How do I download the Android SDK without downloading Android Studio?

To download the SDK over command line, the link has changed slightly than previously mentioned:

wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip

Latest version listed on the downloads page.

Compare two dates with JavaScript

function datesEqual(a, b)
{
   return (!(a>b || b>a))
}

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

JUnit 4 compare Sets

Check this article. One example from there:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go:

USE information_schema;
SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id';

If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:

SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id'
  AND TABLE_SCHEMA = 'your_database_name';

C++ - struct vs. class

1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

Using --add-host or extra_hosts with docker-compose

This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.

fatal: bad default revision 'HEAD'

Your repo is yours, what goes on in it is entirely your business until you push or (allow a) fetch or clone. When you deleted your windows repo -- that folder didn't represent your local repo, it was your actual local repo, you deleted everything done in it that was never pushed, fetched or cloned.

edit: Ah, okay, I think I see what's going on here: you pushed to your linux repo but it's not bare and you never worked in it.

Instead of git log, do git log --all. Or git checkoutsome-branch-name.

Then try cloning the repo locally, on your linux box; I bet it works. What are you using to serve your repo on linux? Try cd'ing into its .git directory and git daemon --base-path=. --export-all, if that just sits there then go to your windows box and try git clone git://your.linux.box.ip, if the daemon complains it can't bind add --port=54345 to the daemon invoke and :54345 to the clone url.

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Angular 5 ngHide ngShow [hidden] not working

Try this:

<button (click)="click()">Click me</button>

<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />

component.ts:

isHidden: boolean = false;
click(){
    this.isHidden = !this.isHidden;
}

How to use Python's pip to download and keep the zipped files for a package?

Use pip download <package1 package2 package n> to download all the packages including dependencies

Use pip install --no-index --find-links . <package1 package2 package n> to install all the packages including dependencies. It gets all the files from CWD. It will not download anything

How to execute a Windows command on a remote PC?

You can use native win command:

WMIC /node:ComputerName process call create “cmd.exe /c start.exe”

The WMIC is part of wbem win folder: C:\Windows\System32\wbem

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

WPF Image Dynamically changing Image source during runtime

Here is how it worked beautifully for me. In the window resources add the image.

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

Then the code goes like this.

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

"this" is referring to the Window object

Jquery If radio button is checked

$('input:radio[name="postage"]').change(
    function(){
        if ($(this).is(':checked') && $(this).val() == 'Yes') {
            // append goes here
        }
    });

Or, the above - again - using a little less superfluous jQuery:

$('input:radio[name="postage"]').change(
    function(){
        if (this.checked && this.value == 'Yes') {
            // note that, as per comments, the 'changed'
            // <input> will *always* be checked, as the change
            // event only fires on checking an <input>, not
            // on un-checking it.
            // append goes here
        }
    });

Revised (improved-some) jQuery:

// defines a div element with the text "You're appendin'!"
// assigns that div to the variable 'appended'
var appended = $('<div />').text("You're appendin'!");

// assigns the 'id' of "appended" to the 'appended' element
appended.id = 'appended';

// 1. selects '<input type="radio" />' elements with the 'name' attribute of 'postage'
// 2. assigns the onChange/onchange event handler
$('input:radio[name="postage"]').change(
    function(){

        // checks that the clicked radio button is the one of value 'Yes'
        // the value of the element is the one that's checked (as noted by @shef in comments)
        if ($(this).val() == 'Yes') {

            // appends the 'appended' element to the 'body' tag
            $(appended).appendTo('body');
        }
        else {

            // if it's the 'No' button removes the 'appended' element.
            $(appended).remove();
        }
    });

_x000D_
_x000D_
var appended = $('<div />').text("You're appendin'!");_x000D_
appended.id = 'appended';_x000D_
$('input:radio[name="postage"]').change(function() {_x000D_
  if ($(this).val() == 'Yes') {_x000D_
    $(appended).appendTo('body');_x000D_
  } else {_x000D_
    $(appended).remove();_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes_x000D_
<input type="radio" id="postageno" name="postage" value="No" />No
_x000D_
_x000D_
_x000D_

JS Fiddle demo.

And, further, a mild update (since I was editing to include Snippets as well as the JS Fiddle links), in order to wrap the <input /> elements with <label>s - allow for clicking the text to update the relevant <input /> - and changing the means of creating the content to append:

_x000D_
_x000D_
var appended = $('<div />', {_x000D_
  'id': 'appended',_x000D_
  'text': 'Appended content'_x000D_
});_x000D_
$('input:radio[name="postage"]').change(function() {_x000D_
  if ($(this).val() == 'Yes') {_x000D_
    $(appended).appendTo('body');_x000D_
  } else {_x000D_
    $(appended).remove();_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
  <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>_x000D_
<label>_x000D_
  <input type="radio" id="postageno" name="postage" value="No" />No</label>
_x000D_
_x000D_
_x000D_

JS Fiddle demo.

Also, if you only need to show content depending on which element is checked by the user, a slight update that will toggle visibility using an explicit show/hide:

_x000D_
_x000D_
// caching a reference to the dependant/conditional content:_x000D_
var conditionalContent = $('#conditional'),_x000D_
    // caching a reference to the group of inputs, since we're using that_x000D_
    // same group twice:_x000D_
    group = $('input[type=radio][name=postage]');_x000D_
_x000D_
// binding the change event-handler:_x000D_
group.change(function() {_x000D_
  // toggling the visibility of the conditionalContent, which will_x000D_
  // be shown if the assessment returns true and hidden otherwise:_x000D_
  conditionalContent.toggle(group.filter(':checked').val() === 'Yes');_x000D_
  // triggering the change event on the group, to appropriately show/hide_x000D_
  // the conditionalContent on page-load/DOM-ready:_x000D_
}).change();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
  <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>_x000D_
<label>_x000D_
  <input type="radio" id="postageno" name="postage" value="No" />No</label>_x000D_
<div id="conditional">_x000D_
  <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And, finally, using just CSS:

_x000D_
_x000D_
/* setting the default of the conditionally-displayed content_x000D_
to hidden: */_x000D_
#conditional {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
/* if the #postageyes element is checked then the general sibling of_x000D_
that element, with the id of 'conditional', will be shown: */_x000D_
#postageyes:checked ~ #conditional {_x000D_
  display: block;_x000D_
}
_x000D_
<!-- note that the <input> elements are now not wrapped in the <label> elements,_x000D_
in order that the #conditional element is a (subsequent) sibling of the radio_x000D_
<input> elements: -->_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />_x000D_
<label for="postageyes">Yes</label>_x000D_
<input type="radio" id="postageno" name="postage" value="No" />_x000D_
<label for="postageno">No</label>_x000D_
<div id="conditional">_x000D_
  <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo.

References: