Programs & Examples On #Storing information

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

How to set Meld as git mergetool

I think that mergetool.meld.path should point directly to the meld executable. Thus, the command you want is:

git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld

Python requests - print entire http request (raw)?

A fork of @AntonioHerraizS answer (HTTP version missing as stated in comments)


Use this code to get a string representing the raw HTTP packet without sending it:

import requests


def get_raw_request(request):
    request = request.prepare() if isinstance(request, requests.Request) else request
    headers = '\r\n'.join(f'{k}: {v}' for k, v in request.headers.items())
    body = '' if request.body is None else request.body.decode() if isinstance(request.body, bytes) else request.body
    return f'{request.method} {request.path_url} HTTP/1.1\r\n{headers}\r\n\r\n{body}'


headers = {'User-Agent': 'Test'}
request = requests.Request('POST', 'https://stackoverflow.com', headers=headers, json={"hello": "world"})
raw_request = get_raw_request(request)
print(raw_request)

Result:

POST / HTTP/1.1
User-Agent: Test
Content-Length: 18
Content-Type: application/json

{"hello": "world"}

Can also print the request in the response object

r = requests.get('https://stackoverflow.com')
raw_request = get_raw_request(r.request)
print(raw_request)

Call method in directive controller from other controller

You can also use events to trigger the Popdown.

Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcasts 'success' and 'error' events down the scope chain:

$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error   = function(msg) { $scope.$broadcast('error', msg); };

The Popdown module then registers handler functions for these events, e.g:

$scope.$on('success', function(event, msg) {
    $scope.status = 'success';
    $scope.message = msg;
    $scope.toggleDisplay();
});

This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.

ssh: check if a tunnel is alive

These are more detailed steps to test or troubleshoot an SSH tunnel. You can use some of them in a script. I'm adding this answer because I had to troubleshoot the link between two applications after they stopped working. Just grepping for the ssh process wasn't enough, as it was still there. And I couldn't use nc -z because that option wasn't available on my incantation of netcat.

Let's start from the beginning. Assume there is a machine, which will be called local with IP address 10.0.0.1 and another, called remote, at 10.0.3.12. I will prepend these hostnames, to the commands below, so it's obvious where they're being executed.

The goal is to create a tunnel that will forward TCP traffic from the loopback address on the remote machine on port 123 to the local machine on port 456. This can be done with the following command, on the local machine:

local:~# ssh -N -R 123:127.0.0.1:456 10.0.3.12

To check that the process is running, we can do:

local:~# ps aux | grep ssh

If you see the command in the output, we can proceed. Otherwise, check that the SSH key is installed in the remote. Note that excluding the username before the remote IP, makes ssh use the current username.

Next, we want to check that the tunnel is open on the remote:

remote:~# netstat | grep 10.0.0.1

We should get an output similar to this:

tcp  0  0  10.0.3.12:ssh  10.0.0.1:45988  ESTABLISHED

Would be nice to actually see some data going through from the remote to the host. This is where netcat comes in. On CentOS it can be installed with yum install nc.

First, open a listening port on the local machine:

local:~# nc -l 127.0.0.1:456

Then make a connection on the remote:

remote:~# nc 127.0.0.1 123

If you open a second terminal to the local machine, you can see the connection. Something like this:

local:~# netstat | grep 456
tcp  0  0 localhost.localdom:456 localhost.localdo:33826 ESTABLISHED
tcp  0  0 localhost.localdo:33826 localhost.localdom:456 ESTABLISHED

Better still, go ahead and type something on the remote:

remote:~# nc 127.0.0.1 8888
Hallo?
anyone there?

You should see this being mirrored on the local terminal:

local:~# nc -l 127.0.0.1:456
Hallo?
anyone there?

The tunnel is working! But what if you have an application, called appname, which is supposed to be listening on port 456 on the local machine? Terminate nc on both sides then run your application. You can check that it's listening on the correct port with this:

local:~# netstat -tulpn | grep LISTEN | grep appname
tcp  0  0  127.0.0.1:456  0.0.0.0:* LISTEN  2964/appname

By the way, running the same command on the remote should show sshd listening on port 127.0.0.1:123.

How can I replace text with CSS?

Obligatory: This is a hack: CSS isn't the right place to do this, but in some situations - eg, you have a third party library in an iframe that can only be customized by CSS - this kind of hack is the only option.

You can replace text through CSS. Let's replace a green button that has the word 'hello' with a red button that has the word 'goodbye', using CSS.

Before:

enter image description here

After:

enter image description here

See http://jsfiddle.net/ZBj2m/274/ for a live demo:

Here's our green button:

<button>Hello</button>

button {
  background-color: green;
  color: black;
  padding: 5px;
}

Now let's hide the original element, but add another block element afterwards:

button {
  visibility: hidden;
}
button:after {
  content:'goodbye'; 
  visibility: visible;
  display: block;
  position: absolute;
  background-color: red;
  padding: 5px;
  top: 2px;
}

Note:

  • We explicitly need to mark this as a block element, 'after' elements are inline by default
  • We need to compensate for the original element by adjusting the pseudo-element's position.
  • We must hide the original element and display the pseudo element using visibility. Note display: none on the original element doesn't work.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:

http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.

You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!

Hope it helps :)

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

phpmyadmin logs out after 1440 secs

To set permanently cookie you need to follow some steps

Goto->/etc/phpmyadmin/config.inc.php file

add this code

$cfg['LoginCookieValidity'] = <cookie expiration time in seconds > 

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

You would do it like this:

std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
    foo_value = std::stoi(arg.substr(prefix.size()));

Looking for a lib such as Boost.ProgramOptions that does this for you is also a good idea.

Android intent for playing video?

From now onwards after API 24, Uri.parse(filePath) won't work. You need to use this

final File videoFile = new File("path to your video file");
Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
startActivity(intent);

But before using this you need to understand how file provider works. Go to official document link to understand file provider better.

Make column fixed position in bootstrap

Use this, works for me and solve problems with small screen.

<div class="row">
    <!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
    <div class="col-lg-3 device-lg visible-lg">
       <div class="affix">
           fixed position 
        </div>
    </div>
    <div class="col-lg-9">
    <!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
    <div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
       <div>
           NO fixed position
        </div>
    </div>
       Normal data enter code here
    </div>
</div>

Address already in use: JVM_Bind

My answer does 100% fit to this problem, but I want to document my solution and the trap behind it, since the Exception is the same.

My port was always in use testing a Jetty in a Junit testcase. Problem was Google's code pro on Eclipse, which, I guess, was testing in the background and thus starting jetty before me all the time. Workaround: let Eclipse open *.java files always w/ the Java editor instead of Google's Junit editor. That seems to help.

Bootstrap col-md-offset-* not working

For now, If you want to move a column over just 4 column units for instance, I would suggest to use just a dummy placeholder like in my example below

<div class="row">
      <div class="col-md-4">Offset 4 column</div>
      <div class="col-md-8">
            //content
      </div>
</div>

Need to list all triggers in SQL Server database with table name and table's schema

SELECT
   ServerName   = @@servername,
   DatabaseName = db_name(),
   SchemaName   = isnull( s.name, '' ),
   TableName    = isnull( o.name, 'DDL Trigger' ),
   TriggerName  = t.name, 
   Defininion   = object_definition( t.object_id )

FROM sys.triggers t
   LEFT JOIN sys.all_objects o
      ON t.parent_id = o.object_id
   LEFT JOIN sys.schemas s
      ON s.schema_id = o.schema_id
ORDER BY 
   SchemaName,
   TableName,
   TriggerName

How to Convert an int to a String?

You have two options:

1) Using String.valueOf() method:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2) adding an empty string:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

Casting is not an option, will throw a ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

grep --ignore-case --only

It should be a problem in your version of grep.

Your test cases are working correctly here on my machine:

$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC

And my version is:

$ grep --version
grep (GNU grep) 2.10

How do I list the symbols in a .so file

Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.

HTTP POST with URL query parameters -- good idea or not?

If your action is not idempotent, then you MUST use POST. If you don't, you're just asking for trouble down the line. GET, PUT and DELETE methods are required to be idempotent. Imagine what would happen in your application if the client was pre-fetching every possible GET request for your service – if this would cause side effects visible to the client, then something's wrong.

I agree that sending a POST with a query string but without a body seems odd, but I think it can be appropriate in some situations.

Think of the query part of a URL as a command to the resource to limit the scope of the current request. Typically, query strings are used to sort or filter a GET request (like ?page=1&sort=title) but I suppose it makes sense on a POST to also limit the scope (perhaps like ?action=delete&id=5).

Swap two items in List<T>

List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.

your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.

Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

Cannot read property 'length' of null (javascript)

The proper test is:

