Programs & Examples On #Jboss web

For development issues encountered while using Red Hat JBoss Web Server.

Enable Hibernate logging

I answer to myself. As suggested by Vadzim, I must consider the jboss-logging.xml file and insert these lines:

<logger category="org.hibernate">
     <level name="TRACE"/>
</logger>

Instead of DEBUG level I wrote TRACE. Now don't look only the console but open the server.log file (debug messages aren't sent to the console but you can configure this mode!).

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Eclipse "this compilation unit is not on the build path of a java project"

For example if there are 4 project and a root project, add the other child projects to build path of root project. If there is not selection of build path, add below codes to .project file.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>rootProject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.m2e.core.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
        <nature>org.eclipse.m2e.core.maven2Nature</nature>
    </natures>
</projectDescription>

How can I determine if a variable is 'undefined' or 'null'?

I've just had this problem i.e. checking if an object is null.
I simply use this:

if (object) {
    // Your code
}

For example:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

Send POST data using XMLHttpRequest

Use modern JavaScript!

I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

_x000D_
_x000D_
const url = "http://example.com";
fetch(url, {
    method : "POST",
    body: new FormData(document.getElementById("inputform")),
    // -- or --
    // body : JSON.stringify({
        // user : document.getElementById('user').value,
        // ...
    // })
}).then(
    response => response.text() // .json(), etc.
    // same as function(response) {return response.text();}
).then(
    html => console.log(html)
);
_x000D_
_x000D_
_x000D_

In Node.js, you'll need to import fetch using:

const fetch = require("node-fetch");

If you want to use it synchronously (doesn't work in top scope):

const json = await fetch(url, optionalOptions)
  .then(response => response.json()) // .text(), etc.
  .catch((e) => {});

More Info:

Mozilla Documentation

Can I Use (96% Nov 2020)

David Walsh Tutorial

Excel VBA: function to turn activecell to bold

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

Eg

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

What is the best regular expression to check if a string is a valid URL?

Here is the best and the most matched regex for this situation

^(?:http(?:s)?:\/\/)?(?:www\.)?(?:[\w-]*)\.\w{2,}$

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

Eclipse will not open due to environment variables

You should install both 32bit & 64bit java (At least JRE), that in case you're using 64bit OS.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

On moving a .html template to a wordpress one, I found this "popper required" popping up regularly :)

Two reasons it happened for me: and the console error can be deceptive:

  1. The error in the console can send you down the wrong path. It MIGHT not be the real issue. First reason for me was the order in which you have set your .js files to load. In html easy, put them in the same order as the theme template. In Wordpress, you need to enqueue them in the right order, but also set a priority if they don't appear in the right order,

  2. Second thing is are the .js files in the header or the footer. Moving them to the footer can solve the issue - it did for me, after a day of trying to debug the issue. Usually doesn't matter, but for a complex page with lots of js libraries, it might!

How to find a whole word in a String in java

To Match "123woods" instead of "woods" , use atomic grouping in regular expresssion. One thing to be noted is that, in a string to match "123woods" alone , it will match the first "123woods" and exits instead of searching the same string further.

\b(?>123woods|woods)\b

it searches 123woods as primary search, once it got matched it exits the search.

Add missing dates to pandas dataframe

You could use Series.reindex:

import pandas as pd

idx = pd.date_range('09-01-2013', '09-30-2013')