if (capital != null && capital.length < 1) {

This ensures that capital is always non null, when you perform the length check.

Also, as the comments suggest, capital is null because you never initialize it.

What is an attribute in Java?

An abstract class is a type of class that can only be used as a base class for another class; such thus cannot be instantiated. To make a class abstract, the keyword abstract is used. Abstract classes may have one or more abstract methods that only have a header line (no method body). The method header line ends with a semicolon (;). Any class that is derived from the base class can define the method body in a way that is consistent with the header line using all the designated parameters and returning the correct data type (if the return type is not void). An abstract method acts as a place holder; all derived classes are expected to override and complete the method.

Example in Java

abstract public class Shape

{

double area;

public abstract double getArea();

}

(How) can I count the items in an enum?

I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small

enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }

in this about examples the result would create a array of 3 items when you need an array of 5 items

enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }

in this about examples the result would create a array of 301 items when you need an array of 5 items

The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know

passing form data to another HTML page

Using pure JavaScript.It's very easy using local storage.
The first page form:

_x000D_
_x000D_
function getData()
{
    //gettting the values
    var email = document.getElementById("email").value;
    var password= document.getElementById("password").value; 
    var telephone= document.getElementById("telephone").value; 
    var mobile= document.getElementById("mobile").value; 
    //saving the values in local storage
    localStorage.setItem("txtValue", email);
    localStorage.setItem("txtValue1", password);
    localStorage.setItem("txtValue2", mobile);
    localStorage.setItem("txtValue3", telephone);   
}
_x000D_
  input{
    font-size: 25px;
  }
  label{
    color: rgb(16, 8, 46);
    font-weight: bolder;
  }
  #data{

  }
_x000D_
   <fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
        <form action="action.html">
        <legend>Sign Up Form</legend>
        <label>Email:<br />
        <input type="text" name="email" id="email"/></label><br />
        <label>Password<br />
        <input type="text" name="password" id="password"/></label><br>
        <label>Mobile:<br />
        <input type="text" name="mobile" id="mobile"/></label><br />
        <label>Telephone:<br />
        <input type="text" name="telephone" id="telephone"/></label><br> 
        <input type="submit" value="Submit" onclick="getData()">
    </form>
    </fieldset>
_x000D_
_x000D_
_x000D_

This is the second page:

_x000D_
_x000D_
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
_x000D_
 <div style=" font-size: 30px;  color: rgb(32, 7, 63); text-align: center;">
    <div style="font-size: 40px; color: red; margin: 0 auto;">
        Here's Your data
    </div>
    The Email is equal to: <span id="data"> Email</span><br> 
    The Password is equal to <span id="data1"> Password</span><br>
    The Mobile is equal to <span id="data2"> Mobile</span><br>
    The Telephone is equal to <span id="data3"> Telephone</span><br>
    </div>
_x000D_
_x000D_
_x000D_

Important Note:

Please don't forget to give name "action.html" to the second html file to work the code properly. I can't use multiple pages in a snippet, that's why its not working here try in the browser in your editor where it will surely work.

tar: file changed as we read it

Although its very late but I recently had the same issue.

Issue is because dir . is changing as xyz.tar.gz is created after running the command. There are two solutions:

Solution 1: tar will not mind if the archive is created in any directory inside .. There can be reasons why can't create the archive outside the work space. Worked around it by creating a temporary directory for putting the archive as:

mkdir artefacts
tar -zcvf artefacts/archive.tar.gz --exclude=./artefacts .
echo $?
0

Solution 2: This one I like. create the archive file before running tar:

touch archive.tar.gz
tar --exclude=archive.tar.gz -zcvf archive.tar.gz .
echo $?
0

How do you replace all the occurrences of a certain character in a string?

I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.

def remove_chars(line):
    line7=line[7].translate(None,'abcd')
    return line[:7]+[line7]+line[8:]

line= ['ad','da','sdf','asd',
        '3424','342sfas','asdfaf','sdfa',
        'afase']
print line[7]
line = remove_chars(line)
print line[7]

implement time delay in c

Write this code :

void delay(int x)
{   int i=0,j=0;
    for(i=0;i<x;i++){for(j=0;j<200000;j++){}}
}

int main()
{
    int i,num;

    while(1) {

    delay(500);

    printf("Host name");
    printf("\n");}

}

WPF Binding StringFormat Short Date String

Some DateTime StringFormat samples I found useful. Lifted from C# Examples

DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

NodeJS/express: Cache and 304 status code

Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.

The empty page can be easily solved by using Shift key+reload button at the browser.

The empty page can be a result of:

  • a bug in your code
  • while testing you served an empty page (you can't remember) that is cached by the browser
  • a bug in Safari (if so, please report it to Apple and don't try to fix it yourself)

Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.

Setting Inheritance and Propagation flags with set-acl and powershell

I think your answer can be found on this page. From the page:

This Folder, Subfolders and Files:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

Preprocessing in scikit learn - single sample - Depreciation warning

Just listen to what the warning is telling you:

Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.

For your example type(if you have more than one feature/column):

temp = temp.reshape(1,-1) 

For one feature/column:

temp = temp.reshape(-1,1)

How do I do logging in C# without using 3rd party libraries?

I would rather not use any outside frameworks like log4j.net.

Why? Log4net would probably address most of your requirements. For example check this class: RollingFileAppender.

Log4net is well documented and there are thousand of resources and use cases on the web.

Switch to another branch without changing the workspace files

It sounds like you made changes, committing them to master along the way, and now you want to combine them into a single commit.

If so, you want to rebase your commits, squashing them into a single commit.

I'm not entirely sure of what exactly you want, so I'm not going to tempt you with a script. But I suggest you read up on git rebase and the options for "squash"ing, and try a few things out.

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

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

npm install hangs

I had the same problem. The reason - wrong proxy was configured and because of that npm was unable to download packages.

So your best bet is to the see the output of

$ npm install --verbose

and identify the problem. If you have never configured proxy, then possible causes can be

  • Very outdated npm version.
  • Some problem with your internet connection.
  • Permissions are not sufficient for npm to modify files.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Is there any way to do HTTP PUT in python

A more proper way of doing this with requests would be:

import requests

payload = {'username': 'bob', 'email': '[email protected]'}

try:
    response = requests.put(url="http://somedomain.org/endpoint", data=payload)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(e)
    raise

This raises an exception if there is an error in the HTTP PUT request.

How do I add the Java API documentation to Eclipse?

For OpenJDK 8 on Linux see: https://askubuntu.com/questions/755853/how-to-install-jdk-sources

The way that worked for me is:

  • The default src.zip is a symbolic link pointing to a non-existing folder ...
  • sudo apt-get install openjdk-8-source this adds this folder
  • locate "src.zip"
  • Eclipse: Window --> Preferences --> Java --> "Installed JREs", edit and point to src.zip (or open any JRE class like for example HashMap and attach source)

You should now see the JavaDoc when opening JRE classes via Ctrl+Shift+t, previously this was not possible, Eclipse may have got a docs from the default URL on mouse over methods but this requires a stable internet connection.

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

How to add font-awesome to Angular 2 + CLI project

This post describes how to integrate Fontawesome 5 into Angular 6 (Angular 5 and previous versions will also work, but then you have to adjust my writings)

Option 1: Add the css-Files

Pro: Every icon will be included

Contra: Every icon will be included (bigger app size because all fonts are included)

Add the following package:

npm install @fortawesome/fontawesome-free-webfonts

Afterwards add the following lines to your angular.json:

"app": {
....
"styles": [
....
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fontawesome.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-regular.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-brands.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-solid.css"
],
...    
}

Option 2: Angular package

Pro: Smaller app size

Contra: You have to include every icon you want to use seperatly

Use the FontAwesome 5 Angular package:

npm install @fortawesome/angular-fontawesome

Just follow their documentation to add the icons. They use the svg-icons, so you only have to add the svgs / icons, you really use.

adding multiple entries to a HashMap at once in one statement

Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main (String[] args){
        HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");

        System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
    }

    private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
        HashMap<String, Integer> returnVar = new HashMap<String, Integer>();

        String currentStr = str;
        Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");

        // Parse all elements in the given string.
        boolean thereIsMore = true;
        while (thereIsMore){
            Matcher matcher = pattern1.matcher(currentStr);
            if (matcher.find()) {
                returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                currentStr = matcher.group(3);
            }
            else{
                thereIsMore = false;
            }
        }

        // Validate that all elements in the given string were parsed properly
        if (currentStr.length() > 0){
            System.out.println("WARNING: Problematic string format. given String: " + str);
        }

        return returnVar;
    }
}

How do I get the current date in Cocoa

There is no difference in the location of the asterisk (at in C, which Obj-C is based on, it doesn't matter). It is purely preference (style).

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

Java NIO FileChannel versus FileOutputstream performance / usefulness

If the thing you want to compare is performance of file copying, then for the channel test you should do this instead:

final FileInputStream inputStream = new FileInputStream(src);
final FileOutputStream outputStream = new FileOutputStream(dest);
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();

This won't be slower than buffering yourself from one channel to the other, and will potentially be massively faster. According to the Javadocs:

Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

Simplest JQuery validation rules example

The input in the markup is missing "type", the input (text I assume) has the attribute name="name" and ID="cname", the provided code by Ayo calls the input named "cname"* where it should be "name".

Where are the Android icon drawables within the SDK?

You can find android drawables icons from the example path below...

C:\Users\User\AppData\Local\Android\sdk\platforms\android-25\data\res\drawable-xhdpi

imagecreatefromjpeg and similar functions are not working in PHP

As mentioned before, you might need GD library installed.

On a shell, check your php version first:
php -v

Then install accordingly. In my system (Linux-Ubuntu) it's php version 7.0:
sudo apt-get install php7.0-gd

Restart your webserver:
systemctl restart apache2

You should now have GD library installed and enabled.

Wrapping long text without white space inside of a div

I have found something strange here about word-wrap only works with width property of CSS properly.

_x000D_
_x000D_
#ONLYwidth {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#wordwrapWITHOUTWidth {_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
#wordwrapWITHWidth {_x000D_
  width: 200px;_x000D_
  word-wrap: break-word;_x000D_
}
_x000D_
<b>This is the example of word-wrap only using width property</b>_x000D_
<p id="ONLYwidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap without width property</b>_x000D_
<p id="wordwrapWITHOUTWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap with width property</b>_x000D_
<p id="wordwrapWITHWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>
_x000D_
_x000D_
_x000D_

Here is a working demo that I have prepared about it. http://jsfiddle.net/Hss5g/2/

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Get a filtered list of files in a directory

Preliminary code

import glob
import fnmatch
import pathlib
import os

pattern = '*.py'
path = '.'

Solution 1 - use "glob"

# lookup in current dir
glob.glob(pattern)

In [2]: glob.glob(pattern)
Out[2]: ['wsgi.py', 'manage.py', 'tasks.py']

Solution 2 - use "os" + "fnmatch"

Variant 2.1 - Lookup in current dir

# lookup in current dir
fnmatch.filter(os.listdir(path), pattern)

In [3]: fnmatch.filter(os.listdir(path), pattern)
Out[3]: ['wsgi.py', 'manage.py', 'tasks.py']

Variant 2.2 - Lookup recursive

# lookup recursive
for dirpath, dirnames, filenames in os.walk(path):

    if not filenames:
        continue

    pythonic_files = fnmatch.filter(filenames, pattern)
    if pythonic_files:
        for file in pythonic_files:
            print('{}/{}'.format(dirpath, file))

Result

./wsgi.py
./manage.py
./tasks.py
./temp/temp.py
./apps/diaries/urls.py
./apps/diaries/signals.py
./apps/diaries/actions.py
./apps/diaries/querysets.py
./apps/library/tests/test_forms.py
./apps/library/migrations/0001_initial.py
./apps/polls/views.py
./apps/polls/formsets.py
./apps/polls/reports.py
./apps/polls/admin.py

Solution 3 - use "pathlib"

# lookup in current dir
path_ = pathlib.Path('.')
tuple(path_.glob(pattern))

# lookup recursive
tuple(path_.rglob(pattern))

Notes:

  1. Tested on the Python 3.4
  2. The module "pathlib" was added only in the Python 3.4
  3. The Python 3.5 added a feature for recursive lookup with glob.glob https://docs.python.org/3.5/library/glob.html#glob.glob. Since my machine is installed with Python 3.4, I have not tested that.

Datepicker: How to popup datepicker when click on edittext

class MyClass implements OnClickListener, OnDateSetListener {   
   EditText editText;
   this.editText = (EditText) findViewById(R.id.editText);
   this.editText.setOnClickListener(this);
   @Override
   public void onClick(View v) {

       DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
       dialog.show();
   }
   @Override
   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
       // this.editText.setText();
   }
}

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

x_train = x_train.reshape(-1,28, 28, 1)   #Reshape for CNN -  should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))

Output:

Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

What SOAP client libraries exist for Python, and where is the documentation for them?

Could this help: http://users.skynet.be/pascalbotte/rcx-ws-doc/python.htm#SOAPPY

I found it by searching for wsdl and python, with the rational being, that you would need a wsdl description of a SOAP server to do any useful client wrappers....

When to use Hadoop, HBase, Hive and Pig?

I implemented a Hive Data platform recently in my firm and can speak to it in first person since I was a one man team.

Objective

  1. To have the daily web log files collected from 350+ servers daily queryable thru some SQL like language
  2. To replace daily aggregation data generated thru MySQL with Hive
  3. Build Custom reports thru queries in Hive

Architecture Options

I benchmarked the following options:

  1. Hive+HDFS
  2. Hive+HBase - queries were too slow so I dumped this option

Design

  1. Daily log Files were transported to HDFS
  2. MR jobs parsed these log files and output files in HDFS
  3. Create Hive tables with partitions and locations pointing to HDFS locations
  4. Create Hive query scripts (call it HQL if you like as diff from SQL) that in turn ran MR jobs in the background and generated aggregation data
  5. Put all these steps into an Oozie workflow - scheduled with Daily Oozie Coordinator

Summary

HBase is like a Map. If you know the key, you can instantly get the value. But if you want to know how many integer keys in Hbase are between 1000000 and 2000000 that is not suitable for Hbase alone.

If you have data that needs to be aggregated, rolled up, analyzed across rows then consider Hive.

Hopefully this helps.

Hive actually rocks ...I know, I have lived it for 12 months now... So does HBase...

indexOf Case Sensitive?

Yes, it is case-sensitive. You can do a case-insensitive indexOf by converting your String and the String parameter both to upper-case before searching.

String str = "Hello world";
String search = "hello";
str.toUpperCase().indexOf(search.toUpperCase());

Note that toUpperCase may not work in some circumstances. For instance this:

String str = "Feldbergstraße 23, Mainz";
String find = "mainz";
int idxU = str.toUpperCase().indexOf (find.toUpperCase ());
int idxL = str.toLowerCase().indexOf (find.toLowerCase ());

idxU will be 20, which is wrong! idxL will be 19, which is correct. What's causing the problem is tha toUpperCase() converts the "ß" character into TWO characters, "SS" and this throws the index off.

Consequently, always stick with toLowerCase()

What Process is using all of my disk IO

To find out which processes in state 'D' (waiting for disk response) are currently running:

while true; do date; ps aux | awk '{if($8=="D") print $0;}'; sleep 1; done

or

watch -n1 -d "ps axu | awk '{if (\$8==\"D\") {print \$0}}'"

Wed Aug 29 13:00:46 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:47 CLT 2012
Wed Aug 29 13:00:48 CLT 2012
Wed Aug 29 13:00:49 CLT 2012
Wed Aug 29 13:00:50 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:51 CLT 2012
Wed Aug 29 13:00:52 CLT 2012
Wed Aug 29 13:00:53 CLT 2012
Wed Aug 29 13:00:55 CLT 2012
Wed Aug 29 13:00:56 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:57 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:58 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:59 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:00 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:01 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:02 CLT 2012
Wed Aug 29 13:01:03 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]

As you can see from the result, the jdb2/dm-0-8 (ext4 journal process), and kdmflush are constantly block your Linux.

For more details this URL could be helpful: Linux Wait-IO Problem

Find element's index in pandas Series

In [92]: (myseries==7).argmax()
Out[92]: 3

This works if you know 7 is there in advance. You can check this with (myseries==7).any()

Another approach (very similar to the first answer) that also accounts for multiple 7's (or none) is

In [122]: myseries = pd.Series([1,7,0,7,5], index=['a','b','c','d','e'])
In [123]: list(myseries[myseries==7].index)
Out[123]: ['b', 'd']

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Calling a user defined function in jQuery

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 


$('#my-form').clear();

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

There are a few options:

  • Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    
  • Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    

How to pass parameters in $ajax POST?

function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}

OnClick vs OnClientClick for an asp:CheckBox?

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

How to drop a list of rows from Pandas dataframe?

To drop rows with indices 1, 2, 4 you can use:

df[~df.index.isin([1, 2, 4])]

The tilde operator ~ negates the result of the method isin. Another option is to drop indices:

df.loc[df.index.drop([1, 2, 4])]

Setting background-image using jQuery CSS property

The problem I was having, is that I kept adding a semi-colon ; at the end of the url() value, which prevented the code from working.

? NOT WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');

? WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');

Notice the omitted semi-colon ; at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.

python - checking odd/even numbers and changing outputs on number size

1) How do I check if it's even or odd? I tried "if number/2 == int" in the hope that it might do something, and the internet tells me to do "if number%2==0", but that doesn't work.

def isEven(number):
        return number % 2 == 0

How to float 3 divs side by side using CSS?

But does it work in Chrome?

Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11

Click for JS Fiddle

HTML