s = pd.Series({'09-02-2013': 2,
               '09-03-2013': 10,
               '09-06-2013': 5,
               '09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)

s = s.reindex(idx, fill_value=0)
print(s)

yields

2013-09-01     0
2013-09-02     2
2013-09-03    10
2013-09-04     0
2013-09-05     0
2013-09-06     5
2013-09-07     1
2013-09-08     0
...

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

NHibernate.MappingException: No persister for: XYZ

My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!

How can I pass a list as a command-line argument with argparse?

TL;DR

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

nargs

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

append

parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567

With append you provide the option multiple times to build up the list.

Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.


Let's take a look in more detail at some of the different ways one might try to do this, and the end result.

import argparse

parser = argparse.ArgumentParser()

# By default it will fail with multiple arguments.
parser.add_argument('--default')

# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)

# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')

# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')

# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)

# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')

# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
    if value is not None:
        print(value)

Here is the output you can expect:

$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ # Quotes won't help here... 
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']

$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Takeaways:

  • Use nargs or action='append'
    • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
    • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
  • Don't use quotes on the command line1
  • Don't use type=list, as it will return a list of lists
    • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
    • You can use type=int (or whatever) to get a list of ints (or whatever)

1: I don't mean in general.. I mean using quotes to pass a list to argparse is not what you want.

Hidden Features of Java

I know this was added in release 1.5 but the new enum type is a great feature. Not having to use the old "int enum pattern" has greatly helped a bunch of my code. Check out JLS 8.9 for the sweet gravy on your potatoes!

print variable and a string in python

By printing multiple values separated by a comma:

print "I have", card.price

The print statement will output each expression separated by spaces, followed by a newline.

If you need more complex formatting, use the ''.format() method:

print "I have: {0.price}".format(card)

or by using the older and semi-deprecated % string formatting operator.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Known bug with Xcode 11.2 can cause this issue. Xcode 11.2 has been deprecated.

Downloading Xcode 11.2.1 solved the issue.

Apple 11.2 Bug Forum

I also updated real device to current iOS, but i don't think that was the issue.

Composer: Command Not Found

I am using CentOS and had same problem.

I changed /usr/local/bin/composer to /usr/bin/composer and it worked.

Run below command :

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/bin/composer

Verify Composer is installed or not

composer --version

Best data type to store money values in MySQL

You can use DECIMAL or NUMERIC both are same

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL

i.e. DECIMAL(10,2)

Example settings

Good read

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Limiting the number of characters in a JTextField

Here is an optimized version of npinti's answer:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;

public class TextComponentLimit extends PlainDocument
{
    private int charactersLimit;

    private TextComponentLimit(int charactersLimit)
    {
        this.charactersLimit = charactersLimit;
    }

    @Override
    public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
    {
        if (isAllowed(input))
        {
            super.insertString(offset, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isAllowed(String string)
    {
        return (getLength() + string.length()) <= charactersLimit;
    }

    public static void addTo(JTextComponent textComponent, int charactersLimit)
    {
        TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
        textComponent.setDocument(textFieldLimit);
    }
}

To add a limit to your JTextComponent, simply write the following line of code:

JTextFieldLimit.addTo(myTextField, myMaximumLength);

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

How does one generate a random number in Apple's Swift language?

I used this code:

var k: Int = random() % 10;

How to scroll UITableView to specific position

finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{    
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{  
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {         
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault    
                                       reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * theCell = (UITableViewCell *)[tableView     
                                              cellForRowAtIndexPath:indexPath];

    CGPoint tableViewCenter = [tableView contentOffset];
    tableViewCenter.y += myTable.frame.size.height/2;

    [tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
    [tableView reloadData]; 
 }

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

How do I get the App version and build number using Swift?

Swift 4

func getAppVersion() -> String {
    return "\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] ?? "")"
}

Bundle.main.infoDictionary!["CFBundleShortVersionString"]

Swift old syntax

let appVer: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]

Git: Merge a Remote branch locally

Maybe you want to track the remote branch with a local branch:

  1. Create a new local branch: git branch new-local-branch
  2. Set this newly created branch to track the remote branch: git branch --set-upstream-to=origin/remote-branch new-local-branch
  3. Enter into this branch: git checkout new-local-branch
  4. Pull all the contents of the remote branch into the local branch: git pull

C# How to determine if a number is a multiple of another?

there are some syntax errors to your program heres a working code;

#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is  multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}

}

Clean out Eclipse workspace metadata

In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-

I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system: 1. Go to Eclipse --> Project --> Clean 2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"

After that boom - things gets start working :)

If you want to load variables from other files too then ado this :- Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"

Then it will show element , variables and other functions also.

Join a list of items with different types as string in Python

How come no-one seems to like repr?
python 3.7.2:

>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>> 

Take care though, it's an explicit representation. An example shows:

#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>> 

more info at pydocs-repr

sqlplus how to find details of the currently connected database session

I know this is an old question but I did try all the above answers but didnt work in my case. What ultimately helped me out is

SHOW PARAMETER instance_name

Unable to locate tools.jar

I have resolved tool.jar file error recently. I am using eclipse oxygen ide. It works perfectly and easy. Repeat these steps on your system as

  1. Download tool.jar file according to your jre jdk version. Lets suppose tool.jar file is 1.8.0.tool.jar

  2. After donwload 1.8 .0 tool.jar file rename is as as tool.jar

  3. Then go to your jdk installation folder

  4. Then go to lib folder open it

  5. And paste here

  6. You will make this type path. E:\jdk 8\lib\tools.jar

How do I edit an incorrect commit message in git ( that I've pushed )?

The message from Linus Torvalds may answer your question:

Modify/edit old commit messages

Short answer: you can not (if pushed).


extract (Linus refers to BitKeeper as BK):

Side note, just out of historical interest: in BK you could.

And if you're used to it (like I was) it was really quite practical. I would apply a patch-bomb from Andrew, notice something was wrong, and just edit it before pushing it out.

I could have done the same with git. It would have been easy enough to make just the commit message not be part of the name, and still guarantee that the history was untouched, and allow the "fix up comments later" thing.

But I didn't.

Part of it is purely "internal consistency". Git is simply a cleaner system thanks to everything being SHA1-protected, and all objects being treated the same, regardless of object type. Yeah, there are four different kinds of objects, and they are all really different, and they can't be used in the same way, but at the same time, even if their encoding might be different on disk, conceptually they all work exactly the same.

But internal consistency isn't really an excuse for being inflexible, and clearly it would be very flexible if we could just fix up mistakes after they happen. So that's not a really strong argument.

The real reason git doesn't allow you to change the commit message ends up being very simple: that way, you can trust the messages. If you allowed people to change them afterwards, the messages are inherently not very trustworthy.


To be complete, you could rewrite your local commit history in order to reflect what you want, as suggested by sykora (with some rebase and reset --hard, gasp!)

However, once you publish your revised history again (with a git push origin +master:master, the + sign forcing the push to occur, even if it doesn't result in a "fast-forward" commit)... you might get into some trouble.

Extract from this other SO question:

I actually once pushed with --force to git.git repository and got scolded by Linus BIG TIME. It will create a lot of problems for other people. A simple answer is "don't do it".

How to Install Sublime Text 3 using Homebrew

$ brew tap caskroom/cask
$ brew install brew-cask
$ brew tap caskroom/versions
$ brew cask install sublime-text

Cannot read configuration file due to insufficient permissions

Go to the parent folder, right-click and select Properties. Select the Security tab, edit the permissions and Add. Click on Advanced and the Find Now. Select IIS_IUSRS and click OK and OK again. Make sure you have check Write. Click OK and OK again.

Job done!

Volley JsonObjectRequest Post request not working

Easy one for me ! I got it few weeks ago :

This goes in getBody() method, not in getParams() for a post request.

Here is mine :

    @Override
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    //        Map<String, String> params = getParams();
    Map<String, String> params = new HashMap<String, String>();
    params.put("id","1");
    params.put("name", "myname");
    if (params != null && params.size() > 0) {
        return encodeParameters(params, getParamsEncoding());
    }
    return null;

}

(I assumed you want to POST the params you wrote in your getParams)

I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.

This is what my code looks like :

    Bundle param = new Bundle();
    param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
    param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
    param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);

    switch (type) {
    case RequestType.POST:
        param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
        SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));

and if you want even more this last string params comes from :

param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();

and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

How do I compile a .c file on my Mac?

You can use gcc, in Terminal, by doing gcc -c tat.c -o tst

however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from http://developer.apple.com

Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...

http://connect.apple.com/cgi-bin/WebObjects/MemberSite.woa/wo/5.1.17.2.1.3.3.1.0.1.1.0.3.3.3.3.1

Permission denied (publickey) when SSH Access to Amazon EC2 instance

You need to do the following steps:

  1. Open your ssh client or terminal if you are using Linux.
  2. Locate your private key file and change your directory.
    cd <path to your .pem file>
  3. Execute below commands:
    chmod 400 <filename>.pem
    ssh -i <filename>.pem ubuntu@<ipaddress.com>

If ubuntu user is not working then try with ec2-user.

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Critical t values in R

Extending @Ryogi answer above, you can take advantage of the lower.tail parameter like so:

qt(0.25/2, 40, lower.tail = FALSE) # 75% confidence

qt(0.01/2, 40, lower.tail = FALSE) # 99% confidence

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  
}

Allowed memory size of 536870912 bytes exhausted in Laravel

I had the same problem. No matter how much I was increasing memory_limit (even tried 4GB) I was getting the same error, until I figured out it was because of wrong database credentials setted up in .env file

Use space as a delimiter with cut command

I just discovered that you can also use "-d ":

cut "-d "

Test

$ cat a
hello how are you
I am fine
$ cut "-d " -f2 a
how
am

href image link download on click

The easiest way of creating download link for image or html is setting download attribute, but this solution works in modern browsers only.

<a href="/path/to/image" download="myimage"><img src="/path/to/image" /></a>

"myimage" is a name of file to download. Extension will be added automatically Example here

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I found the solution for it by analyzing the data packets using wireshark. What I found is that while making a secure connection, android was falling back to SSLv3 from TLSv1 . It is a bug in android versions < 4.4 , and it can be solved by removing the SSLv3 protocol from Enabled Protocols list. I made a custom socketFactory class called NoSSLv3SocketFactory.java. Use this to make a socketfactory.

/*Copyright 2015 Bhavit Singh Sengar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


public class NoSSLv3SocketFactory extends SSLSocketFactory{
    private final SSLSocketFactory delegate;

public NoSSLv3SocketFactory() {
    this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
}

public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
    this.delegate = delegate;
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

private Socket makeSocketSafe(Socket socket) {
    if (socket instanceof SSLSocket) {
        socket = new NoSSLv3SSLSocket((SSLSocket) socket);
    }
    return socket;
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return makeSocketSafe(delegate.createSocket(address, port, localAddress, localPort));
}

private class NoSSLv3SSLSocket extends DelegateSSLSocket {

    private NoSSLv3SSLSocket(SSLSocket delegate) {
        super(delegate);

    }

    @Override
    public void setEnabledProtocols(String[] protocols) {
        if (protocols != null && protocols.length == 1 && "SSLv3".equals(protocols[0])) {

            List<String> enabledProtocols = new ArrayList<String>(Arrays.asList(delegate.getEnabledProtocols()));
            if (enabledProtocols.size() > 1) {
                enabledProtocols.remove("SSLv3");
                System.out.println("Removed SSLv3 from enabled protocols");
            } else {
                System.out.println("SSL stuck with protocol available for " + String.valueOf(enabledProtocols));
            }
            protocols = enabledProtocols.toArray(new String[enabledProtocols.size()]);
        }

        super.setEnabledProtocols(protocols);
    }
}

public class DelegateSSLSocket extends SSLSocket {

    protected final SSLSocket delegate;

    DelegateSSLSocket(SSLSocket delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public String[] getEnabledCipherSuites() {
        return delegate.getEnabledCipherSuites();
    }

    @Override
    public void setEnabledCipherSuites(String[] suites) {
        delegate.setEnabledCipherSuites(suites);
    }

    @Override
    public String[] getSupportedProtocols() {
        return delegate.getSupportedProtocols();
    }

    @Override
    public String[] getEnabledProtocols() {
        return delegate.getEnabledProtocols();
    }

    @Override
    public void setEnabledProtocols(String[] protocols) {
        delegate.setEnabledProtocols(protocols);
    }

    @Override
    public SSLSession getSession() {
        return delegate.getSession();
    }

    @Override
    public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
        delegate.addHandshakeCompletedListener(listener);
    }

    @Override
    public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
        delegate.removeHandshakeCompletedListener(listener);
    }

    @Override
    public void startHandshake() throws IOException {
        delegate.startHandshake();
    }

    @Override
    public void setUseClientMode(boolean mode) {
        delegate.setUseClientMode(mode);
    }

    @Override
    public boolean getUseClientMode() {
        return delegate.getUseClientMode();
    }

    @Override
    public void setNeedClientAuth(boolean need) {
        delegate.setNeedClientAuth(need);
    }

    @Override
    public void setWantClientAuth(boolean want) {
        delegate.setWantClientAuth(want);
    }

    @Override
    public boolean getNeedClientAuth() {
        return delegate.getNeedClientAuth();
    }

    @Override
    public boolean getWantClientAuth() {
        return delegate.getWantClientAuth();
    }

    @Override
    public void setEnableSessionCreation(boolean flag) {
        delegate.setEnableSessionCreation(flag);
    }

    @Override
    public boolean getEnableSessionCreation() {
        return delegate.getEnableSessionCreation();
    }

    @Override
    public void bind(SocketAddress localAddr) throws IOException {
        delegate.bind(localAddr);
    }

    @Override
    public synchronized void close() throws IOException {
        delegate.close();
    }

    @Override
    public void connect(SocketAddress remoteAddr) throws IOException {
        delegate.connect(remoteAddr);
    }

    @Override
    public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
        delegate.connect(remoteAddr, timeout);
    }

    @Override
    public SocketChannel getChannel() {
        return delegate.getChannel();
    }

    @Override
    public InetAddress getInetAddress() {
        return delegate.getInetAddress();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return delegate.getInputStream();
    }

    @Override
    public boolean getKeepAlive() throws SocketException {
        return delegate.getKeepAlive();
    }

    @Override
    public InetAddress getLocalAddress() {
        return delegate.getLocalAddress();
    }

    @Override
    public int getLocalPort() {
        return delegate.getLocalPort();
    }

    @Override
    public SocketAddress getLocalSocketAddress() {
        return delegate.getLocalSocketAddress();
    }

    @Override
    public boolean getOOBInline() throws SocketException {
        return delegate.getOOBInline();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return delegate.getOutputStream();
    }

    @Override
    public int getPort() {
        return delegate.getPort();
    }

    @Override
    public synchronized int getReceiveBufferSize() throws SocketException {
        return delegate.getReceiveBufferSize();
    }

    @Override
    public SocketAddress getRemoteSocketAddress() {
        return delegate.getRemoteSocketAddress();
    }

    @Override
    public boolean getReuseAddress() throws SocketException {
        return delegate.getReuseAddress();
    }

    @Override
    public synchronized int getSendBufferSize() throws SocketException {
        return delegate.getSendBufferSize();
    }

    @Override
    public int getSoLinger() throws SocketException {
        return delegate.getSoLinger();
    }

    @Override
    public synchronized int getSoTimeout() throws SocketException {
        return delegate.getSoTimeout();
    }

    @Override
    public boolean getTcpNoDelay() throws SocketException {
        return delegate.getTcpNoDelay();
    }

    @Override
    public int getTrafficClass() throws SocketException {
        return delegate.getTrafficClass();
    }

    @Override
    public boolean isBound() {
        return delegate.isBound();
    }

    @Override
    public boolean isClosed() {
        return delegate.isClosed();
    }

    @Override
    public boolean isConnected() {
        return delegate.isConnected();
    }

    @Override
    public boolean isInputShutdown() {
        return delegate.isInputShutdown();
    }

    @Override
    public boolean isOutputShutdown() {
        return delegate.isOutputShutdown();
    }

    @Override
    public void sendUrgentData(int value) throws IOException {
        delegate.sendUrgentData(value);
    }

    @Override
    public void setKeepAlive(boolean keepAlive) throws SocketException {
        delegate.setKeepAlive(keepAlive);
    }

    @Override
    public void setOOBInline(boolean oobinline) throws SocketException {
        delegate.setOOBInline(oobinline);
    }

    @Override
    public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
        delegate.setPerformancePreferences(connectionTime, latency, bandwidth);
    }

    @Override
    public synchronized void setReceiveBufferSize(int size) throws SocketException {
        delegate.setReceiveBufferSize(size);
    }

    @Override
    public void setReuseAddress(boolean reuse) throws SocketException {
        delegate.setReuseAddress(reuse);
    }

    @Override
    public synchronized void setSendBufferSize(int size) throws SocketException {
        delegate.setSendBufferSize(size);
    }

    @Override
    public void setSoLinger(boolean on, int timeout) throws SocketException {
        delegate.setSoLinger(on, timeout);
    }

    @Override
    public synchronized void setSoTimeout(int timeout) throws SocketException {
        delegate.setSoTimeout(timeout);
    }

    @Override
    public void setTcpNoDelay(boolean on) throws SocketException {
        delegate.setTcpNoDelay(on);
    }

    @Override
    public void setTrafficClass(int value) throws SocketException {
        delegate.setTrafficClass(value);
    }

    @Override
    public void shutdownInput() throws IOException {
        delegate.shutdownInput();
    }

    @Override
    public void shutdownOutput() throws IOException {
        delegate.shutdownOutput();
    }

    @Override
    public String toString() {
        return delegate.toString();
    }

    @Override
    public boolean equals(Object o) {
        return delegate.equals(o);
    }
}
}

Use this class like this while connecting :

SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());

HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
l_connection = (HttpsURLConnection) l_url.openConnection();
l_connection.connect();

UPDATE :

Now, correct solution would be to install a newer security provider using Google Play Services:

    ProviderInstaller.installIfNeeded(getApplicationContext());

This effectively gives your app access to a newer version of OpenSSL and Java Security Provider, which includes support for TLSv1.2 in SSLEngine. Once the new provider is installed, you can create an SSLEngine which supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 the usual way:

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    SSLEngine engine = sslContext.createSSLEngine();

Or you can restrict the enabled protocols using engine.setEnabledProtocols.

Don't forget to add the following dependency (check the latest version here):

implementation 'com.google.android.gms:play-services-auth:17.0.0'

For more info, checkout this link.

ReactJS and images in public folder

the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

SQL query question: SELECT ... NOT IN

select * from table_name where id=5 and column_name not in ('sandy,'pandy');

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

Changing the color of a clicked table row using jQuery

in your css:

.selected{
    background: #F00;
}

in the jquery:

$("#data tr").click(function(){
   $(this).toggleClass('selected');
});

Basically you create a class and adds/removes it from the selected row.

Btw you could have shown more effort, there's no css or jquery/js at all in your code xD

Can't execute jar- file: "no main manifest attribute"

most of the solutions did not work for me but my instructor helped me out i would like to share his solution here i used kali linux terminal but should be fine in all debian

javac *.java
nano MANIFEST.MF

in the file type

Main-Class: Main or whatever your main file name is (make sure to add package name if it exists)

jar -cvmf MANIFEST.MF new.jar *.class

now to run the file use

java -jar new.jar

or you can go to propeties of file and check

Allow Execution of file as program

double click on it

it helped me while most of the above answers did not

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

How can I check if a string is a number?

int num;
bool isNumeric = int.TryParse("123", out num);

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Allow user to select camera or gallery for image

This is simple by using AlertDialog and Intent.ACTION_PICK

    //camOption is a string array contains two items (Camera, Gallery)
    AlertDialog.Builder builder = new AlertDialog.Builder(CarPhotos.this);
    builder.setTitle(R.string.selectSource)
    .setItems(R.array.imgOption, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which)

     {

        if (which==0) {
        Intent intent = new Intent(this, CameraActivity.class);
        startActivityForResult(intent, REQ_CAMERA_IMAGE);               }

        if (which==1) {
        Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);
            }

     }
            });
             builder.create();
             builder.show();

PHP Redirect with POST data

Here there is another approach that works for me:

if you need to redirect to another web page (user.php) and includes a PHP variable ($user[0]):

header('Location:./user.php?u_id='.$user[0]);

or

header("Location:./user.php?u_id=$user[0]");

Android Studio: Plugin with id 'android-library' not found

Use mavenCentral() or jcenter() adding in the build.gradle file the script:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'   
    }
}

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

ERROR 1044 (42000): Access denied for 'root' With All Privileges

If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:

  1. Close your MySQL command prompt.

  2. Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_

  3. Go to MySQL.exe by Typing the following commands:

C:\Users\User>cd\ C:\>cd xampp C:\xampp>cd mysql C:\xxampp\mysql>cd bin C:\xampp\mysql\bin>mysql -u root

  1. Now try creating a new database by typing:

    mysql> create database employee;
    

    if it shows:

    Query OK, 1 row affected (0.00 sec)
    mysql>
    

    Then congrats ! You are good to go...

echo key and value of an array without and with loop

How to echo key and value of an array without and with loop

$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

How can I remove a character from a string using JavaScript?

The shortest way would be to use splice

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);

Assigning default values to shell variables with a single command in bash

To answer your question and on all variable substitutions

echo "$\{var}"
echo "Substitute the value of var."


echo "$\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."


echo "$\{var:=word}"
echo "If var is null or unset, var is set to the value of word."


echo "$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."


echo "$\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Arrow functions which is denoted by symbol (=>) helps you to create anonymous functions and methods. That leads to more shorter syntax. For example, below is a simple “Add” function which returns addition of two numbers.

function Add(num1 , num2 ){
return num1 + num2;
}

The above function becomes shorter by using “Arrow” syntax as shown below.

enter image description here

Above code has two parts as shown in the above diagram: -

Input: — This section specifies the input parameters to the anonymous function.

Logic: — This section comes after the symbol “=>”. This section has the logic of the actual function.

Many developers think that arrow function makes your syntax shorter, simpler and thus makes your code readable.

If you believe the above sentence, then let me assure you it’s a myth. If you think for a moment a properly written function with name is much readable than cryptic functions created in one line using an arrow symbol.

The main use of arrow function is to ensure that code runs in the callers context.

See the below code in which have a global variable "context" defined , this global variable is accessed inside a function "SomeOtherMethod" which is called from other method "SomeMethod".

This "SomeMethod" has local "context" variable. Now because "SomeOtherMethod" is called from ""SomeMethod" we expect it to display "local context" , but it displays "global context".

var context = “global context”;

function SomeOtherMethod(){
alert(this.context);
}

function SomeMethod(){
this.context = “local context”;
SomeOtherMethod();
}

var instance = new SomeMethod();

But if replace the call by using Arrow function it will display "local context".

var context = "global context";

    function SomeMethod(){
        this.context = "local context";
        SomeOtherMethod = () => {
            alert(this.context);
        }
        SomeOtherMethod();
    }
    var instance = new SomeMethod();

I would encourage you to read this link ( Arrow function in JavaScript ) which explain all the scenarios of javascript context and in which scenarios the callers context is not respected.

You can also see the demonstration of Arrow function with javascript in this youtube video which demonstrates practically the term Context.

How to take complete backup of mysql database using mysqldump command line utility

It depends a bit on your version. Before 5.0.13 this is not possible with mysqldump.

From the mysqldump man page (v 5.1.30)

 --routines, -R

      Dump stored routines (functions and procedures) from the dumped
      databases. Use of this option requires the SELECT privilege for the
      mysql.proc table. The output generated by using --routines contains
      CREATE PROCEDURE and CREATE FUNCTION statements to re-create the
      routines. However, these statements do not include attributes such
      as the routine creation and modification timestamps. This means that
      when the routines are reloaded, they will be created with the
      timestamps equal to the reload time.
      ...

      This option was added in MySQL 5.0.13. Before that, stored routines
      are not dumped. Routine DEFINER values are not dumped until MySQL
      5.0.20. This means that before 5.0.20, when routines are reloaded,
      they will be created with the definer set to the reloading user. If
      you require routines to be re-created with their original definer,
      dump and load the contents of the mysql.proc table directly as
      described earlier.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

"unable to locate adb" using Android Studio

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

How to set the default value for radio buttons in AngularJS?

<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
               <%=rs.getString(6).equals("male") ? "checked='checked'": "" %>

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

How to check a string against null in java?

If I understand correctly, this should do it:

if(!stringname.isEmpty())
// an if to check if stringname is not null
if(stringname.isEmpty())
// an if to check if stringname is null

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How to set default Checked in checkbox ReactJS?

To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked.

An example:

<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />

How to round a number to n decimal places in Java

Since I found no complete answer on this theme I've put together a class that should handle this properly, with support for:

  • Formatting: Easily format a double to string with a certain number of decimal places
  • Parsing: Parse the formatted value back to double
  • Locale: Format and parse using the default locale
  • Exponential notation: Start using exponential notation after a certain threshold

Usage is pretty simple:

(For the sake of this example I am using a custom locale)

public static final int DECIMAL_PLACES = 2;

NumberFormatter formatter = new NumberFormatter(DECIMAL_PLACES);

String value = formatter.format(9.319); // "9,32"
String value2 = formatter.format(0.0000005); // "5,00E-7"
String value3 = formatter.format(1324134123); // "1,32E9"

double parsedValue1 = formatter.parse("0,4E-2", 0); // 0.004
double parsedValue2 = formatter.parse("0,002", 0); // 0.002
double parsedValue3 = formatter.parse("3423,12345", 0); // 3423.12345

Here is the class:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;

public class NumberFormatter {

    private static final String SYMBOL_INFINITE           = "\u221e";
    private static final char   SYMBOL_MINUS              = '-';
    private static final char   SYMBOL_ZERO               = '0';
    private static final int    DECIMAL_LEADING_GROUPS    = 10;
    private static final int    EXPONENTIAL_INT_THRESHOLD = 1000000000; // After this value switch to exponential notation
    private static final double EXPONENTIAL_DEC_THRESHOLD = 0.0001; // Below this value switch to exponential notation

    private DecimalFormat decimalFormat;
    private DecimalFormat decimalFormatLong;
    private DecimalFormat exponentialFormat;

    private char groupSeparator;

    public NumberFormatter(int decimalPlaces) {
        configureDecimalPlaces(decimalPlaces);
    }

    public void configureDecimalPlaces(int decimalPlaces) {
        if (decimalPlaces <= 0) {
            throw new IllegalArgumentException("Invalid decimal places");
        }

        DecimalFormatSymbols separators = new DecimalFormatSymbols(Locale.getDefault());
        separators.setMinusSign(SYMBOL_MINUS);
        separators.setZeroDigit(SYMBOL_ZERO);

        groupSeparator = separators.getGroupingSeparator();

        StringBuilder decimal = new StringBuilder();
        StringBuilder exponential = new StringBuilder("0.");

        for (int i = 0; i < DECIMAL_LEADING_GROUPS; i++) {
            decimal.append("###").append(i == DECIMAL_LEADING_GROUPS - 1 ? "." : ",");
        }

        for (int i = 0; i < decimalPlaces; i++) {
            decimal.append("#");
            exponential.append("0");
        }

        exponential.append("E0");

        decimalFormat = new DecimalFormat(decimal.toString(), separators);
        decimalFormatLong = new DecimalFormat(decimal.append("####").toString(), separators);
        exponentialFormat = new DecimalFormat(exponential.toString(), separators);

        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        decimalFormatLong.setRoundingMode(RoundingMode.HALF_UP);
        exponentialFormat.setRoundingMode(RoundingMode.HALF_UP);
    }

    public String format(double value) {
        String result;
        if (Double.isNaN(value)) {
            result = "";
        } else if (Double.isInfinite(value)) {
            result = String.valueOf(SYMBOL_INFINITE);
        } else {
            double absValue = Math.abs(value);
            if (absValue >= 1) {
                if (absValue >= EXPONENTIAL_INT_THRESHOLD) {
                    value = Math.floor(value);
                    result = exponentialFormat.format(value);
                } else {
                    result = decimalFormat.format(value);
                }
            } else if (absValue < 1 && absValue > 0) {
                if (absValue >= EXPONENTIAL_DEC_THRESHOLD) {
                    result = decimalFormat.format(value);
                    if (result.equalsIgnoreCase("0")) {
                        result = decimalFormatLong.format(value);
                    }
                } else {
                    result = exponentialFormat.format(value);
                }
            } else {
                result = "0";
            }
        }
        return result;
    }

    public String formatWithoutGroupSeparators(double value) {
        return removeGroupSeparators(format(value));
    }

    public double parse(String value, double defValue) {
        try {
            return decimalFormat.parse(value).doubleValue();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return defValue;
    }

    private String removeGroupSeparators(String number) {
        return number.replace(String.valueOf(groupSeparator), "");
    }

}

Body of Http.DELETE request in Angular2

You are actually able to fool Angular2 HTTP into sending a body with a DELETE by using the request method. This is how:

let body = {
    target: targetId,
    subset: "fruits",
    reason: "rotten"
};

let options = new RequestOptionsArgs({ 
    body: body,
    method: RequestMethod.Delete
  });

this.http.request('http://testAPI:3000/stuff', options)
    .subscribe((ok)=>{console.log(ok)});

Note, you will have to set the request method in the RequestOptionsArgs and not in http.request's alternative first parameter Request. That for some reason yields the same result as using http.delete

I hope this helps and that I am not to late. I think the angular guys are wrong here to not allow a body to be passed with delete, even though it is discouraged.

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

Replace invalid values with None in Pandas DataFrame

df.replace('-', np.nan).astype("object")

This will ensure that you can use isnull() later on your dataframe

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

Import data.sql MySQL Docker Container

You can run a container setting a shared directory (-v volume), and then run bash in that container. After this, you can interactively use mysql-client to execute the .sql file, from inside the container. obs: /my-host-dir/shared-dir is the .sql location in the host system.

docker run --detach --name=test-mysql -p host-port:container-port  --env="MYSQL_ROOT_PASSWORD=my-root-pswd" -v /my-host-dir/shared-dir:/container-dir mysql:latest


docker exec -it test-mysql bash

Inside the container...

mysql -p < /container-dir/file.sql 

Custom parameters:

  • test-mysql (container name)
  • host-port and container-port
  • my-root-pswd (mysql root password)
  • /my-host-dir/shared-dir and /container-dir (the host directory that will be mounted in the container, and the container location of the shared directory)

How do I open an .exe from another C++ .exe?

You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.

#include <windows.h>
using namespace std;
int main()
{
  system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
  return 0;
}

Remove plot axis values

Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,

x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)

The lattice equivalent is

library(lattice)
xyplot(y ~ x, scales=list(alternating=0))

Java current machine name and logged in user?

To get the currently logged in user path:

System.getProperty("user.home");

What is the Simplest Way to Reverse an ArrayList?

Reversing a ArrayList in a recursive way and without creating a new list for adding elements :

   public class ListUtil {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
        System.out.println("Reverse Order: " + reverse(arrayList));

    }

    public static <T> List<T> reverse(List<T> arrayList) {
        return reverse(arrayList,0,arrayList.size()-1);
    }
    public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {

        if(startIndex<lastIndex) {
            T t=arrayList.get(lastIndex);
            arrayList.set(lastIndex,arrayList.get(startIndex));
            arrayList.set(startIndex,t);
            startIndex++;
            lastIndex--;
            reverse(arrayList,startIndex,lastIndex);
        }
        return arrayList;
    }

}

Getting all names in an enum as a String[]

With java 8:

Arrays.stream(MyEnum.values()).map(Enum::name)
                    .collect(Collectors.toList()).toArray();

ASP.NET email validator regex

Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

This Row already belongs to another table error when trying to add rows?

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    DataRow myRow = dtSpecificOrders.NewRow();  // <-- create a brand-new row
    myRow[dcID] = int.Parse(dr["ID"]);
    myRow[dcName] = dr["Name"].ToString();
    dtSpecificOrders.Rows.Add(myRow);   // <-- this will add the new row
}

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.

How exactly does binary code get converted into letters?

Assuming that by "binary code" you mean just plain old data (sequences of bits, or bytes), and that by "letters" you mean characters, the answer is in two steps. But first, some background.

  • A character is just a named symbol, like "LATIN CAPITAL LETTER A" or "GREEK SMALL LETTER PI" or "BLACK CHESS KNIGHT". Do not confuse a character (abstract symbol) with a glyph (a picture of a character).
  • A character set is a particular set of characters, each of which is associated with a special number, called its codepoint. To see the codepoint mappings in the Unicode character set, see http://www.unicode.org/Public/UNIDATA/UnicodeData.txt.

Okay now here are the two steps:

  1. The data, if it is textual, must be accompanied somehow by a character encoding, something like UTF-8, Latin-1, US-ASCII, etc. Each character encoding scheme specifies in great detail how byte sequences are interpreted as codepoints (and conversely how codepoints are encoded as byte sequences).

  2. Once the byte sequences are interpreted as codepoints, you have your characters, because each character has a specific codepoint.

A couple notes:

  • In some encodings, certain byte sequences correspond to no codepoints at all, so you can have character decoding errors.
  • In some character sets, there are codepoints that are unused, that is, they correspond to no character at all.

In other words, not every byte sequence means something as text.

Android Studio : unmappable character for encoding UTF-8

I have the problem with encoding in javadoc generated by intellij idea. The solution is to add

-encoding UTF-8 -docencoding utf-8 -charset utf-8

into command line arguments!

UPDATE: more information about compilation Javadoc in Intellij IDEA see in my post

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

In laravel 7, to set current time use following:

$table->timestamp('column_name')->useCurrent();

Using strtok with a std::string

With C++17 str::string receives data() overload that returns a pointer to modifieable buffer so string can be used in strtok directly without any hacks:

#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>

int main()
{
    ::std::string text{"pop dop rop"};
    char const * const psz_delimiter{" "};
    char * psz_token{::std::strtok(text.data(), psz_delimiter)};
    while(nullptr != psz_token)
    {
        ::std::cout << psz_token << ::std::endl;
        psz_token = std::strtok(nullptr, psz_delimiter);
    }
    return EXIT_SUCCESS;
}

output

pop
dop
rop

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

Is there a replacement for unistd.h for Windows (Visual C)?

Create your own unistd.h header and include the needed headers for function prototypes.

Bootstrap - dropdown menu not working?

When i checked i saw display: none; value is in the .dropdown-menu bootstrap css class. Hence i removed it.

Git: How to remove remote origin from Git repo

you can try this out,if you want to remove origin and then add it:

git remote remove origin

then:

git remote add origin http://your_url_here

How much should a function trust another function

Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.

C# difference between == and Equals()

The == token in C# is used for two different equality-check operators. When the compiler encounters that token, it will check whether either of the types being compared has implemented an equality-operator overload for either the specific combination types being compared(*), or for a combination of types to which both types can be converted. If the compiler finds such an overload it will use it. Otherwise, if the two types are both reference types and they are not unrelated classes (either may be an interface, or they may be related classes), the compiler will regard == as a reference-comparison operator. If neither condition applies, compilation will fail.

Note that some other languages use separate tokens for the two equality-check operators. In VB.NET, for example, the = token is used within expressions solely for the overloadable equality-check operator, and Is is used as a reference-test or null-test operator. An to use = on a type which does not override the equality-check operator will fail, as will attempting to use Is for any purpose other than testing reference equality or nullity.

(*)Types generally only overload equality for comparison with themselves, but it may be useful for types to overload the equality operator for comparison with other particular types; for example, int could have (and IMHO should have but didn't) defined an equality operators for comparison with float, so that 16777217 would not report itself equal to 16777216f. As it is, since no such operator is defined, C# will promote the int to float, rounding it to 16777216f before the equality-check operator sees it; that operator then sees two equal floating-point numbers and reports them as equal, unaware of the rounding that took place.

To show a new Form on click of a button in C#

private void ButtonClick(object sender, System.EventArgs e)
{
    MyForm form = new MyForm();
    form.Show(); // or form.ShowDialog(this);
}

How to convert nanoseconds to seconds using the TimeUnit enum?

This will convert a time to seconds in a double format, which is more precise than an integer value:

double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;

Postgresql query between date ranges

From PostreSQL 9.2 Range Types are supported. So you can write this like:

SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date

this should be more efficient than the string comparison

How to perform a for-each loop over all the files under a specified path?

More compact version working with spaces and newlines in the file name:

find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

Correct way to pause a Python program

As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:

For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on Python 2.x) to prompt the user, rather than a time delay. Fast readers won't want to wait for a delay, slow readers might want more time on the delay, someone might be interrupted while reading it and want a lot more time, etc. Also, if someone uses the program a lot, he/she may become used to how it works and not need to even read the long text. It's just friendlier to let the user control how long the block of text is displayed for reading.

Disable submit button on form submit

Your code actually works on FF, it doesn't work on Chrome.

This works on FF and Chrome.

$(document).ready(function() {
        // Solution for disabling the submit temporarily for all the submit buttons.
        // Avoids double form submit.
        // Doing it directly on the submit click made the form not to submit in Chrome.
        // This works in FF and Chrome.
        $('form').on('submit', function(e){
          //console.log('submit2', e, $(this).find('[clicked=true]'));
          var submit = $(this).find('[clicked=true]')[0];
          if (!submit.hasAttribute('disabled'))
          {
            submit.setAttribute('disabled', true);
            setTimeout(function(){
              submit.removeAttribute('disabled');
            }, 1000);
          }
          submit.removeAttribute('clicked');
          e.preventDefault();
        });
        $('[type=submit]').on('click touchstart', function(){
          this.setAttribute('clicked', true);
        });
      });
    </script>

How to handle back button in activity

You should use:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
    // This will be called either automatically for you on 2.0
    // or later, or by the code above on earlier versions of the
    // platform.
    return;
}

As defined here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

If you are using an older version to compile the code, replace android.os.Build.VERSION_CODES.ECLAIR by 5 (you can add a private int named ECLAIR for example)

Dynamically load a JavaScript file

does anyone have a better way?

I think just adding the script to the body would be easier then adding it to the last node on the page. How about this:

function include(url) {
  var s = document.createElement("script");
  s.setAttribute("type", "text/javascript");
  s.setAttribute("src", url);
  document.body.appendChild(s);
}

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

Best way to change font colour halfway through paragraph?

Nornally the tag is used for that, with a change in style.

Like <p>This is my text <span class="highlight"> and these words are different</span></p>,

You set the css in the header (or rather, in a separate css file) to make your "highlight" text assume the color you wish.

(e.g.: with

<style type="text/css">
  .highlight {color: orange}

</style>

in the header. Avoid using the tag <font /> for that at all costs. :-)

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

There is already an open DataReader associated with this Command which must be closed first

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

Creating a system overlay window (always on top)

WORKING ALWAYS ON TOP IMAGE BUTTON

first of all sorry for my english

i edit your codes and make working image button that listens his touch event do not give touch control to his background elements.

also it gives touch listeners to out of other elements

button alingments are bottom and left

you can chage alingments but you need to chages cordinats in touch event in the if element

import android.annotation.SuppressLint;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

public class HepUstte extends Service {
    HUDView mView;

    @Override
    public void onCreate() {
        super.onCreate();   

        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();

        final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo_l);


        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                kangoo.getWidth(), 
                kangoo.getHeight(),
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                |WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                 PixelFormat.TRANSLUCENT);






        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);



        mView = new HUDView(this,kangoo);

        mView.setOnTouchListener(new OnTouchListener() {


            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                //Log.e("kordinatlar", arg1.getX()+":"+arg1.getY()+":"+display.getHeight()+":"+kangoo.getHeight());
                if(arg1.getX()<kangoo.getWidth() & arg1.getY()>0)
                {
                 Log.d("tiklandi", "touch me");
                }
                return false;
            }
             });


        wm.addView(mView, params);



        }



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}



@SuppressLint("DrawAllocation")
class HUDView extends ViewGroup {


    Bitmap kangoo;

    public HUDView(Context context,Bitmap kangoo) {
        super(context);

        this.kangoo=kangoo;



    }


    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);


        // delete below line if you want transparent back color, but to understand the sizes use back color
        canvas.drawColor(Color.BLACK);

        canvas.drawBitmap(kangoo,0 , 0, null); 


        //canvas.drawText("Hello World", 5, 15, mLoadPaint);

    }


    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
       // Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();

        return true;
    }
}

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

This explanation might help: http://code.google.com/p/android/issues/detail?id=8488#c80

"Fast Tips:

1) NEVER call System.gc() yourself. This has been propagated as a fix here, and it doesn't work. Do not do it. If you noticed in my explanation, before getting an OutOfMemoryError, the JVM already runs a garbage collection so there is no reason to do one again (its slowing your program down). Doing one at the end of your activity is just covering up the problem. It may causes the bitmap to be put on the finalizer queue faster, but there is no reason you couldn't have simply called recycle on each bitmap instead.

2) Always call recycle() on bitmaps you don't need anymore. At the very least, in the onDestroy of your activity go through and recycle all the bitmaps you were using. Also, if you want the bitmap instances to be collected from the dalvik heap faster, it doesn't hurt to clear any references to the bitmap.

3) Calling recycle() and then System.gc() still might not remove the bitmap from the Dalvik heap. DO NOT BE CONCERNED about this. recycle() did its job and freed the native memory, it will just take some time to go through the steps I outlined earlier to actually remove the bitmap from the Dalvik heap. This is NOT a big deal because the large chunk of native memory is already free!

4) Always assume there is a bug in the framework last. Dalvik is doing exactly what its supposed to do. It may not be what you expect or what you want, but its how it works. "

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

Though this seems to be an old question with many answers I'm posting another one, because it provides information about another approaches (looking more convenient than already mentioned), and the question itself remains actual.

First, there is a blogpost Running multiple versions of Google Chrome on Windows. It describes a method which works, but has 2 drawbacks:

  • you can't run Chrome instances of different versions simultaneously;
  • from time to time, Chrome changes format of its profile, and as long as 2 versions installed by this method share the same directory with profiles, this may produce a problem if it's happened to test 2 versions with incompatible profile formats;

Second method is a preferred one, which I'm currently using. It relies on portable versions of Chrome, which become available for every stable release at the portableapps.com.

The only requirement of this method is that existing Chrome version should not run during installation of a next version. Of course, each version must be installed in a separate directory. This way, after installation, you can run Chromes of different versions in parallel. Of course, there is a drawback in this method as well:

  • profiles in all versions live separately, so if you need to setup a profile in a specific way, you should do it twice or more times, according to the number of different Chrome versions you have installed.

How to avoid annoying error "declared and not used"

One angle not so far mentioned is tool sets used for editing the code.

Using Visual Studio Code along with the Extension from lukehoban called Go will do some auto-magic for you. The Go extension automatically runs gofmt, golint etc, and removes and adds import entries. So at least that part is now automatic.

I will admit its not 100% of the solution to the question, but however useful enough.

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

Single selection in RecyclerView

The following might be helpful for RecyclerView with Single Choice.

Three steps to do that, 1) Declare a global integer variable,

private int mSelectedItem = -1;

2) in onBindViewHolder

 mRadio.setChecked(position == mSelectedItem);

3) in onClickListener

mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mSingleCheckList.size());
mAdapter.onItemHolderClick(SingleCheckViewHolder.this);

Use ffmpeg to add text subtitles

NOTE: This solution "burns the subtitles" into the video, so that every viewer of the video will be forced to see them.

If your ffmpeg has libass enabled at compile time, you can directly do:

ffmpeg -i mymovie.mp4 -vf subtitles=subtitles.srt mysubtitledmovie.mp4

This is the case e.g. for Ubuntu 20.10, you can check if ffmpeg --version has --enable-libass.

Otherwise, you can the libass library (make sure your ffmpeg install has the library in the configuration --enable-libass).

First convert the subtitles to .ass format:

ffmpeg -i subtitles.srt subtitles.ass

Then add them using a video filter:

ffmpeg -i mymovie.mp4 -vf ass=subtitles.ass mysubtitledmovie.mp4

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

How to force R to use a specified factor level as reference in a regression?

For those looking for a dplyr/tidyverse version. Building on Gavin Simpson solution:

# Create DF
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
                 y = 4 + (1.5*x) + rnorm(100, sd = 2),
                 b = gl(5, 20))

# Change reference level
DF = DF %>% mutate(b = relevel(b, 3))

m2 <- lm(y ~ x + b, data = DF)
summary(m2)

Python ImportError: No module named wx

Just open your terminal and run this command thats for windows users pip install -U wxPython

for Ubuntu user you can use this

pip install -U \
-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
wxPython

Enumerations on PHP

What about class constants?

<?php

class YourClass
{
    const SOME_CONSTANT = 1;

    public function echoConstant()
    {
        echo self::SOME_CONSTANT;
    }
}

echo YourClass::SOME_CONSTANT;

$c = new YourClass;
$c->echoConstant();

"error: assignment to expression with array type error" when I assign a struct field (C)

typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

[----------------------------,------------------------------,----]
 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails

s1.name = "Paulo";

because the compiler knows that s1.name is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(s1.name,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with

[Paulo0----------------------,Rossi0-------------------------,0001]

strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create

[----,----,----]

This will now work because you are filling the struct with pointers.

s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this

[---4,--10,---1]

Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.

Async await in linq select

Existing code is working, but is blocking the thread.

.Select(async ev => await ProcessEventAsync(ev))

creates a new Task for every event, but

.Select(t => t.Result)

blocks the thread waiting for each new task to end.

In the other hand your code produce the same result but keeps asynchronous.

Just one comment on your first code. This line

var tasks = await Task.WhenAll(events...

will produce a single Task<TResult[]> so the variable should be named in singular.

Finally your last code make the same but is more succinct.

For reference: Task.Wait / Task.WhenAll

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

grep output to show only matching file

You can use the Unix-style -l switch – typically terse and cryptic – or the equivalent --files-with-matches – longer and more readable.

The output of grep --help is not easy to read, but it's there:

-l, --files-with-matches  print only names of FILEs containing matches

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), fmdate, 101) from sery

101 is a style argument.

Rest of 'em can be found here.

T-SQL Cast / Convert date to string

MySQL server has gone away - in exactly 60 seconds

I had this problem recently. I stumbled across an option: default_authentication_plugin

For some reason it had set it to caching_sha2_password, but updating the value to mysql_native_password fixed it for me. I'm not sure what the differences are, though, so be careful!

Hope this helps someone!

ValueError: object too deep for desired array while using convolution

np.convolve() takes one dimension array. You need to check the input and convert it into 1D.

You can use the np.ravel(), to convert the array to one dimension.

How to use the ConfigurationManager.AppSettings

ConfigurationManager.AppSettings is actually a property, so you need to use square brackets.

Overall, here's what you need to do:

SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

Excel 2010: how to use autocomplete in validation list

=OFFSET(NameList!$A$2:$A$200,MATCH(INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*",NameList!$A$2:$A$200,0)-1,0,COUNTIF($A$2:$A$200,INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*"),1)
  1. Create sheet name as Namelist. In column A fill list of data.

  2. Create another sheet name as FillData for making data validation list as you want.

  3. Type first alphabet and select, drop down menu will appear depend on you type.

psql - save results of command to a file

Approach for docker

via psql command

 docker exec -i %containerid% psql -U %user% -c '\dt' > tables.txt

or query from sql file

docker exec -i %containerid% psql -U %user% < file.sql > data.txt

Get list of passed arguments in Windows batch script (.bat)

The way to retrieve all the args to a script is here:

@ECHO off
ECHO The %~nx0 script args are...
for %%I IN (%*) DO ECHO %%I
pause

How to insert a row in an HTML table body in JavaScript

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

How to get distinct results in hibernate with joins and row-based limiting (paging)?

A slight improvement building on FishBoy's suggestion.

It is possible to do this kind of query in one hit, rather than in two separate stages. i.e. the single query below will page distinct results correctly, and also return entities instead of just IDs.

Simply use a DetachedCriteria with an id projection as a subquery, and then add paging values on the main Criteria object.

It will look something like this:

DetachedCriteria idsOnlyCriteria = DetachedCriteria.forClass(MyClass.class);
//add other joins and query params here
idsOnlyCriteria.setProjection(Projections.distinct(Projections.id()));

Criteria criteria = getSession().createCriteria(myClass);
criteria.add(Subqueries.propertyIn("id", idsOnlyCriteria));
criteria.setFirstResult(0).setMaxResults(50);
return criteria.list();

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Removing duplicate values from a PowerShell array

With my method you can completely remove duplicate values, leaving you with values from the array that only had a count of 1. It was not clear if this is what the OP actually wanted however I was unable to find an example of this solution online so here it is.

$array=@'
Bananna
Apple
Carrot
Pear
Apricot
Pear
Bananna
'@ -split '\r\n'

($array | Group-Object -NoElement | ?{$_.count -eq 1}).Name

Merge PDF files

Is it possible, using Python, to merge seperate PDF files?

Yes.

The following example merges all files in one folder to a single new PDF file:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from argparse import ArgumentParser
from glob import glob
from pyPdf import PdfFileReader, PdfFileWriter
import os

def merge(path, output_filename):
    output = PdfFileWriter()

    for pdffile in glob(path + os.sep + '*.pdf'):
        if pdffile == output_filename:
            continue
        print("Parse '%s'" % pdffile)
        document = PdfFileReader(open(pdffile, 'rb'))
        for i in range(document.getNumPages()):
            output.addPage(document.getPage(i))

    print("Start writing '%s'" % output_filename)
    with open(output_filename, "wb") as f:
        output.write(f)

if __name__ == "__main__":
    parser = ArgumentParser()

    # Add more options if you like
    parser.add_argument("-o", "--output",
                        dest="output_filename",
                        default="merged.pdf",
                        help="write merged PDF to FILE",
                        metavar="FILE")
    parser.add_argument("-p", "--path",
                        dest="path",
                        default=".",
                        help="path of source PDF files")

    args = parser.parse_args()
    merge(args.path, args.output_filename)

how to pass parameter from @Url.Action to controller function

If you are using Url.Action inside JavaScript then you can

var personId="someId";
$.ajax({
  type: 'POST',
  url: '@Url.Action("CreatePerson", "Person")',
  dataType: 'html',
  data: ({
  //insert your parameters to pass to controller
    id: personId 
  }),
  success: function() {
    alert("Successfully posted!");
  }
});

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

How can I handle the warning of file_get_contents() function in PHP?

Enable allow_url_fopen From cPanel Or WHM then Try Hope it will Fix

git pull keeping local changes

Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.

Assuming that:

  1. You're on the branch master
  2. The upstream branch is master in origin
  3. You have no uncommitted changes

.... you could do:

# Do a pull as usual, but don't commit the result:
git pull --no-commit

# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php

# Create the commit:
git commit -F .git/MERGE_MSG

You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php, this would throw them away.

How to pass multiple parameters in json format to a web service using jquery?

i have same issue and resolved by

 data: "Id1=" + id1 + "&Id2=" + id2

How to add a class to a given element?

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

You can use the substringWithRange method. It takes a start and end String.Index.

var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground"

To change the start and end index, use advancedBy(n).

var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun"

You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this:

let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))

Note: as JanX2 mentioned, this second method is not safe with unicode strings.

C# Return Different Types?

Let the method return a object from a common baseclass or interface.

public class TV:IMediaPlayer
{
   void Play(){};
}

public class Radio:IMediaPlayer
{
   void Play(){};
}

public interface IMediaPlayer
{
   void Play():
}

public class Test
{
  public void Main()
  {
     IMediaPlayer player = GetMediaPlayer();
     player.Play();
  }


  private IMediaPlayer GetMediaPlayer()
  {
     if(...)
        return new TV();
     else
        return new Radio();
  }
}

How to retry image pull in a kubernetes Pods?

In case of not having the yaml file:

kubectl get pod PODNAME -n NAMESPACE -o yaml | kubectl replace --force -f -

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Add this key in plist file...Everything will be alright..

<key>ITSAppUsesNonExemptEncryption</key>  
<false/>

Just paste before </dict></plist>

When should we call System.exit in Java

The method never returns because it's the end of the world and none of your code is going to be executed next.

Your application, in your example, would exit anyway at the same spot in the code, but, if you use System.exit. you have the option of returning a custom code to the enviroment, like, say

System.exit(42);

Who is going to make use of your exit code? A script that called the application. Works in Windows, Unix and all other scriptable environments.

Why return a code? To say things like "I did not succeed", "The database did not answer".

To see how to get the value od an exit code and use it in a unix shell script or windows cmd script, you might check this answer on this site

Can Android Studio be used to run standard Java projects?

EDIT: many moon after this question was asked, yes, now apparently you can.

No, but it's based on Intellij IDEA.

The community version of that is free for download but it doesn't support most things requiring an external database or application server. The line for Java is pretty much that JavaSE code can happily use Community.

If you want that (or are using JavaEE) then you either need the Ultimate version, which isn't free, or the EAP of the next version which is usually good for a month until they release another.

Basically it works like this

Android Studio is just Android the Android Stuff from IDEA 13 Community...

...which will be free, and is anything from IDEA 13 Ultimate...

...that doesn't require a database or app server.

http://www.jetbrains.com/idea/

IDEA 12 Community doesn't have the ability to import the gradilized project and it won't, so while you can do Android development in it now (I do), don't expect it to have the same features as Android Studio. There's a lot of good new Android stuff in it, that's going into 13.

Show/hide image with JavaScript

HTML

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";
}

CSS:

#theImage { display:none; }

Reading data from a website using C#

Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

From the answers for the question System.Net.WebClient unreasonably slow

Try setting Proxy = null;

WebClient wc = new WebClient(); wc.Proxy = null;

Credit to Alex Burtsev

What generates the "text file busy" message in Unix?

If you are running the .sh from a ssh connection with a tool like MobaXTerm, and if said tool has an autosave utility to edit remote file from local machine, that will lock the file.

Closing and reopening the SSH session solves it.

How do I vertical center text next to an image in html/css?

There are to ways: Use the attribute of the image tag align="absmiddle" or locate the image and the text in a container DIV or TD in a table and use

style="vertical-align:middle"

Java ArrayList replace at specific index

Use the set() method: see doc

arraylist.set(index,newvalue);

Accessing an SQLite Database in Swift

Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift

Features:

  • An API that will look familiar to users of ccgus/fmdb

  • A low-level SQLite API that leverages the Swift standard library

  • A pretty Swift query interface for SQL-allergic developers

  • Support for the SQLite WAL mode, and concurrent database access for extra performance

  • A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations

  • Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.

  • Database Migrations

  • Speed: https://github.com/groue/GRDB.swift/wiki/Performance

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can use the :before pseudo-selector to insert content in front of the list item. You can find an example on Quirksmode, at http://www.quirksmode.org/css/beforeafter.html. I use this to insert giant quotes around blockquotes...

HTH.

angular.service vs angular.factory

TL;DR

1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory.

app.controller('myFactoryCtrl', function($scope, myFactory){
  $scope.artist = myFactory.getArtist();
});

app.factory('myFactory', function(){
  var _artist = 'Shakira';
  var service = {};

  service.getArtist = function(){
    return _artist;
  }

  return service;
});


2) When you’re using Service, Angular instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.

app.controller('myServiceCtrl', function($scope, myService){
  $scope.artist = myService.getArtist();
});

app.service('myService', function(){
  var _artist = 'Nelly';
  this.getArtist = function(){
    return _artist;
  }
});



Non TL;DR

1) Factory
Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below.

app.factory('myFactory', function(){
  var service = {};
  return service;
});

Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller.

Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed.

app.factory('myFactory', function($http, $q){
  var service = {};
  var baseUrl = 'https://itunes.apple.com/search?term=';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
   _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK';
    return _finalUrl
  }

  return service;
});

Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later.

  • baseUrl is the base URL that the iTunes API requires
  • _artist is the artist we wish to lookup
  • _finalUrl is the final and fully built URL to which we’ll make the call to iTunes makeUrl is a function that will create and return our iTunes friendly URL.

Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ we’ll be able to directly use in whichever controller we pass ‘myFactory’ into.

We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in Angular, I highly recommend doing a deep dive on them.

Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’.

app.factory('myFactory', function($http, $q){
  var service = {};
  var baseUrl = 'https://itunes.apple.com/search?term=';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;
  }

  service.setArtist = function(artist){
    _artist = artist;
  }

  service.getArtist = function(){
    return _artist;
  }

  service.callItunes = function(){
    makeUrl();
    var deferred = $q.defer();
    $http({
      method: 'JSONP',
      url: _finalUrl
    }).success(function(data){
      deferred.resolve(data);
    }).error(function(){
      deferred.reject('There was an error')
    })
    return deferred.promise;
  }

  return service;
});

Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes).

app.controller('myFactoryCtrl', function($scope, myFactory){
  $scope.data = {};
  $scope.updateArtist = function(){
    myFactory.setArtist($scope.data.artist);
  };

  $scope.submitArtist = function(){
    myFactory.callItunes()
      .then(function(data){
        $scope.data.artistData = data;
      }, function(data){
        alert(data);
      })
  }
});

In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object that are coming from data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’. All of our logic and persistent data is located in our service, not in our controller.

2) Service
Perhaps the biggest thing to know when dealing with creating a Service is that that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of you with a limited background in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service.

To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same.

First let’s create our Constructor.

var Person = function(name, age){
  this.name = name;
  this.age = age;
}

This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object.

Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’.

Person.prototype.sayName = function(){
  alert('My name is ' + this.name);
}

Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name.

Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function.

var tyler = new Person('Tyler', 23);
tyler.sayName(); //alerts 'My name is Tyler'

So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this.

var Person = function(name, age){
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function(){
  alert('My name is ' + this.name);
}
var tyler = new Person('Tyler', 23);
tyler.sayName(); //alerts 'My name is Tyler'

Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object - that’s because it is. So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then call it. Wait a minute, I don’t see it here - all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”.

Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes.

var Person = function(name, age){
  //The line below this creates an obj object that will delegate to the person's prototype on failed lookups.
  //var obj = Object.create(Person.prototype);

  //The line directly below this sets 'this' to the newly created object
  //this = obj;

  this.name = name;
  this.age = age;

  //return this;
}

Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in Angular should be easier to understand.

The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action.

Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work.

First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example.

app.service('myService', function($http, $q){
  var baseUrl = 'https://itunes.apple.com/search?term=';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;
  }
});

Now, we’ll attach all of our methods that will be available in our controller to ‘this’.

app.service('myService', function($http, $q){
  var baseUrl = 'https://itunes.apple.com/search?term=';
  var _artist = '';
  var _finalUrl = '';

  var makeUrl = function(){
    _artist = _artist.split(' ').join('+');
    _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
    return _finalUrl;
  }

  this.setArtist = function(artist){
    _artist = artist;
  }

  this.getArtist = function(){
    return _artist;
  }

  this.callItunes = function(){
    makeUrl();
    var deferred = $q.defer();
    $http({
      method: 'JSONP',
      url: _finalUrl
    }).success(function(data){
      deferred.resolve(data);
    }).error(function(){
      deferred.reject('There was an error')
    })
    return deferred.promise;
  }

});

Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller).

app.controller('myServiceCtrl', function($scope, myService){
  $scope.data = {};
  $scope.updateArtist = function(){
    myService.setArtist($scope.data.artist);
  };

  $scope.submitArtist = function(){
    myService.callItunes()
      .then(function(data){
        $scope.data.artistData = data;
      }, function(data){
        alert(data);
      })
  }
});

Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in Angular.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

How to overwrite styling in Twitter Bootstrap

You can just make sure your css file parses AFTER boostrap.css , like so:

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/myFile.css" rel="stylesheet">

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

how to toggle attr() in jquery

For readonly/disabled and other attributes with true/false values

$(':submit').attr('disabled', function(_, attr){ return !attr});

jQuery issue in Internet Explorer 8

The solution is to upgrade to the latest version of jQuery. I had the exact same problem and upgraded to 1.4.2 and it all works fine again in IE8.

Seems to be totally backwards-compatible with all the jQuery 1.3.2 stuff I did as well so no complaints here!

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I put this for future visitors:

if you are receiving the error on creating an Exception object, then the cause of it probably is a lack of definition for what() virtual function.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Simply change,

dispatch_async(kBgQueue, ^{
     NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:   [NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
     dispatch_async(dispatch_get_main_queue(), ^{
        cell.poster.image = [UIImage imageWithData:imgData];
     });
 });

Into

    dispatch_async(kBgQueue, ^{
         NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:   [NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
         cell.poster.image = [UIImage imageWithData:imgData];
         dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
         });
     });

How to increment a number by 2 in a PHP For Loop

You should do it like this:

 for ($i=1; $i <=10; $i+=2) 
{ 
    echo $i.'<br>';
}

"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"

Sum columns with null values in oracle

In some cases, nvl(sum(column_name),0) is also required. You may want to consider your scenarios.

For example, I am trying to fetch the sum of a particular column, from a particular table based on certain conditions. Based on the conditions,

  1. one or more rows exist in the table. In this case I want the sum.
  2. rows do not exist. In this case I want 0.

If you use sum(nvl(column_name,0)) here, it would give you null. What you might want is nvl(sum(column_name),0).

This may be required especially when you are passing this result to, say, java, have the datatype as number there because then this will not require special null handling.

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

Loop through childNodes

Couldn't resist to add another method, using childElementCount. It returns the number of child element nodes from a given parent, so you can loop over it.

for(var i=0, len = parent.childElementCount ; i < len; ++i){
    ... do something with parent.children[i]
    }

How to create a new variable in a data.frame based on a condition?

If you have a very limited number of levels, you could try converting y into factor and change its levels.

> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
  x y    w
1 1 1 good
2 2 4 fair
3 4 5  bad

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

Replace a newline in TSQL

In SQL Server 2017 & later, use Trim

Select Trim(char(10) + char(13) from @str)
  1. it trims on starting and ending, not in the middle
  2. the order of \r and \n does not matter

I use it to trim special characters for a file name

Select Trim(char(10) + char(13) + ' *<>' from @fileName)

MySQL > Table doesn't exist. But it does (or it should)

I don't know the reason but in my case I solved just disabling and enabling the foreign keys check

SET FOREIGN_KEY_CHECKS=0;
SET FOREIGN_KEY_CHECKS=1;

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

For normal MySQL, just connect as the 'root' administrative super user, and issue the command:

FLUSH HOSTS

Even in the case of too many connections, MySQL should be keeping a connection in reserve so that a super user can connect.

The mysqladmin client generally connects as root anyway and issues the above SQL.

Reference alias (calculated in SELECT) in WHERE clause

You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated. Two workarounds:

SELECT BalanceDue FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices
) AS x
WHERE BalanceDue > 0;

Or just repeat the expression:

SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE  (InvoiceTotal - PaymentTotal - CreditTotal)  > 0;

I prefer the latter. If the expression is extremely complex (or costly to calculate) you should probably consider a computed column (and perhaps persisted) instead, especially if a lot of queries refer to this same expression.

PS your fears seem unfounded. In this simple example at least, SQL Server is smart enough to only perform the calculation once, even though you've referenced it twice. Go ahead and compare the plans; you'll see they're identical. If you have a more complex case where you see the expression evaluated multiple times, please post the more complex query and the plans.

Here are 5 example queries that all yield the exact same execution plan:

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE LEN(name) + column_id > 30;

SELECT x FROM (
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE column_id + LEN(name) > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE LEN(name) + column_id > 30;

Resulting plan for all five queries:

enter image description here

How to create a number picker dialog?

For kotlin lovers.

fun numberPickerCustom() {
    val d = AlertDialog.Builder(context)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.number_picker_dialog, null)
    d.setTitle("Title")
    d.setMessage("Message")
    d.setView(dialogView)
    val numberPicker = dialogView.findViewById<NumberPicker>(R.id.dialog_number_picker)
    numberPicker.maxValue = 15
    numberPicker.minValue = 1
    numberPicker.wrapSelectorWheel = false
    numberPicker.setOnValueChangedListener { numberPicker, i, i1 -> println("onValueChange: ") }
    d.setPositiveButton("Done") { dialogInterface, i ->
        println("onClick: " + numberPicker.value)       
        }
    d.setNegativeButton("Cancel") { dialogInterface, i -> }
    val alertDialog = d.create()
    alertDialog.show()
}

and number_picker_dialog.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal">

    <NumberPicker
        android:id="@+id/dialog_number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

How to get thread id of a pthread in linux c program?

pthread_self() function will give the thread id of current thread.

pthread_t pthread_self(void);

The pthread_self() function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np() to return an integral identifier for the thread.

NOTE:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

is significantly faster than these calls, but provides the same behavior.

pthread_id_np_t   tid;
pthread_t         self;
self = pthread_self();
pthread_getunique_np(&self, &tid);

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

also, with wmode=opaque and with IE, the Flash gets the keyboard events, but also the html page receives them, so it can't be use for something like embedding a flash game. Very annoying

Array to String PHP?

You can use the PHP string function implode()

Like,

<?php
  $sports=$_POST['sports'];;
  $festival=$_POST['festival'];
  $food=$_POST['food'];
  $array=[$sports,$festival,$food];
  $string=implode('|',$array);
  echo $string;
?>

If, for example, $sports='football'; $festival='janmastami'; $food='biriyani';

Then output would be:

football|janmastami|biriyani

For more details on PHP implode() function refer to w3schools

UICollectionView Self Sizing Cells with Auto Layout

A few key changes to Daniel Galasko's answer fixed all my problems. Unfortunately, I don't have enough reputation to comment directly (yet).

In step 1, when using Auto Layout, simply add a single parent UIView to the cell. EVERYTHING inside the cell must be a subview of the parent. That answered all of my problems. While Xcode adds this for UITableViewCells automatically, it doesn't (but it should) for UICollectionViewCells. According to the docs:

To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the contentView property. Do not directly add subviews to the cell itself.

Then skip step 3 entirely. It isn't needed.

Number of processors/cores in command line

On newer kernels you could also possibly use the the /sys/devices/system/cpu/ interface to get a bit more information:

$ ls /sys/devices/system/cpu/
cpu0  cpufreq  kernel_max  offline  possible  present  release
cpu1  cpuidle  modalias    online   power     probe    uevent
$ cat /sys/devices/system/cpu/kernel_max 
255
$ cat /sys/devices/system/cpu/offline 
2-63
$ cat /sys/devices/system/cpu/possible 
0-63
$ cat /sys/devices/system/cpu/present 
0-1
$ cat /sys/devices/system/cpu/online 
0-1

See the official docs for more information on what all these mean.

How to check which locks are held on a table

To add to the other responses, sp_lock can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with sp_who2 to quickly zero in on locking problems.

There are multiple different versions of "friendlier" sp_lock procedures available online, depending on the version of SQL Server in question.

In your case, for SQL Server 2005, sp_lock is still available, but deprecated, so it's now recommended to use the sys.dm_tran_locks view for this kind of thing. You can find an example of how to "roll your own" sp_lock function here.

Why do people say that Ruby is slow?

Obviously, talking about speed Ruby loses. Even though benchmark tests suggest that Ruby is not so much slower than PHP. But in return, you are getting easy-to-maintain DRY code, the best out of all frameworks in various languages.

For a small project, you wont feel any slowness (I mean until like <50K users) given that no complex calculations are used in the code, just the mainstream stuff.

For a bigger project, paying for resources pays off and is cheaper than developer wages. In addition, writing code on RoR turns out to be much faster than any other.

In 2014 this magnitude of speed difference you're talking about is for most websites insignificant.

Send raw ZPL to Zebra printer via USB

ZPL is the correct way to go. In most cases it is correct to use a driver that abstracts to GDI commands; however Zebra label printers are a special case. The best way to print to a Zebra printer is to generate ZPL directly. Note that the actual printer driver for a Zebra printer is a "plain text" printer - there is not a "driver" that could be updated or changed in the sense we think of most printers having drivers. It's just a driver in the absolute minimalist sense.

Angular Material: mat-select not selecting default

Try this!

this.selectedObjectList = [{id:1}, {id:2}, {id:3}]
this.allObjectList = [{id:1}, {id:2}, {id:3}, {id:4}, {id:5}]
let newList = this.allObjectList.filter(e => this.selectedObjectList.find(a => e.id == a.id))
this.selectedObjectList = newList

Moment.js - tomorrow, today and yesterday

You can customize the way that both the .fromNow and the .calendar methods display dates using moment.updateLocale. The following code will change the way that .calendar displays as per the question:

moment.updateLocale('en', {
    calendar : {
        lastDay : '[Yesterday]',
        sameDay : '[Today]',
        nextDay : '[Tomorrow]',
        lastWeek : '[Last] dddd',
        nextWeek : '[Next] dddd',
        sameElse : 'L'
    }
});

Based on the question, it seems like the .calendar method would be more appropriate -- .fromNow wants to have a past/present prefix/suffix, but if you'd like to find out more you can read the documentation at http://momentjs.com/docs/#/customization/relative-time/.

To use this in only one place instead of overwriting the locales, pass a string of your choice as the first argument when you define the moment.updateLocale and then invoke the calendar method using that locale (eg. moment.updateLocale('yesterday-today').calendar( /* moment() or whatever */ ))

EDIT: Moment ^2.12.0 now has the updateLocale method. updateLocale and locale appear to be functionally the same, and locale isn't yet deprecated, but updated the answer to use the newer method.