<div class="stack">
    <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
    </div>
        <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
                    <div class="col">
            Three
        </div>
    </div>
</div>

CSS

.stack .row { 
clear:both;

}
.stack .row  .col    {
    float:left;
      border:1px solid;

}

Get all inherited classes of an abstract class

It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport) for each one.

Multiple Indexes vs Multi-Column Indexes

One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.

How to show first commit by 'git log'?

Not the most beautiful way of doing it I guess:

git log --pretty=oneline | wc -l

This gives you a number then

git log HEAD~<The number minus one>

Is there any way to configure multiple registries in a single npmrc file

My approach was to make a slight command line variant that adds the registry switch.

I created these files in the nodejs folder where the npm executable is found:

npm-.cmd:

@ECHO OFF
npm --registry https://registry.npmjs.org %*

npm-:

#!/bin/sh
"npm" --registry https://registry.npmjs.org "$@"

Now, if I want to do an operation against the normal npm registry (while I am not connected to the VPN), I just type npm- where I would usually type npm.

To test this command and see the registry for a package, use this example:

npm- view lodash

PS. I am in windows and have tested this in Bash, CMD, and Powershell. I also

Output single character in C

yes, %c will print a single char:

printf("%c", 'h');

also, putchar/putc will work too. From "man putchar":

#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).

EDIT:

Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */

Laravel - Eloquent or Fluent random row

You can use:

ModelName::inRandomOrder()->first();

How to create a Java / Maven project that works in Visual Studio Code?

Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-

  1. Download VS Code and Apache Maven and install both.
  2. Install the Visual Studio extension pack for Java - e.g. by pasting this URL into a web browser: vscode:extension/vscjava.vscode-java-pack and then clicking on the green Install button after it opens in VS Code.
  3. NOTE: See the comment from ADTC for an "Easier GUI version of step 3...(Skip step 4)." If necessary, the Maven quick start archetype could be used to generate a new Maven project in an appropriate local folder: mvn archetype:generate -DgroupId=com.companyname.appname-DartifactId=appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname and src/main/test/com/companyname/appname to begin with and a sample "Hello World!" Java file named appname.java and associated unit test named appnameTest.java).*
  4. Open the Maven project folder in VS Code via File menu -> Open Folder... and select the appname folder.
  5. Open the Command Palette (via the View menu or by right-clicking) and type in and select Tasks: Configure task then select Create tasks.json from template.
  6. Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:

    {
        "label": "compile",
        "type": "shell",
        "command": "mvn -B compile",
        "group": "build"
    },
    
  7. Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target folder at the same level as the src folder with the compiled class files in the target\classes folder.


Addendum: How to run/debug a class

Following a question in the comments, here are some steps for running/debugging:-

  1. Show the Debug view if it is not already shown (via View menu - Debug or CtrlShiftD).
  2. Click on the green arrow in the Debug view and select "Java".
  3. Assuming it hasn't already been created, a message "launch.json is needed to start the debugger. Do you want to create it now?" will appear - select "Yes" and then select "Java" again.
  4. Enter the fully qualified name of the main class (e.g. com.companyname.appname.App) in the value for "mainClass" and save the file.
  5. Click on the green arrow in the Debug view again.

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

How to bind 'touchstart' and 'click' events but not respond to both?

This hasn't been mentioned here, but you may want to check out this link: https://joshtronic.com/2015/04/19/handling-click-and-touch-events-on-the-same-element/

To recap for posterity, instead of trying to assign to both handlers and then sort out the result, you can simply check if the device is a touchscreen or not and only assign to the relevant event. Observe:

var clickEvent = (function() {
  if ('ontouchstart' in document.documentElement === true)
    return 'touchstart';
  else
    return 'click';
})();

// and assign thusly:

el.addEventListener( clickEvent, function( e ){ 
    // things and stuff
});

I am using this to bind my events so that I can test on touchscreens that handle both touchstart and click events which would fire twice, and on my development PC which only hears the click

One problem the author of that link mentions though, is touchscreen laptops designed to handle both events:

I learned about a third device I was not considering, the touchscreen laptop. It’s a hybrid device that supports both touch and click events. Binding one event means only that event be supported. Does that mean someone with a touchscreen and mouse would have to explicitly touch because that’s the only event I am handling?

Binding touchstart and click seemed ideal to handle these hybrid devices. To keep the event from firing twice, I added e.stopPropagation() and e.preventDefault() to the callback functions. e.stopPropagation() stops events from “bubbling up” to their parents but also keeps a second event from firing. I included e.preventDefault() as a “just in case” but seems like it could be omitted.

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

Using ResourceManager

in priciple it's the same idea as @Landeeyos. anyhow, expanding on that response: a bit late to the party but here are my two cents:

scenario:

I have a unique case of adding some (roughly 28 text files) predefined, template files with my WPF application. So, the idea is that everytime this app is to be installed, these template, text files will be readily available for usage. anyhow, what I did was that made a seperate library to hold the files by adding a resource.resx. Then I added all those files to this resource file (if you double click a .resx file, its designer gets opened in visual studio). I had set the Access Modifier to public for all. Also, each file was marked as an embedded resource via the Build Action of each text file (you can get that by looking at its properties). let's call this bibliothek1.dll i referenced this above library (bibliothek1.dll) in another library (call it bibliothek2.dll) and then consumed this second library in mf wpf app.

actual fun:

        // embedded resource file name <i>with out extension</i>(this is vital!) 

        string fileWithoutExt = Path.GetFileNameWithoutExtension(fileName);

        // is required in the next step

        // without specifying the culture
        string wildFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt);
        Console.Write(wildFile);

        // with culture
        string culturedFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt, CultureInfo.InvariantCulture);
        Console.Write(culturedFile);

sample: checkout 'testingresourcefilesusage' @ https://github.com/Natsikap/samples.git

I hope it helps someone, some day, somewhere!

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

jQuery(document).ready(function ($) {

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

How do I install a module globally using npm?

In Ubuntu, set path of node_modules in .bashrc file

export PATH="/home/username/node_modules/.bin:$PATH"

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

PHP date add 5 year to current date

       $date = strtotime($row['timestamp']);
       $newdate = date('d-m-Y',strtotime("+1 year",$date));

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

I've found a working code:

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

How to get the user input in Java?

Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).

In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console. Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.

For user input, you should have a wide TextField at the top of the GUI console.

This is where the user enters the numbers that they want to perform functions on. Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions. Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.

This video is a bit old but still shows how easy Scene Builder is to use.

How do pointer-to-pointer's work in C? (and when might you use them?)

There so many of the useful explanations, but I didnt found just a short description, so..

Basically pointer is address of the variable. Short summary code:

     int a, *p_a;//declaration of normal variable and int pointer variable
     a = 56;     //simply assign value
     p_a = &a;   //save address of "a" to pointer variable
     *p_a = 15;  //override the value of the variable

//print 0xfoo and 15 
//- first is address, 2nd is value stored at this address (that is called dereference)
     printf("pointer p_a is having value %d and targeting at variable value %d", p_a, *p_a); 

Also useful info can be found in topic What means reference and dereference

And I am not so sure, when can be pointers useful, but in common it is necessary to use them when you are doing some manual/dynamic memory allocation- malloc, calloc, etc.

So I hope it will also helps for clarify the problematic :)

Basic HTTP and Bearer Token Authentication

I had a similar problem - authenticate device and user at device. I used a Cookie header alongside an Authorization: Bearer... header. One header authenticated the device, the other authenticated the user. I used a Cookie header because these are commonly used for authentication.

What REALLY happens when you don't free after malloc?

You are correct, memory is automatically freed when the process exits. Some people strive not to do extensive cleanup when the process is terminated, since it will all be relinquished to the operating system. However, while your program is running you should free unused memory. If you don't, you may eventually run out or cause excessive paging if your working set gets too big.

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

Is there a good JavaScript minifier?

JavaScript Minifier gives a good API you can use programatically:

curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw

Or by uploading a file and redirecting to a new file:

curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js

Hope that helps.

JavaScript query string

// How about this
function queryString(qs) {
    var queryStr = qs.substr(1).split("&"),obj={};
    for(var i=0; i < queryStr.length;i++)
        obj[queryStr[i].split("=")[0]] = queryStr[i].split("=")[1];
    return obj;
}

// Usage:
var result = queryString(location.search);

Why am I getting ImportError: No module named pip ' right after installing pip?

Running these 2 commands helped me:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Converting std::__cxx11::string to std::string

When I had similar issue it's happened because my lib was build using clang++, and it's linked to libstdc++.so by default on my system. While app binary was build using clang and linked with -lc++ option.

Easiest way to check dependencies is to perform ldd libName.so

To fix it you should use the same library on in app and library.

  • Easiest way. Build library using clang++ and compile app using clang++. Without extra linking options on both steps. Default stdlib will be used.

  • Build library with -stdlib=c++ and compile app with -lc++. In this case both library and app will use libc++.so.

  • Build library without extra options and link binary to -lstdc++. In this case both library and app will use libstdc++.so.

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

Confirm deletion in modal / dialog using Twitter Bootstrap?

Following solution is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

_x000D_
_x000D_
const dialogTemplate = '\_x000D_
    <div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
        <div class ="modal-dialog">\_x000D_
            <div class ="modal-content">\_x000D_
                <div class ="modal-body">\_x000D_
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
                </div>\_x000D_
                <div class ="modal-footer">\_x000D_
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
                </div>\_x000D_
            </div>\_x000D_
        </div>\_x000D_
    </div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
    if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
        var iDiv = document.createElement('div');_x000D_
        iDiv.id = 'digimango_MessageBoxContainer';_x000D_
        document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
        $("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
    }_x000D_
_x000D_
    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
    if (options == null) {_x000D_
        okButtonName = 'OK';_x000D_
        cancelButtonName = null;_x000D_
        showTextBox = null;_x000D_
        textBoxDefaultText = null;_x000D_
    } else {_x000D_
        okButtonName = options.okButtonName;_x000D_
        cancelButtonName = options.cancelButtonName;_x000D_
        showTextBox = options.showTextBox;_x000D_
        textBoxDefaultText = options.textBoxDefaultText;_x000D_
    }_x000D_
_x000D_
    if (showTextBox == true) {_x000D_
        if (textBoxDefaultText == null)_x000D_
            $('#digimango_messageBoxTextArea').val('');_x000D_
        else_x000D_
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
        $('#digimango_messageBoxTextArea').show();_x000D_
    }_x000D_
    else_x000D_
        $('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
    if (okButtonName != null)_x000D_
        $('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
    else_x000D_
        $('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
    if (cancelButtonName == null)_x000D_
        $('#digimango_messageBoxCancelButton').hide();_x000D_
    else {_x000D_
        $('#digimango_messageBoxCancelButton').show();_x000D_
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
    }_x000D_
_x000D_
    $('#digimango_messageBoxOkButton').unbind('click');_x000D_
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
    $('#digimango_messageBoxCancelButton').unbind('click');_x000D_
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
    var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
    if (significance == 'error')_x000D_
        content.attr('class', 'text-danger');_x000D_
    else if (significance == 'warning')_x000D_
        content.attr('class', 'text-warning');_x000D_
    else_x000D_
        content.attr('class', 'text-success');_x000D_
_x000D_
    content.html(msg);_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $("#digimango_messageBox").modal();_x000D_
_x000D_
    digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
    // JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
    // thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
    // not execute the last line in this function._x000D_
    if (typeof (event.data.callback) != 'undefined')_x000D_
        event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
_x000D_
_x000D_

To use digimango.messagebox.js:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title>A useful generic message box</title>_x000D_
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function testAlert() {_x000D_
            messageBox('Something went wrong!', 'error');_x000D_
        }_x000D_
_x000D_
        function testAlertWithCallback() {_x000D_
            messageBox('Something went wrong!', 'error', null, function () {_x000D_
                messageBox('OK clicked.');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testConfirm() {_x000D_
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPrompt() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPromptWithDefault() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
    </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
    <a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_ enter image description here

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to run Tensorflow on CPU

You could use tf.config.set_visible_devices. One possible function that allows you to set if and which GPUs to use is:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

Suppose you are on a system with 4 GPUs and you want to use only two GPUs, the one with id = 0 and the one with id = 2, then the first command of your code, immediately after importing the libraries, would be:

set_gpu([0, 2])

In your case, to use only the CPU, you can invoke the function with an empty list:

set_gpu([])

For completeness, if you want to avoid that the runtime initialization will allocate all memory on the device, you can use tf.config.experimental.set_memory_growth. Finally, the function to manage which devices to use, occupying the GPUs memory dynamically, becomes:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            for gpu in gpus_used:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

SQLMenace said money is inexact. But you don't multiply/divide money by money! How much is 3 dollars times 50 cents? 150 dollarcents? You multiply/divide money by scalars, which should be decimal.

DECLARE
@mon1 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@num2*@num3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS moneyresult,
@num4 AS numericresult

Results in the correct result:

moneyresult           numericresult
--------------------- ---------------------------------------
2949.8525             2949.8525

money is good as long as you don't need more than 4 decimal digits, and you make sure your scalars - which do not represent money - are decimals.

Detecting when user scrolls to bottom of div with jQuery

There are some properties/methods you can use:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

So you can take the sum of the first two properties, and when it equals to the last property, you've reached the end:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});

http://jsfiddle.net/doktormolle/w7X9N/

Edit: I've updated 'bind' to 'on' as per:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

Installing PDO driver on MySQL Linux server

If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!

Here's how I installed in Ubuntu-based image:

https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8

RUN docker-php-ext-install mysql mysqli pdo pdo_mysql

Building and running your application is just a 2 step process (considering you are in the current directory of the app):

$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp

Python find elements in one list that are not in the other

If you want a one-liner solution (ignoring imports) that only requires O(max(n, m)) work for inputs of length n and m, not O(n * m) work, you can do so with the itertools module:

from itertools import filterfalse

main_list = list(filterfalse(set(list_1).__contains__, list_2))

This takes advantage of the functional functions taking a callback function on construction, allowing it to create the callback once and reuse it for every element without needing to store it somewhere (because filterfalse stores it internally); list comprehensions and generator expressions can do this, but it's ugly.†

That gets the same results in a single line as:

main_list = [x for x in list_2 if x not in list_1]

with the speed of:

set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]

Of course, if the comparisons are intended to be positional, so:

list_1 = [1, 2, 3]
list_2 = [2, 3, 4]

should produce:

main_list = [2, 3, 4]

(because no value in list_2 has a match at the same index in list_1), you should definitely go with Patrick's answer, which involves no temporary lists or sets (even with sets being roughly O(1), they have a higher "constant" factor per check than simple equality checks) and involves O(min(n, m)) work, less than any other answer, and if your problem is position sensitive, is the only correct solution when matching elements appear at mismatched offsets.

†: The way to do the same thing with a list comprehension as a one-liner would be to abuse nested looping to create and cache value(s) in the "outermost" loop, e.g.:

main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]

which also gives a minor performance benefit on Python 3 (because now set_1 is locally scoped in the comprehension code, rather than looked up from nested scope for each check; on Python 2 that doesn't matter, because Python 2 doesn't use closures for list comprehensions; they operate in the same scope they're used in).

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

As others have answered, this breaks because .ToString fails to translate to relevant SQL on the way into the database.

However, Microsoft provides the SqlFunctions class that is a collection of methods that can be used in situations like this.

For this case, what you are looking for here is SqlFunctions.StringConvert:

from p in context.pages
where  p.Serial == SqlFunctions.StringConvert((double)item.Key.Id)
select p;

Good when the solution with temporary variables is not desirable for whatever reasons.

Similar to SqlFunctions you also have the EntityFunctions (with EF6 obsoleted by DbFunctions) that provides a different set of functions that also are data source agnostic (not limited to e.g. SQL).

'namespace' but is used like a 'type'

If you're working on a big app and can't change any names, you can type a . to select the type you want from the namespace:

namespace Company.Core.Context{
  public partial class Context : Database Context {
    ...
  }
}
...

using Company.Core.Context;
someFunction(){
 var c = new Context.Context();
}

How do you append to an already existing string?

#!/bin/bash

msg1=${1} #First Parameter
msg2=${2} #Second Parameter

concatString=$msg1"$msg2" #Concatenated String
concatString2="$msg1$msg2"

echo $concatString 
echo $concatString2

Windows 7, 64 bit, DLL problems

I also ran into this problem, but the solution that seems to be a common thread here, and I saw elsewhere on the web, is "[re]install the redistributable package". However, for me that does not work, as the problem arose when running the installer for our product (which installs the redistributable package) to test our shiny new Visual Studio 2015 builds.

The issue came up because the DLL files listed are not located in the Visual Studio install path (for example, C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist) and thus had not been added to the install. These api-ms-win-* dlls get installed to a Windows 10 SDK install path as part of the Visual Studio 2015 install (e.g. C:\Program Files (x86)\Windows Kits\10\Redist).

Installing on Windows 10 worked fine, but installing on Windows 7 required adding these DLL files to our product install. For more information, see Update for Universal C Runtime in Windows which describes the addition of these dependencies caused by Visual Studio 2015 and provides downloads for various Windows platforms; also see Introducing the Universal CRT which describes the redesign of the CRT libraries. Of particular interest is item 6 under the section titled Distributing Software that uses the Universal CRT:

Updated September 11, 2015: App-local deployment of the Universal CRT is supported. To obtain the binaries for app-local deployment, install the Windows Software Development Kit (SDK) for Windows 10. The binaries will be installed to C:\Program Files (x86)\Windows Kits\10\Redist\ucrt. You will need to copy all of the DLLs with your app (note that the set of DLL files are necessary is different on different versions of Windows, so you must include all of the DLL files in order for your program to run on all supported versions of Windows).

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Because Stage is required, all one-to-many relationships where Stage is involved will have cascading delete enabled by default. It means, if you delete a Stage entity

  • the delete will cascade directly to Side
  • the delete will cascade directly to Card and because Card and Side have a required one-to-many relationship with cascading delete enabled by default again it will then cascade from Card to Side

So, you have two cascading delete paths from Stage to Side - which causes the exception.

You must either make the Stage optional in at least one of the entities (i.e. remove the [Required] attribute from the Stage properties) or disable cascading delete with Fluent API (not possible with data annotations):

modelBuilder.Entity<Card>()
    .HasRequired(c => c.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Side>()
    .HasRequired(s => s.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

if else in a list comprehension

>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in l]
[27, 18, 46, 51, 99, 70, 48, 49, 6]

Do-something if <condition>, else do-something else.

How to obtain the location of cacerts of the default java installation?

In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts

Get yesterday's date in bash on Linux, DST-safe

Here a solution that will work with Solaris and AIX as well.

Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1

The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
{
   background-color: white;
}

Or have any children (including text):

table td:not(:empty)
{
   background-color: white;
}

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

Browser Caching of CSS files

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache. Changing the file on the server should cause a refresh of the file however.

JavaScript variable assignments from tuples

Javascript 1.7 added destructured assignment which allows you to do essentially what you are after.

function getTuple(){
   return ["Bob", 24];
}
var [a, b] = getTuple();
// a === "bob" , b === 24 are both true

How to get all table names from a database?

If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954

Assigning a variable NaN in python without numpy

You can get NaN from "inf - inf", and you can get "inf" from a number greater than 2e308, so, I generally used:

>>> inf = 9e999
>>> inf
inf
>>> inf - inf
nan

XAMPP: Couldn't start Apache (Windows 10)

I have tried all the above solutions. But it was not working in any way.

Finally, I just uninstalled XAMPP and installed it again. Then it worked for me.

Now I am able to run the server on any port (including 80).

SQL split values to multiple rows

CREATE PROCEDURE `getVal`()
BEGIN
        declare r_len integer;
        declare r_id integer;
        declare r_val varchar(20);
        declare i integer;
        DECLARE found_row int(10);
        DECLARE row CURSOR FOR select length(replace(val,"|","")),id,val from split;
        create table x(id int,name varchar(20));
      open row;
            select FOUND_ROWS() into found_row ;
            read_loop: LOOP
                IF found_row = 0 THEN
                         LEAVE read_loop;
                END IF;
            set i = 1;  
            FETCH row INTO r_len,r_id,r_val;
            label1: LOOP        
                IF i <= r_len THEN
                  insert into x values( r_id,SUBSTRING(replace(r_val,"|",""),i,1));
                  SET i = i + 1;
                  ITERATE label1;
                END IF;
                LEAVE label1;
            END LOOP label1;
            set found_row = found_row - 1;
            END LOOP;
        close row;
        select * from x;
        drop table x;
END

How to add a "open git-bash here..." context menu to the windows explorer?

I had a similar issue and I did this.

Step 1 : Type "regedit" in start menu

Step 2 : Run the registry editor

Step 3 : Navigate to HKEY_CURRENT_USER\SOFTWARE\Classes\Directory\Background\shell

Step 4 : Right-click on "shell" and choose New > Key. name the Key "Bash"

Right click on "shell" and choose New > Key. name the Key "Bash"

Step 5 : Modify the value and set it to "open in Bash" This is the text that appears in the right click.

enter image description here

enter image description here

Step 6 : Create a new key under Bash and name it "command". Set the value of this key to your git-bash.exe path.

enter image description here

enter image description here

enter image description here

Close the registry editor.

You should now be able to see the option in right click menu in explorer

PS Git Bash by default picks up the current directory.

EDIT : If you want a one click approach, check Ozesh's solution below

Restore a deleted file in the Visual Studio Code Recycle Bin

who still facing the problem on linux and didnt find it on trash try this solution

https://github.com/Microsoft/vscode/issues/32078#issuecomment-434393058

find / -name "delete_file_name"

Parse JSON in C#

Thank you all for your help. This is my final version, and it works thanks to your combined help ! I am only showing the changes i made, all the rest is taken from Joe Chung's work

public class GoogleSearchResults
    {
        [DataMember]
        public ResponseData responseData { get; set; }

        [DataMember]
        public string responseDetails { get; set; }

        [DataMember]
        public int responseStatus { get; set; }
    }

and

 [DataContract]
    public class ResponseData
    {
        [DataMember]
        public List<Results> results { get; set; }
    }

How do I use PHP to get the current year?

Get full Year used:

 <?php 
    echo $curr_year = date('Y'); // it will display full year ex. 2017
?>

Or get only two digit of year used like this:

 <?php 
    echo $curr_year = date('y'); // it will display short 2 digit year ex. 17
?>

C# Wait until condition is true

This implementation is totally based on Sinaesthetic's, but adding CancellationToken and keeping the same execution thread and context; that is, delegating the use of Task.Run() up to the caller depending on whether condition needs to be evaluated in the same thread or not.

Also, notice that, if you don't really need to throw a TimeoutException and breaking the loop is enough, you might want to make use of cts.CancelAfter() or new CancellationTokenSource(millisecondsDelay) instead of using timeoutTask with Task.Delay plus Task.WhenAny.

public static class AsyncUtils
{
    /// <summary>
    ///     Blocks while condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks until condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (!condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     The cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitWhileAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }

    /// <summary>
    ///     Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitUntilAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }
}

How to Detect Browser Window /Tab Close Event?

You can also do like below.

put below script code in header tag

<script type="text/javascript" language="text/javascript"> 
function handleBrowserCloseButton(event) { 
   if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) 
    {
      //Call method by Ajax call
      alert('Browser close button clicked');    
    } 
} 
</script>

call above function from body tag like below

<body onbeforeunload="handleBrowserCloseButton(event);">

Thank you

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Java - How do I make a String array with values?

By using the array initializer list syntax, ie:

String myArray[] = { "one", "two", "three" };

Unable to run Java code with Intellij IDEA

If you use Maven, you must to declare your source and test folder in project directory.

For these, click F4 on Intellij Idea and Open Project Structure. Select your project name on the left panel and Mark As your "Source" and "Test" directory.

Automatically create an Enum based on values in a database lookup table?

I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:

public abstract class CustomEnum
{
    private readonly string _name;
    private readonly object _id;

    protected CustomEnum( string name, object id )
    {
        _name = name;
        _id = id;
    }

    public string Name
    {
        get { return _name; }
    }

    public object Id
    {
        get { return _id; }
    }

    public override string ToString()
    {
        return _name;
    }
}

public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
    where TEnumType : CustomEnum<TEnumType, TIdType>
{
    protected CustomEnum( string name, TIdType id )
        : base( name, id )
    { }

    public new TIdType Id
    {
        get { return (TIdType)base.Id; }
    }

    public static TEnumType FromName( string name )
    {
        try
        {
            return FromDelegate( entry => entry.Name.Equals( name ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static TEnumType FromId( TIdType id )
    {
        try
        {
            return FromDelegate( entry => entry.Id.Equals( id ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static IEnumerable<TEnumType> GetAll()
    {
        var elements = new Collection<TEnumType>();
        var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );

        foreach (var info in infoArray)
        {
            var type = info.GetValue( null ) as TEnumType;
            elements.Add( type );
        }

        return elements;
    }

    protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
    {
        if(predicate == null)
            throw new ArgumentNullException( "predicate" );

        foreach (var entry in GetAll())
        {
            if (predicate( entry ))
                return entry;
        }

        throw new ArgumentException( "Element not found while using predicate" );
    }
}

Now I just need to create my enum I want to use:

 public sealed class SampleEnum : CustomEnum<SampleEnum, int>
    {
        public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
        public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );

        private SampleEnum( string name, int id, string additionalText )
            : base( name, id )
        {
            AdditionalText = additionalText;
        }

        public string AdditionalText { get; private set; }
    }

At last I can use it like I want:

 static void Main( string[] args )
        {
            foreach (var element in SampleEnum.GetAll())
            {
                Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
                Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
                Console.WriteLine();
            }

            Console.ReadKey();
        }

And my output would be:

Element1: foo
Is 'Element2': False

Element2: bar
Is 'Element2': True    

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

How to remove padding around buttons in Android?

For removing padding around toggle button we need set minWidth and minHeight 0dp.android:minWidth="0dp" android:minHeight="0dp"

  <ToggleButton
        android:id="@+id/toggle_row_notifications"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="0dp"
        android:minHeight="0dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/_5sdp"
        android:textOn=""
        android:textOff=""
        android:background="@android:color/transparent"
        android:button="@drawable/toggle_selector"
        />

set your drawable file to button attribute like: android:button="@drawable/toggle_selector"

Below is my toggle_selecter.xml file

<?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:drawable="@drawable/notifications_toggle_on" 
                  android:state_checked="true"/>
            <item android:drawable="@drawable/notifications_toggle_off" 
                  android:state_checked="false"/>
     </selector>

Navigation Controller Push View Controller

If you are using Swift:

let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

I fixed a similar error by adding the json dataType like so:

$.ajax({
    type: "POST",
    url: "someUrl",
    dataType: "json",
    data: {
        varname1 : "varvalue1",
        varname2 : "varvalue2"
    },
    success: function (data) {
        $.each(data, function (varname, varvalue){
            ...
        });  
    }
});

And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):

@RequestMapping(value = "/someUrl", method=RequestMethod.POST)
@ResponseBody
public String getJsonData(@RequestBody String parameters) {
    // parameters = varname1=varvalue1&varname2=varvalue2
    String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
    return exampleData;
}

So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):

[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]

Pandas KeyError: value not in index

Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])

So, your entire code example should look like this:

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)

How to execute a raw update sql with dynamic binding in rails

Why use raw SQL for this?

If you have a model for it use where:

f1 = 'foo'
f2 = 'bar'
f3 = 'buzz'
YourModel.where('f1 = ? and f2 = ?', f1, f2).each do |ym|
  # or where(f1: f1, f2: f2).each do (...)
  ym.update(f3: f3) 
end

If you don't have a model for it (just the table), you can create a file and model that will inherit from ActiveRecord::Base

class YourTable < ActiveRecord::Base
  self.table_name = 'your_table' # specify explicitly if needed
end

and again use where the same as above:

HashSet vs. List performance

It's essentially pointless to compare two structures for performance that behave differently. Use the structure that conveys the intent. Even if you say your List<T> wouldn't have duplicates and iteration order doesn't matter making it comparable to a HashSet<T>, its still a poor choice to use List<T> because its relatively less fault tolerant.

That said, I will inspect some other aspects of performance,

+------------+--------+-------------+-----------+----------+----------+-----------+
| Collection | Random | Containment | Insertion | Addition |  Removal | Memory    |
|            | access |             |           |          |          |           |
+------------+--------+-------------+-----------+----------+----------+-----------+
| List<T>    | O(1)   | O(n)        | O(n)      | O(1)*    | O(n)     | Lesser    |
| HashSet<T> | O(n)   | O(1)        | n/a       | O(1)     | O(1)     | Greater** |
+------------+--------+-------------+-----------+----------+----------+-----------+
  • Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.

  • The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. This article might give you an idea.

Git keeps asking me for my ssh key passphrase

What worked for me on Windows was (I had cloned code from a repo 1st):

eval $(ssh-agent)
ssh-add 
git pull 

at which time it asked me one last time for my passphrase

Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket

How can I get the count of line in a file in an efficient way?

Read the file line by line and increment a counter for each line until you have read the entire file.

String formatting: % vs. .format vs. string literal

As of Python 3.6 (2016) you can use f-strings to substitute variables:

>>> origin = "London"
>>> destination = "Paris"
>>> f"from {origin} to {destination}"
'from London to Paris'

Note the f" prefix. If you try this in Python 3.5 or earlier, you'll get a SyntaxError.

See https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings

(13: Permission denied) while connecting to upstream:[nginx]

I’ve run into this problem too. Another solution is to toggle the SELinux boolean value for httpd network connect to on (Nginx uses the httpd label).

setsebool httpd_can_network_connect on

To make the change persist use the -P flag.

setsebool httpd_can_network_connect on -P

You can see a list of all available SELinux booleans for httpd using

getsebool -a | grep httpd

How can I delete a query string parameter in JavaScript?

The above version as a function

function removeURLParam(url, param)
{
 var urlparts= url.split('?');
 if (urlparts.length>=2)
 {
  var prefix= encodeURIComponent(param)+'=';
  var pars= urlparts[1].split(/[&;]/g);
  for (var i=pars.length; i-- > 0;)
   if (pars[i].indexOf(prefix, 0)==0)
    pars.splice(i, 1);
  if (pars.length > 0)
   return urlparts[0]+'?'+pars.join('&');
  else
   return urlparts[0];
 }
 else
  return url;
}

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

If the charset of the tables is the same as it's content try to use mysql_set_charset('UTF8', $link_identifier). Note that MySQL uses UTF8 to specify the UTF-8 encoding instead of UTF-8 which is more common.

Check my other answer on a similar question too.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Call Activity method from adapter

Original:

I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.

In your Activity:

This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.

public class MyActivity extends Activity implements AdapterCallback {

    private MyAdapter myAdapter;

    @Override
    public void onMethodCallback() {
       // do something
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myAdapter = new MyAdapter(this);
    }
}

In your Adapter:

In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private AdapterCallback adapterCallback;

    public MyAdapter(Context context) {
        try {
            adapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.", e);
        }
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
        // simple example, call interface here
        // not complete
        viewHolder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    adapterCallback.onMethodCallback();
                } catch (ClassCastException e) {
                   // do something
                }
            }
        });
    }

    public static interface AdapterCallback {
        void onMethodCallback();
    }
}

Display current date and time without punctuation

If you're using Bash you could also use one of the following commands:

printf '%(%Y%m%d%H%M%S)T'       # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1    # same as above
printf '%(%Y%m%d%H%M%S)T' -2    # prints the time the shell was invoked

You can use the Option -v varname to store the result in $varname instead of printing it to stdout:

printf -v varname '%(%Y%m%d%H%M%S)T'

While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.

'foo' was not declared in this scope c++

In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

What's the best UI for entering date of birth?

I think a date picker just make the move more complicated to enter one's birth date.

As already mentioned, a combination of drop lists for days and months with a text box for the year seems the most efficient for a user. It takes just less than 10 seconds to enter a birth date this way, which is far quicker than a date picker: thanks to the tab key (which all users should learn to use to complete a form), it's fast to go from one form element to the next one.

At least under Macintosh (I don't know about Windows), you also can use the keyboard to access date inside select boxes: thanks to the tab key, you get the focus onto the form element, then press the arrow key to drop down the list, then type for instance 1967 and you get there in the blink of an eye…

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

You need junit-dep.jar because the junit.jar has a copy of old Hamcrest classes.

display data from SQL database into php/ html table

refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echo it inside your table

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>

How can I plot with 2 different y-axes?

Another alternative which is similar to the accepted answer by @BenBolker is redefining the coordinates of the existing plot when adding a second set of points.

Here is a minimal example.

Data:

x  <- 1:10
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)

Plot:

par(mar=c(5,5,5,5)+0.1, las=1)

plot.new()
plot.window(xlim=range(x), ylim=range(y1))
points(x, y1, col="red", pch=19)
axis(1)
axis(2, col.axis="red")
box()

plot.window(xlim=range(x), ylim=range(y2))
points(x, y2, col="limegreen", pch=19)
axis(4, col.axis="limegreen")

example

What is an OS kernel ? How does it differ from an operating system?

a kernel is part of the operating system, it is the first thing that the boot loader loads onto the cpu (for most operating systems), it is the part that interfaces with the hardware, and it also manages what programs can do what with the hardware, it is really the central part of the os, it is made up of drivers, a driver is a program that interfaces with a particular piece of hardware, for example: if I made a digital camera for computers, I would need to make a driver for it, the drivers are the only programs that can control the input and output of the computer

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

How can I get date in application run by node.js?

GMT -03:00 Example

new Date(new Date()-3600*1000*3).toISOString();

Apache - MySQL Service detected with wrong path. / Ports already in use

  1. Go to cmd and run it with Administrator mode.
  2. Uninstall mysql service through command prompt using the following command.

            sc delete mysql
    
  3. restart XAMPP

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Bogobogosort. Yes, it's a thing. to Bogobogosort, you Bogosort the first element. Check to see if that one element is sorted. Being one element, it will be. Then you add the second element, and Bogosort those two until it's sorted. Then you add one more element, then Bogosort. Continue adding elements and Bogosorting until you have finally done every element. This was designed never to succeed with any sizable list before the heat death of the universe.

WPF button click in C# code

I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;

How to get the parent dir location

os.path.abspath doesn't validate anything, so if we're already appending strings to __file__ there's no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

But, since we know how many levels to climb, we could clean this up with a simple little function:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

SQL Server String or binary data would be truncated

One other potential reason for this is if you have a default value setup for a column that exceeds the length of the column. It appears someone fat fingered a column that had a length of 5 but the default value exceeded the length of 5. This drove me nuts as I was trying to understand why it wasn't working on any insert, even if all i was inserting was a single column with an integer of 1. Because the default value on the table schema had that violating default value it messed it all up - which I guess brings us to the lesson learned - avoid having tables with default value's in the schema. :)

<button> background image

Replace button #rock With #rock

No need for additional selector scope. You're using an id which is as specific as you can be.

JsBin example: http://jsbin.com/idobar/1/edit

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE tblcatalog
    CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT FIRST;

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

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }

And in service class, please add the code below for notification:

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned 
         //from the onBind method to communicate with 
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

Service vs IntentService in the Android platform

Android IntentService vs Service

1.Service

  • A Service is invoked using startService().
  • A Service can be invoked from any thread.
  • A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
  • A Service invoked multiple times would create multiple instances.
  • A service needs to be stopped using stopSelf() or stopService().
  • Android service can run parallel operations.

2. IntentService

  • An IntentService is invoked using Intent.
  • An IntentService can in invoked from the Main thread only.
  • An IntentService creates a separate worker thread to run background operations.
  • An IntentService invoked multiple times won’t create multiple instances.
  • An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
  • In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
  • An IntentService cannot run parallel operation like a Service.

Refer from Here

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

You have given permission to perform commands on objects inside the S3 bucket, but you have not given permission to perform any actions on the bucket itself.

Slightly modifying your policy would look like this:

{
  "Version": "version_id",
  "Statement": [
    {
        "Sid": "some_id",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname",
            "arn:aws:s3:::bucketname/*"
        ]
    }
  ] 
}

However, that probably gives more permission than is needed. Following the AWS IAM best practice of Granting Least Privilege would look something like this:

{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
              "s3:ListBucket"
          ],
          "Resource": [
              "arn:aws:s3:::bucketname"
          ]
      },
      {
          "Effect": "Allow",
          "Action": [
              "s3:GetObject"
          ],
          "Resource": [
              "arn:aws:s3:::bucketname/*"
          ]
      }
  ]
}

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Declaring static constants in ES6 classes?

In this document it states:

There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property

This means that it is intentionally like this.

Maybe you can define a variable in the constructor?

constructor(){
    this.key = value
}

How to create a private class method?

By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:

class << self

  private

  def method_name
    ...
  end
end

class << self opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.

Tomcat in Intellij Idea Community Edition

Intellij Community does not offer Java application server integration. Your alternatives are

  1. buying Intellij licence,
  2. switching to Eclipse ;)
  3. installing Smart Tomcat plugin https://plugins.jetbrains.com/plugin/9492
  4. installing IDEA Jetty Runner plugin https://plugins.jetbrains.com/plugin/7505
  5. running the application server from Maven, Gradle, whatever, as outlined in the other answers.

I personally installed the Jetty Runner plugin (Jetty is fine for me, I do not need Tomcat) and I am satisfied with this solution. I had to deal with IntelliJ idea - Jetty, report an exception, though.

How do I create a file AND any folders, if the folders don't exist?

You want Directory.CreateDirectory()

Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:

using System.IO;

public class copyTemplateFiles
{


public static bool Copy(string Source, string destination)
{

    try {

        string[] Files = null;

        if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
            destination += Path.DirectorySeparatorChar;
        }

        if (!Directory.Exists(destination)) {
            Directory.CreateDirectory(destination);
        }

        Files = Directory.GetFileSystemEntries(Source);
        foreach (string Element in Files) {
            // Sub directories
            if (Directory.Exists(Element)) {
                copyDirectory(Element, destination + Path.GetFileName(Element));
            } else {
                // Files in directory
                File.Copy(Element, destination + Path.GetFileName(Element), true);
            }
        }

    } catch (Exception ex) {
        return false;
    }

    return true;

}



private static void copyDirectory(string Source, string destination)
{
    string[] Files = null;

    if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
        destination += Path.DirectorySeparatorChar;
    }

    if (!Directory.Exists(destination)) {
        Directory.CreateDirectory(destination);
    }

    Files = Directory.GetFileSystemEntries(Source);
    foreach (string Element in Files) {
        // Sub directories
        if (Directory.Exists(Element)) {
            copyDirectory(Element, destination + Path.GetFileName(Element));
        } else {
            // Files in directory
            File.Copy(Element, destination + Path.GetFileName(Element), true);
        }
    }

}

}

Php header location redirect not working

Neer to specify exit code here so php not execute further

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');        
    exit(0); // require to exit here 
}

Detect whether Office is 32bit or 64bit via the registry

I have win 7 64 bit + Excel 2010 32 bit. The registry is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-002A-0000-1000-0000000FF1CE}

So this can tell bitness of OS, not bitness of Office

Dynamic instantiation from string name of a class in dynamically imported module?

Copy-paste snippet:

import importlib
def str_to_class(module_name, class_name):
    """Return a class instance from a string reference"""
    try:
        module_ = importlib.import_module(module_name)
        try:
            class_ = getattr(module_, class_name)()
        except AttributeError:
            logging.error('Class does not exist')
    except ImportError:
        logging.error('Module does not exist')
    return class_ or None

How to paste into a terminal?

Gnome terminal defaults to ControlShiftv

OSX terminal defaults to Commandv. You can also use CommandControlv to paste the text in escaped form.

Windows 7 terminal defaults to CtrlShiftInsert

I/O error(socket error): [Errno 111] Connection refused

Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.

If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.

Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Check whether $_POST-value is empty

If the form was successfully submitted, $_POST['userName'] should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

How to terminate a thread when main program ends?

Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt. Such termination functions may (though inevitably in the main thread!) call any stop function you require; together with the possibility of setting a thread as daemon, that gives you the tools to properly design the system functionality you need.

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

How to convert milliseconds to "hh:mm:ss" format?

Test results for the 4 implementations

Having to do a lot of formatting for huge data, needed the best performance, so here are the (surprising) results:

for (int i = 0; i < 1000000; i++) { FUNCTION_CALL }

Durations:

  • combinationFormatter: 196 millis
  • formatDuration: 272 millis
  • apacheFormat: 754 millis
  • formatTimeUnit: 2216 millis

    public static String apacheFormat(long millis) throws ParseException {
        return DurationFormatUtils.formatDuration(millis, "HH:mm:ss");
    }
    
    public static String formatTimeUnit(long millis) throws ParseException {
    String formatted = String.format(
            "%02d:%02d:%02d",
            TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis)
                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis)
                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
        return formatted;
    }
    
    public static String formatDuration(final long millis) {
        long seconds = (millis / 1000) % 60;
        long minutes = (millis / (1000 * 60)) % 60;
        long hours = millis / (1000 * 60 * 60);
    
        StringBuilder b = new StringBuilder();
        b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) : 
        String.valueOf(hours));
        b.append(":");
        b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :     
        String.valueOf(minutes));
        b.append(":");
        b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) : 
        String.valueOf(seconds));
        return b.toString();
    }
    
    public static String combinationFormatter(final long millis) {
        long seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
        long minutes = TimeUnit.MILLISECONDS.toMinutes(millis)
                - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
        long hours = TimeUnit.MILLISECONDS.toHours(millis);
    
        StringBuilder b = new StringBuilder();
        b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) : 
        String.valueOf(hours));
        b.append(":");
        b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) : 
        String.valueOf(minutes));
            b.append(":");
        b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) : 
        String.valueOf(seconds));
        return b.toString(); 
     }
    

PL/SQL print out ref cursor returned by a stored procedure

Note: This code is untested

Define a record for your refCursor return type, call it rec. For example:

TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...);  --define the record
rec MyRec;        -- instantiate the record

Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:

LOOP
  FETCH refCursor INTO rec;
  EXIT WHEN refCursor%NOTFOUND;
  dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

Java keytool easy way to add server cert from url/port

I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool can do the whole job:

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]

Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 

libpng warning: iCCP: known incorrect sRGB profile

Here is a ridiculously brute force answer:

I modified the gradlew script. Here is my new exec command at the end of the file in the

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" **| grep -v "libpng warning:"**

How can I install the Beautiful Soup module on the Mac?

The "normal" way is to:

Another solution is to use easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:

easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup

easy_install will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install on your machine, you install many, many different third-party packages simply by one command at a shell.

Why is jquery's .ajax() method not sending my session cookie?

Adding my scenario and solution in case it helps someone else. I encountered similar case when using RESTful APIs. My Web server hosting HTML/Script/CSS files and Application Server exposing APIs were hosted on same domain. However the path was different.

web server - mydomain/webpages/abc.html

used abc.js which set cookie named mycookie

app server - mydomain/webapis/servicename.

to which api calls were made

I was expecting the cookie in mydomain/webapis/servicename and tried reading it but it was not being sent. After reading comment from the answer, I checked in browser's development tool that mycookie's path was set to "/webpages" and hence not available in service call to

mydomain/webapis/servicename

So While setting cookie from jquery, this is what I did -

$.cookie("mycookie","mayvalue",{**path:'/'**});