Programs & Examples On #Unbuffered

How to avoid pressing Enter with getchar() for reading a single character only?

Can create a new function that checks for Enter:

#include <stdio.h>

char getChar()
{
    printf("Please enter a char:\n");

    char c = getchar();
    if (c == '\n')
    {
        c = getchar();
    }

    return c;
}

int main(int argc, char *argv[])
{
    char ch;
    while ((ch = getChar()) != '.')
    {
        printf("Your char: %c\n", ch);
    }

    return 0;
}

How to concatenate multiple lines of output to one line?

This is an example which produces output separate by commas. You can replace the comma by whatever separator you need.

cat <<EOD | xargs | sed 's/ /,/g'
> 1
> 2
> 3
> 4
> 5
> EOD

produces:

1,2,3,4,5

What are the main differences between JWT and OAuth authentication?

JWT (JSON Web Tokens)- It is just a token format. JWT tokens are JSON encoded data structures contains information about issuer, subject (claims), expiration time etc. It is signed for tamper proof and authenticity and it can be encrypted to protect the token information using symmetric or asymmetric approach. JWT is simpler than SAML 1.1/2.0 and supported by all devices and it is more powerful than SWT(Simple Web Token).

OAuth2 - OAuth2 solve a problem that user wants to access the data using client software like browse based web apps, native mobile apps or desktop apps. OAuth2 is just for authorization, client software can be authorized to access the resources on-behalf of end user using access token.

OpenID Connect - OpenID Connect builds on top of OAuth2 and add authentication. OpenID Connect add some constraint to OAuth2 like UserInfo Endpoint, ID Token, discovery and dynamic registration of OpenID Connect providers and session management. JWT is the mandatory format for the token.

CSRF protection - You don't need implement the CSRF protection if you do not store token in the browser's cookie.

jQuery click function doesn't work after ajax call?

The problem is that .click only works for elements already on the page. You have to use something like on if you are wiring up future elements

$("#LangTable").on("click",".deletelanguage", function(){
  alert("success");
});

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

! [rejected] master -> master (fetch first)

try:

git fetch origin master
git merge origin master

After to wrote this code I received other error: (non-fast-forward)

I write this code:

git fetch origin master:tmp
git rebase tmp
git push origin HEAD:master
git branch -D tmp

And resolved my problem

How to delete file from public folder in laravel 5.1

public function destroy($id) {
    $news = News::findOrFail($id);
    $image_path = app_path("images/news/".$news->photo);

    if(file_exists($image_path)){
        //File::delete($image_path);
        File::delete( $image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','??? ??????? ???  ??');
}

How to customize the configuration file of the official PostgreSQL Docker image?

A fairly low-tech solution to this problem seems to be to declare the service (I'm using swarm on AWS and a yaml file) with your database files mounted to a persisted volume (here AWS EFS as denoted by the cloudstor:aws driver specification).

  version: '3.3'
  services:
    database:
      image: postgres:latest
      volumes:
        - postgresql:/var/lib/postgresql
        - postgresql_data:/var/lib/postgresql/data
    volumes:
       postgresql:
         driver: "cloudstor:aws" 
       postgresql_data:
         driver: "cloudstor:aws"
  1. The db comes up as initialized with the image default settings.
  2. You edit the conf settings inside the container, e.g if you want to increase the maximum number of concurrent connections that requires a restart
  3. stop the running container (or scale the service down to zero and then back to one)
  4. the swarm spawns a new container, which this time around picks up your persisted configuration settings and merrily applies them.

A pleasant side-effect of persisting your configuration is that it also persists your databases (or was it the other way around) ;-)

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How can I use async/await at the top level?

i like this clever syntax to do async work from an entrypoint

void async function main() {
  await doSomeWork()
  await doMoreWork()
}()

horizontal scrollbar on top and bottom of table

First of all, great answer, @StanleyH. If someone is wondering how to make the double scroll container with dynamic width :

css

.wrapper1, .wrapper2 { width: 100%; overflow-x: scroll; overflow-y: hidden; }
.wrapper1 { height: 20px; }
.div1 { height: 20px; }
.div2 { overflow: none; }

js

$(function () {
    $('.wrapper1').on('scroll', function (e) {
        $('.wrapper2').scrollLeft($('.wrapper1').scrollLeft());
    }); 
    $('.wrapper2').on('scroll', function (e) {
        $('.wrapper1').scrollLeft($('.wrapper2').scrollLeft());
    });
});
$(window).on('load', function (e) {
    $('.div1').width($('table').width());
    $('.div2').width($('table').width());
});

html

<div class="wrapper1">
    <div class="div1"></div>
</div>
<div class="wrapper2">
    <div class="div2">
        <table>
            <tbody>
                <tr>
                    <td>table cell</td>
                    <td>table cell</td>
                    <!-- ... -->
                    <td>table cell</td>
                    <td>table cell</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

demo

http://jsfiddle.net/simo/67xSL/

convert an enum to another type of enum

public static TEnum ConvertByName<TEnum>(this Enum source, bool ignoreCase = false) where TEnum : struct
{
    // if limited by lack of generic enum constraint
    if (!typeof(TEnum).IsEnum)
    {
        throw new InvalidOperationException("enumeration type required.");
    }

    TEnum result;
    if (!Enum.TryParse(source.ToString(), ignoreCase, out result))
    {
        throw new Exception("conversion failure.");
    }

    return result;
}

Branch from a previous commit using Git

You can do it in Stash.

  1. Click the commit
  2. On the right top of the screen click "Tag this commit"
  3. Then you can create the new branch from the tag you just created.

Multiple returns from a function

I had a similar problem - so I tried around and googled a bit (finding this thread). After 5 minutes of try and error I found out that you can simply use "AND" to return two (maybe more - not tested yet) in one line of return.

My code:

  function get_id(){
    global $b_id, $f_id;
    // stuff happens
    return $b_id AND $f_id;
  }
  //later in the code:
  get_id();
  var_dump($b_id);
  var_dump($f_id); // tested output by var_dump

it works. I got both the values I expected to get/should get. I hope I could help anybody reading this thread :)

How to access parameters in a Parameterized Build?

Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:

getBinding().hasVariable("MY_PARAM")

Is not working anymore. Please try this instead:

def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false

How do I use a pipe to redirect the output of one command to the input of another?

You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...

C:\>PowerShell -Command "temperature | prismcom.exe usb"

Please read up on Understanding the Windows PowerShell Pipeline

You can also type in C:\>PowerShell at the command-line and it'll put you in PS C:\> mode instanctly, where you can directly start writing PS.

How to generate javadoc comments in Android Studio

Here we can some something like this. And instead of using any shortcut we can write "default" comments at class/ package /project level. And modify as per requirement

   *** Install JavaDoc Plugin ***



     1.Press shift twice and  Go to Plugins.
     2. search for JavaDocs plugin
     3. Install it. 
     4. Restart Android Studio.
     5. Now, rightclick on Java file/package and goto 
        JavaDocs >> create javadocs for all elements
        It will  generate all default comments.

Advantage is that, you can create comment block for all the methods at a time.

How to amend a commit without changing commit message (reusing the previous one)?

git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

CSS center display inline block?

The accepted solution wouldn't work for me as I need a child element with display: inline-block to be both horizontally and vertically centered within a 100% width parent.

I used Flexbox's justify-content and align-items properties, which respectively allow you to center elements horizontally and vertically. By setting both to center on the parent, the child element (or even multiple elements!) will be perfectly in the middle.

This solution does not require fixed width, which would have been unsuitable for me as my button's text will change.

Here is a CodePen demo and a snippet of the relevant code below:

_x000D_
_x000D_
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
_x000D_
<div class="parent">
  <a class="child" href="#0">Button</a>
</div>
_x000D_
_x000D_
_x000D_

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

Simple search MySQL database using php

This is a better code that will help you through.
With your database, but rather, I have used mysql not mysqli
Enjoy it.

<body>

<form action="" method="post">

  <input name="search" type="search" autofocus><input type="submit" name="button">

</form>

<table>
  <tr><td><b>First Name</td><td></td><td><b>Last Name</td></tr>

<?php

$con=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('employee');


if(isset($_POST['button'])){    //trigger button click

  $search=$_POST['search'];

  $query=mysql_query("select * from employees where first_name like '%{$search}%' || last_name like '%{$search}%' ");

if (mysql_num_rows($query) > 0) {
  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}else{
    echo "No employee Found<br><br>";
  }

}else{                          //while not in use of search  returns all the values
  $query=mysql_query("select * from employees");

  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}

mysql_close();
?>

How can I stop a running MySQL query?

If you have mysqladmin available, you may get the list of queries with:

> mysqladmin -uUSERNAME -pPASSWORD pr

+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id  | User | Host            | db     | Command | Time | State        | Info             |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query   | 292  | Sending data | DELETE FROM      |
| 145 | root | localhost:55745 |        | Query   | 0    |              | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+

Then you may stop the mysql process that is hosting the long running query:

> mysqladmin -uUSERNAME -pPASSWORD kill 137

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

You didn't specify a GradientType:

background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */

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

I get exception when using Thread.sleep(x) or wait()

Use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

Sleep for one second or

TimeUnit.MINUTES.sleep(1);

Sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a [ScheduledExecutorService][1] and either [scheduleAtFixedRate][2] or [scheduleWithFixedDelay][3].

To run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

What does string::npos mean in this code?

size_t is an unsigned variable, thus 'unsigned value = - 1' automatically makes it the largest possible value for size_t: 18446744073709551615

Why are there two ways to unstage a file in Git?

Just use:

git reset HEAD <filename>

This unstages the file and keeps the changes you did to it, so you can, in turn, change branches if you wanted and git add those files to another branch instead. All changes are kept.

How to measure time in milliseconds using ANSI C?

I always use the clock_gettime() function, returning time from the CLOCK_MONOTONIC clock. The time returned is the amount of time, in seconds and nanoseconds, since some unspecified point in the past, such as system startup of the epoch.

#include <stdio.h>
#include <stdint.h>
#include <time.h>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
  return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
           ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}

int main(int argc, char **argv)
{
  struct timespec start, end;
  clock_gettime(CLOCK_MONOTONIC, &start);

  // Some code I am interested in measuring 

  clock_gettime(CLOCK_MONOTONIC, &end);

  uint64_t timeElapsed = timespecDiff(&end, &start);
}

R Error in x$ed : $ operator is invalid for atomic vectors

From the help file about $ (See ?"$") you can read:

$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.

Now, let's check whether x is recursive

> is.recursive(x)
[1] FALSE

A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check

> is.atomic(x)
[1] TRUE

Therefore you get an error when applying $ to a vector (non-recursive object), use [ instead:

> x["ed"]
ed 
 2 

You can also use getElement

> getElement(x, "ed")
[1] 2

How to set size for local image using knitr for markdown?

Un updated answer: in knitr 1.17 you can simply use

![Image Title](path/to/your/image){width=250px}

edit as per comment from @jsb

Note this works only without spaces, e.g. {width=250px} not {width = 250px}

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

.htaccess rewrite subdomain to directory

For any sub domain request, use this:

RewriteEngine on 
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co 
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co 
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+) 
RewriteRule ^(.*)$ /%1/$1 [L] 

Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.

$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)

<?php
if(!isset($_GET['json']))
    die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Radio buttons and label to display in same line

I always avoid using float:left but instead I use display: inline

_x000D_
_x000D_
.wrapper-class input[type="radio"] {_x000D_
  width: 15px;_x000D_
}_x000D_
_x000D_
.wrapper-class label {_x000D_
  display: inline;_x000D_
  margin-left: 5px;_x000D_
  }
_x000D_
<div class="wrapper-class">_x000D_
  <input type="radio" id="radio1">_x000D_
  <label for="radio1">Test Radio</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

in /etc/my.cnf add this lines:

[client]
socket=/var/lib/mysql/mysql.sock <= this path should be also same as is[mysqld]

And restart the service with: service mysql restart

this worked for me

How to change the locale in chrome browser

Use ModHeader Chrome extension.

enter image description here

Or you can try more complex value like Accept-Language: en-US,en;q=0.9,ru;q=0.8,th;q=0.7

jQuery selectors on custom data attributes using HTML5

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.

The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not).

In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches

var facebook = $('[data-company$="book"]',group);//facebook

_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
  <li data-company="Microsoft">Microsoft</li>_x000D_
  <li data-company="Google">Google</li>_x000D_
  <li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

@selector() in Swift?

It may be useful to note where you setup the control that triggers the action matters.

For example, I have found that when setting up a UIBarButtonItem, I had to create the button within viewDidLoad or else I would get an unrecognized selector exception.

override func viewDidLoad() {
    super.viewDidLoad() 

    // add button
    let addButton = UIBarButtonItem(image: UIImage(named: "746-plus-circle.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("addAction:"))
    self.navigationItem.rightBarButtonItem = addButton
}

func addAction(send: AnyObject?) {     
    NSLog("addAction")
}

Reading Space separated input in python

If you have it in a string, you can use .split() to separate them.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>

How to install mechanize for Python 2.7?

I dont know why , but "pip install mechanize" didnt work for me . easy install worked anyway . Try this :

sudo easy_install mechanize

Is it bad practice to use break to exit a loop in Java?

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.

How to implement a Keyword Search in MySQL?

You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches

This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.

Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching

In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:

SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance  FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;

I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.

Depending in your criterias you can use either options.

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

How to make matrices in Python?

you can also use append function

b = [ ]

for x in range(0, 5):
    b.append(["O"] * 5)

def print_b(b):
    for row in b:
        print " ".join(row)

How to bring an activity to foreground (top of stack)?

If you want to bring an activity to the top of the stack when clicking on a Notification then you may need to do the following to make the FLAG_ACTIVITY_REORDER_TO_FRONT work:

The solution for me for this was to make a broadcast receiver that listens to broadcast actions that the notification triggers. So basically:

  1. Notification triggers a broadcast action with an extra the name of the activity to launch.

  2. Broadcast receiver catches this when the notification is clicked, then creates an intent to launch that activity using the FLAG_ACTIVITY_REORDER_TO_FRONT flag

  3. Activity is brought to the top of activity stack, no duplicates.

A Simple, 2d cross-platform graphics library for c or c++?

What about SDL?

Perhaps it's a bit too complex for your needs, but it's certainly cross-platform.

How does the modulus operator work?

This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj

The modulus function works something like this:

     function modulus(x,y){
       var m = Math.floor(x / y);
       var r = m * y;
       return x - r;
     }

How to implement the --verbose or -v option into a script?

Use the logging module:

import logging as log
…
args = p.parse_args()
if args.verbose:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    log.info("Verbose output.")
else:
    log.basicConfig(format="%(levelname)s: %(message)s")

log.info("This should be verbose.")
log.warning("This is a warning.")
log.error("This is an error.")

All of these automatically go to stderr:

% python myprogram.py
WARNING: This is a warning.
ERROR: This is an error.

% python myprogram.py -v
INFO: Verbose output.
INFO: This should be verbose.
WARNING: This is a warning.
ERROR: This is an error.

For more info, see the Python Docs and the tutorials.

Preferred method to store PHP arrays (json_encode vs serialize)

I would suggest you to use Super Cache, which is a file cache mechanism which won't use json_encode or serialize. It is simple to use and really fast compared to other PHP Cache mechanism.

https://packagist.org/packages/smart-php/super-cache

Ex:

<?php
require __DIR__.'/vendor/autoload.php';
use SuperCache\SuperCache as sCache;

//Saving cache value with a key
// sCache::cache('<key>')->set('<value>');
sCache::cache('myKey')->set('Key_value');

//Retrieving cache value with a key
echo sCache::cache('myKey')->get();
?>

Escape double quotes for JSON in Python

Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes

Sequence Permission in Oracle

Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:

    select * from dba_tab_privs where table_name = 'sequence_name';

How to change background color in android app

The best way using background with gradient as it does not increase app size of your app images are poison for android app so try to use it less instead of using one color as a background you can use multiple colors in one background. enter image description here enter image description here

enter image description hereenter image description here

List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

C - function inside struct

How about this?

#include <stdio.h>

typedef struct hello {
    int (*someFunction)();
} hello;

int foo() {
    return 0;
}

hello Hello() {
    struct hello aHello;
    aHello.someFunction = &foo;
    return aHello;
}

int main()
{
    struct hello aHello = Hello();
    printf("Print hello: %d\n", aHello.someFunction());

    return 0;
} 

What is the best way to convert an array to a hash in Ruby

Not sure if it's the best way, but this works:

a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
  m1[a[x*2]] = a[x*2 + 1]
end

b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
  m2[x] = y
end

pandas DataFrame: replace nan values with average of columns

# To read data from csv file
Dataset = pd.read_csv('Data.csv')

X = Dataset.iloc[:, :-1].values

# To calculate mean use imputer class
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])

How to remove unused C/C++ symbols with GCC and ld?

It seems to me that the answer provided by Nemo is the correct one. If those instructions do not work, the issue may be related to the version of gcc/ld you're using, as an exercise I compiled an example program using instructions detailed here

#include <stdio.h>
void deadcode() { printf("This is d dead codez\n"); }
int main(void) { printf("This is main\n"); return 0 ; }

Then I compiled the code using progressively more aggressive dead-code removal switches:

gcc -Os test.c -o test.elf
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections -Wl,--strip-all

These compilation and linking parameters produced executables of size 8457, 8164 and 6160 bytes, respectively, the most substantial contribution coming from the 'strip-all' declaration. If you cannot produce similar reductions on your platform,then maybe your version of gcc does not support this functionality. I'm using gcc(4.5.2-8ubuntu4), ld(2.21.0.20110327) on Linux Mint 2.6.38-8-generic x86_64

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

How to trigger a file download when clicking an HTML button or JavaScript

Anywhere between your <body> and </body> tags, put in a button using the below code:

<button>
    <a href="file.doc" download>Click to Download!</a>
</button>

This is sure to work!

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

In MacOS Mojave, the location is:

/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre/lib/security/cacerts 

If using sdkman to manage java versions, the cacerts is in

~/.sdkman/candidates/java/current/jre/lib/security

Create table (structure) from existing table

  1. If you Want to copy Same DataBase

    Select * INTO NewTableName from OldTableName
    
  2. If Another DataBase

    Select * INTO NewTableName from DatabaseName.OldTableName
    

How does one parse XML files?

If you're using .NET 2.0, try XmlReader and its subclasses XmlTextReader, and XmlValidatingReader. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.

If you need XPath capabilities, try the XPathNavigator. If you need the entire document in memory try XmlDocument.

How to check if a value is not null and not empty string in JS

I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.

/**
 * Test if the given value equals null or the empty string.
 * 
 * @param {string} value
**/
const isEmpty = (value) => value === null || value === '';

// Test:
isEmpty('');        // true
isEmpty(null);      // true
isEmpty(1);         // false
isEmpty(0);         // false
isEmpty(undefined); // false

What is a segmentation fault?

Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don't find an error in your code, maybe a memtest could help you.

The solution in this case, change the RAM.

edit:

Here there is a reference: Segmentation fault by hardware

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

Angular 2 optional route parameter

The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

Then use the matcher in your route config:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

What is the proper way to display the full InnerException?

You can simply print exception.ToString() -- that will also include the full text for all the nested InnerExceptions.

How to catch exception correctly from http.request()?

New service updated to use the HttpClientModule and RxJS v5.5.x:

import { Injectable }                    from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable }                    from 'rxjs/Observable';
import { catchError, tap }               from 'rxjs/operators';
import { SomeClassOrInterface}           from './interfaces';
import 'rxjs/add/observable/throw';

@Injectable() 
export class MyService {
    url = 'http://my_url';
    constructor(private _http:HttpClient) {}
    private handleError(operation: String) {
        return (err: any) => {
            let errMsg = `error in ${operation}() retrieving ${this.url}`;
            console.log(`${errMsg}:`, err)
            if(err instanceof HttpErrorResponse) {
                // you could extract more info about the error if you want, e.g.:
                console.log(`status: ${err.status}, ${err.statusText}`);
                // errMsg = ...
            }
            return Observable.throw(errMsg);
        }
    }
    // public API
    public getData() : Observable<SomeClassOrInterface> {
        // HttpClient.get() returns the body of the response as an untyped JSON object.
        // We specify the type as SomeClassOrInterfaceto get a typed result.
        return this._http.get<SomeClassOrInterface>(this.url)
            .pipe(
                tap(data => console.log('server data:', data)), 
                catchError(this.handleError('getData'))
            );
    }

Old service, which uses the deprecated HttpModule:

import {Injectable}              from 'angular2/core';
import {Http, Response, Request} from 'angular2/http';
import {Observable}              from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
//import 'rxjs/Rx';  // use this line if you want to be lazy, otherwise:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';  // debug
import 'rxjs/add/operator/catch';

@Injectable()
export class MyService {
    constructor(private _http:Http) {}
    private _serverError(err: any) {
        console.log('sever error:', err);  // debug
        if(err instanceof Response) {
          return Observable.throw(err.json().error || 'backend server error');
          // if you're using lite-server, use the following line
          // instead of the line above:
          //return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
    }
    private _request = new Request({
        method: "GET",
        // change url to "./data/data.junk" to generate an error
        url: "./data/data.json"
    });
    // public API
    public getData() {
        return this._http.request(this._request)
          // modify file data.json to contain invalid JSON to have .json() raise an error
          .map(res => res.json())  // could raise an error if invalid JSON
          .do(data => console.log('server data:', data))  // debug
          .catch(this._serverError);
    }
}

I use .do() (now .tap()) for debugging.

When there is a server error, the body of the Response object I get from the server I'm using (lite-server) contains just text, hence the reason I use err.text() above rather than err.json().error. You may need to adjust that line for your server.

If res.json() raises an error because it could not parse the JSON data, _serverError will not get a Response object, hence the reason for the instanceof check.

In this plunker, change url to ./data/data.junk to generate an error.


Users of either service should have code that can handle the error:

@Component({
    selector: 'my-app',
    template: '<div>{{data}}</div> 
       <div>{{errorMsg}}</div>`
})
export class AppComponent {
    errorMsg: string;
    constructor(private _myService: MyService ) {}
    ngOnInit() {
        this._myService.getData()
            .subscribe(
                data => this.data = data,
                err  => this.errorMsg = <any>err
            );
    }
}

EditorFor() and html properties

UPDATE: hm, obviously this won't work because model is passed by value so attributes are not preserved; but I leave this answer as an idea.

Another solution, I think, would be to add your own TextBox/etc helpers, that will check for your own attributes on model.

public class ViewModel
{
  [MyAddAttribute("class", "myclass")]
  public string StringValue { get; set; }
}

public class MyExtensions
{
  public static IDictionary<string, object> GetMyAttributes(object model)
  {
     // kind of prototype code...
     return model.GetType().GetCustomAttributes(typeof(MyAddAttribute)).OfType<MyAddAttribute>().ToDictionary(
          x => x.Name, x => x.Value);
  }
}

<!-- in the template -->
<%= Html.TextBox("Name", Model, MyExtensions.GetMyAttributes(Model)) %>

This one is easier but not as convinient/flexible.

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

How can I run multiple curl requests processed sequentially?

Another crucial method not mentioned here is using the same TCP connection for multiple HTTP requests, and exactly one curl command for this.

This is very useful to save network bandwidth, client and server resources, and overall the need of using multiple curl commands, as curl by default closes the connection when end of command is reached.

Keeping the connection open and reusing it is very common for standard clients running a web-app.

Starting curl version 7.36.0, the --next or -: command-line option allows to chain multiple requests, and usable both in command-line and scripting.

For example:

  • Sending multiple requests on the same TCP connection:

curl http://example.com/?update_=1 -: http://example.com/foo

  • Sending multiple different HTTP requests on the same connection:

curl http://example.com/?update_=1 -: -d "I am posting this string" http://example.com/?update_=2

  • Sending multiple HTTP requests with different curl options for each request:

curl -o 'my_output_file' http://example.com/?update_=1 -: -d "my_data" -s -m 10 http://example.com/foo -: -o /dev/null http://example.com/random

From the curl manpage:

-:, --next

Tells curl to use a separate operation for the following URL and associated options. This allows you to send several URL requests, each with their own specific options, for example, such as different user names or custom requests for each.

-:, --next will reset all local options and only global ones will have their values survive over to the operation following the -:, --next instruction. Global options include -v, --verbose, --trace, --trace-ascii and --fail-early.

For example, you can do both a GET and a POST in a single command line:

curl www1.example.com --next -d postthis www2.example.com

Added in 7.36.0.

SQL Insert Multiple Rows

For MSSQL, there are two ways:(Consider you have a 'users' table,below both examples are using this table for example)

1) In case, you need to insert different values in users table. Then you can write statement like:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

2) Another case, if you need to insert same value for all rows(for example, 10 rows you need to insert here). Then you can use below sample statement:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe')
GO 10

Hope this helps.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

for sbt, use below versions

val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"

val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"

val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"

How does one represent the empty char?

You can use c[i]= '\0' or simply c[i] = (char) 0.

The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.

Angular2: child component access parent class variable/function

You can do this In the parent component declare:

get self(): ParenComponentClass {
        return this;
    }

In the child component,after include the import of ParenComponentClass, declare:

private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
    this._parent = value;
}

get parent(): ParenComponentClass {
    return this._parent;
}

Then in the template of the parent you can do

<childselector [parent]="self"></childselector>

Now from the child you can access public properties and methods of parent using

this.parent

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

BTW, Yandex Metrica also uses IDFA.

./Pods/YandexMobileMetrica/libYandexMobileMetrica.a

They say on their GitHub page that

"Starting from version 1.6.0 Yandex AppMetrica became also a tracking instrument and uses Apple idfa to attribute installs. Because of that during submitting your application to the AppStore you will be prompted with three checkboxes to state your intentions for idfa usage. As Yandex AppMetrica uses idfa for attributing app installations you need to select Attribute this app installation to a previously served advertisement."

So, I will try to select this checkbox and send my app without actually no any ads in it.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

Check if a file is executable

Seems nobody noticed that -x operator does not differ file with directory.

So to precisely check an executable file, you may use [[ -f SomeFile && -x SomeFile ]]

Replacing all non-alphanumeric characters with empty strings

return value.replaceAll("[^A-Za-z0-9 ]", "");

This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.

What key shortcuts are to comment and uncomment code?

"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding

Laravel update model with unique validation rule for attribute

You can trying code bellow

return [
    'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
    'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
    'password' => 'required|min:6',
    'confirm-password' => 'required|same:password',
];

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

jQuery $("#radioButton").change(...) not firing during de-selection

<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>                  

jquery part

$(".rg").change(function () {

if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', 'disabled');
        }
                    });

here is the DEMO

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

Property '...' has no initializer and is not definitely assigned in the constructor

Go to your tsconfig.json file and change "noImplicitReturns": false then add "strictPropertyInitialization": false to your tsconfig.json file under "compilerOptions" property. Here is what my tsconfig.json file looks like

tsconfig.json

{
  ...
  "compilerOptions": {
        ....
        "noImplicitReturns": false,
        ....
        "strictPropertyInitialization": false
  },
  "angularCompilerOptions": {
     ......
  }  
}

Hope this will help !! Good Luck

Replacement for "rename" in dplyr

I tried to use dplyr::rename and I get an error:

occ_5d <- dplyr::rename(occ_5d, rowname='code_5d')
Error: Unknown column `code_5d` 
Call `rlang::last_error()` to see a backtrace

I instead used the base R function which turns out to be quite simple and effective:

names(occ_5d)[1] = "code_5d"

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Can you use @Autowired with static fields?

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Force re-download of release dependency using Maven

mvn clean install -U

-U means force update of dependencies.

If you want to update a single dependency without clean or -U you could just remove it from your local repo and then build.

Block direct access to a file over http but allow php script access

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow
Deny from all

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

How to detect when keyboard is shown and hidden

You could use KBKeyboardObserver library. It contains some examples and provides simple interface.

Selecting only numeric columns from a data frame

Filter() from the base package is the perfect function for that use-case: You simply have to code:

Filter(is.numeric, x)

It is also much faster than select_if():

library(microbenchmark)
microbenchmark(
    dplyr::select_if(mtcars, is.numeric),
    Filter(is.numeric, mtcars)
)

returns (on my computer) a median of 60 microseconds for Filter, and 21 000 microseconds for select_if (350x faster).

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Drop root privileges after you bind to port 80 (or 443).

This allows port 80/443 to remain protected, while still preventing you from serving requests as root:

function drop_root() {
    process.setgid('nobody');
    process.setuid('nobody');
}

A full working example using the above function:

var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
    res.write("Success!");
    res.end();
});

server.listen(80, null, null, function() {
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
    drop_root();
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});

See more details at this full reference.

How to extract Month from date in R

For some time now, you can also only rely on the data.table package and its IDate class plus associated functions. (Check ?as.IDate()). So, no need to additionally install lubridate.

require(data.table)

some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

JavaScript - Getting HTML form values

HTML:

<input type="text" name="name" id="uniqueID" value="value" />

JS:

var nameValue = document.getElementById("uniqueID").value;

SQL Server: Get data for only the past year

The other suggestions are good if you have "SQL only".

However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.

At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.

Typescript es6 import module "File is not a module error"

In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.

VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.

for example, everything after the first line of the Class definition was auto-indented during the paste.

export class MyClass extends Something<string> {
    public blah: string = null;

    constructor() { ... }
  }

Service will not start: error 1067: the process terminated unexpectedly

Goto:

Registry-> HKEY_LOCAL??_MACHINE-> System-> Cur??rentControlSet-> Servi??ces.

Find the concerned service & delete it. Close regedit. Reboot the PC & Re-install the concerned service. Now the error should be gone.

What is a .NET developer?

Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.

Remove last character from string. Swift language

Swift 4.0 (also Swift 5.0)

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

Swift 3.0

The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Or the in-place version:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

Thanks Zmey, Rob Allen!

Swift 2.0+ Way

There are a few ways to accomplish this:

Via the Foundation extension, despite not being part of the Swift library:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Using the removeRange() method (which alters the name):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

Using the dropLast() function:

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Old String.Index (Xcode 6 Beta 4 +) Way

Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

Alternatively (for a more practical, but less educational example) you can use endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

Note: I found this to be a great starting point for understanding String.Index

Old (pre-Beta 4) Way

You can simply use the substringToIndex() function, providing it one less than the length of the String:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"

PHP - Session destroy after closing browser

Use a keep alive.

On login:

session_start();
$_SESSION['last_action'] = time();

An ajax call every few (eg 20) seconds:

windows.setInterval(keepAliveCall, 20000);

Server side keepalive.php:

session_start();
$_SESSION['last_action'] = time();

On every other action:

session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
  // destroy the session and quit
}

php: loop through json array

Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

How to execute a program or call a system command from Python

It can be this simple:

import os
cmd = "your command"
os.system(cmd)

Select first row in each GROUP BY group?

On Oracle 9.2+ (not 8i+ as originally stated), SQL Server 2005+, PostgreSQL 8.4+, DB2, Firebird 3.0+, Teradata, Sybase, Vertica:

WITH summary AS (
    SELECT p.id, 
           p.customer, 
           p.total, 
           ROW_NUMBER() OVER(PARTITION BY p.customer 
                                 ORDER BY p.total DESC) AS rk
      FROM PURCHASES p)
SELECT s.*
  FROM summary s
 WHERE s.rk = 1

Supported by any database:

But you need to add logic to break ties:

  SELECT MIN(x.id),  -- change to MAX if you want the highest
         x.customer, 
         x.total
    FROM PURCHASES x
    JOIN (SELECT p.customer,
                 MAX(total) AS max_total
            FROM PURCHASES p
        GROUP BY p.customer) y ON y.customer = x.customer
                              AND y.max_total = x.total
GROUP BY x.customer, x.total

Is there a better jQuery solution to this.form.submit();?

You can always JQuery-ize your form.submit, but it may just call the same thing:

$("form").submit(); // probably able to affect multiple forms (good or bad)

// or you can address it by ID
$("#yourFormId").submit();

You can also attach functions to the submit event, but that is a different concept.

How can I make the cursor turn to the wait cursor?

Use this with WPF:

Cursor = Cursors.Wait;

// Your Heavy work here

Cursor = Cursors.Arrow;

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

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

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

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

Styling HTML5 input type number

There are only 4 specific atrributes:

  1. value - Value is the default value of the input box when a page is first loaded. This is a common attribute for element regardless which type you are using.
  2. min - Obviously, the minimum value you of the number. I should have specified minimum value to 0 for my demo up there as a negative number doesn't make sense for number of movie watched in a week.
  3. max - Apprently, this represents the biggest number of the number input.
  4. step - Step scale factor, default value is 1 if this attribute is not specified.

So you cannot control length of what user type by keyword. But the implementation of browsers may change.

for each loop in groovy

This one worked for me:

def list = [1,2,3,4]
for(item in list){
    println item
}

Source: Wikia.

Execute stored procedure with an Output parameter?

Return val from procedure

ALTER PROCEDURE testme @input  VARCHAR(10),
                       @output VARCHAR(20) output
AS
  BEGIN
      IF @input >= '1'
        BEGIN
            SET @output = 'i am back';

            RETURN;
        END
  END

DECLARE @get VARCHAR(20);

EXEC testme
  '1',
  @get output

SELECT @get 

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Getting value from table cell in JavaScript...not jQuery

the above guy was close but here is what you want:

       var table = document.getElementById(tableID);
       var rowCount = table.rows.length;        
         for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].firstChild.value);
        }
    }
        }catch(e) {
            alert(e);
        }

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

Clear all fields in a form upon going back with browser back button

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:

window.addEventListener("pageshow", () => {
  // update hidden input field
});

See more details for Gecko and WebKit implementations.

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

How can I copy a conditional formatting from one document to another?

To achieve this you can try below steps:

  1. Copy the cell or column which has the conditional formatting you want to copy.
  2. Go to the desired cell or column (maybe other sheets) where you want to apply conditional formatting.
  3. Open the context menu of the desired cell or column (by right-click on it).
  4. Find the "Paste Special" option which has a sub-menu.
  5. Select the "Paste conditional formatting only" option of the sub-menu and done.

How to validate array in Laravel?

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Change the maximum upload file size

You can change it via an .htaccess file.

.htaccess files are stored in the same directory as your .php files are. They modify configuration for that folder and all sub-folders. You simply use them by creating an .htaccess file in the directory of your choice (or modify it if present).

The following should enable you to increase your upload limit (if the server provider allows PHP config changes via .htaccess).

php_value upload_max_filesize 40M
php_value post_max_size 42M

How to redirect single url in nginx?

location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

asp:TextBox ReadOnly=true or Enabled=false?

If a control is disabled it cannot be edited and its content is excluded when the form is submitted.

If a control is readonly it cannot be edited, but its content (if any) is still included with the submission.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

The chosen answer is a great start, but it essentially forces list-style-position: inside; styling on the list items, making wrapped text hard to read. Here's a simple workaround that also gives control over the margin between the number and text, and right-aligns the number as per the default behaviour.

ol {
    counter-reset: item;
}
ol li {
    display: block;
    position: relative;
}
ol li:before {
    content: counters(item, ".")".";
    counter-increment: item;
    position: absolute;
    margin-right: 100%;
    right: 10px; /* space between number and text */
}

JSFiddle: http://jsfiddle.net/3J4Bu/

What is the difference between static func and class func in Swift?

Both the static and class keywords allow us to attach methods to a class rather than to instances of a class. For example, you might create a Student class with properties such as name and age, then create a static method numberOfStudents that is owned by the Student class itself rather than individual instances.

Where static and class differ is how they support inheritance. When you make a static method it becomes owned by the class and can't be changed by subclasses, whereas when you use class it may be overridden if needed.

Here is an Example code:

  class Vehicle {
    static func getCurrentSpeed() -> Int {
        return 0
    }

    class func getCurrentNumberOfPassengers() -> Int {
        return 0
    } 

  }

  class Bicycle: Vehicle {
    //This is not allowed
    //Compiler error: "Cannot override static method"
  //  static override func getCurrentSpeed() -> Int {
  //        return 15
  //  }

      class override func getCurrentNumberOfPassengers() -> Int {
        return 1
      }
  }

IIS7: Setup Integrated Windows Authentication like in IIS6

So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.

If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.

Select datatype of the field in postgres

Pulling data type from information_schema is possible, but not convenient (requires joining several columns with a case statement). Alternatively one can use format_type built-in function to do that, but it works on internal type identifiers that are visible in pg_attribute but not in information_schema. Example

SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a JOIN pg_class b ON a.attrelid = b.relfilenode
WHERE a.attnum > 0 -- hide internal columns
AND NOT a.attisdropped -- hide deleted columns
AND b.oid = 'my_table'::regclass::oid; -- example way to find pg_class entry for a table

Based on https://gis.stackexchange.com/a/97834.

How to change a text with jQuery

This should work fine (using .text():

$("#toptitle").text("New word");

How can I remove a style added with .css() function?

Use my Plugin :

$.fn.removeCss=function(all){
        if(all===true){
            $(this).removeAttr('class');
        }
        return $(this).removeAttr('style')
    }

For your case ,Use it as following :

$(<mySelector>).removeCss();

or

$(<mySelector>).removeCss(false);

if you want to remove also CSS defined in its classes :

$(<mySelector>).removeCss(true);

PHP: How to remove all non printable characters in a string?

"cedivad" solved the issue for me with persistent result of Swedish chars ÅÄÖ.

$text = preg_replace( '/[^\p{L}\s]/u', '', $text );

Thanks!

compare differences between two tables in mysql

Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.

<?php

    $User = "<DatabaseUser>";
    $Pass = "<DatabasePassword>";
    $SourceDB = "<SourceDatabase>";
    $TestDB = "<DatabaseToTest>";

    $link = new mysqli( "p:". "localhost", $User, $Pass, "" );

    if ( mysqli_connect_error() ) {

        die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());

    }

    mysqli_set_charset( $link, "utf8" );
    mb_language( "uni" );
    mb_internal_encoding( "UTF-8" );

    $sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';

    $SourceDB_Content = query( $link, $sQuery );

    if ( !is_array( $SourceDB_Content) ) {

        echo "Table $SourceDB cannot be accessed";
        exit(0);

    }

    $sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';

    $TestDB_Content = query( $link, $sQuery );

    if ( !is_array( $TestDB_Content) ) {

        echo "Table $TestDB cannot be accessed";
        exit(0);

    }

    $SourceDB_Tables = array();
    foreach( $SourceDB_Content as $item ) {
        $SourceDB_Tables[] = $item["TABLE_NAME"];
    }

    $TestDB_Tables = array();
    foreach( $TestDB_Content as $item ) {
        $TestDB_Tables[] = $item["TABLE_NAME"];
    }
    //var_dump( $SourceDB_Tables, $TestDB_Tables );
    $LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
    $NoOfDiscrepancies = 0;
    echo "

    <table border='1' width='100%'>
    <tr>
        <td>Table</td>
        <td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
        <td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
        <td>Test result</td>
    <tr>

    ";

    foreach( $LookupTables as $table ) {

        $FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
        $FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
        echo "

    <tr>
        <td>$table</td>
        <td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td> 
        <td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>   
        <td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>  
    </tr>   
        ";

    }

    echo "

    </table>
    <br><br>
    No of discrepancies found: $NoOfDiscrepancies
    ";


    function query( $link, $q ) {

        $result = mysqli_query( $link, $q );

        $errors = mysqli_error($link);
        if ( $errors > "" ) {

            echo $errors;
            exit(0);

        }

        if( $result == false ) return false;
        else if ( $result === true ) return true;
        else {

            $rset = array();

            while ( $row = mysqli_fetch_assoc( $result ) ) {

                $rset[] = $row;

            }

            return $rset;

        }

    }

    function compareTables( $source, $test, $table ) {

        global $link;
        global $NoOfDiscrepancies;

        $sQuery = "

    SELECT column_name,ordinal_position,data_type,column_type FROM
    (
        SELECT
            column_name,ordinal_position,
            data_type,column_type,COUNT(1) rowcount
        FROM information_schema.columns
        WHERE
        (
            (table_schema='$source' AND table_name='$table') OR
            (table_schema='$test' AND table_name='$table')
        )
        AND table_name IN ('$table')
        GROUP BY
            column_name,ordinal_position,
            data_type,column_type
        HAVING COUNT(1)=1
    ) A;    

        ";

        $result = query( $link, $sQuery );

        $data = "";
        if( is_array( $result ) && count( $result ) > 0 ) {

            $NoOfDiscrepancies++;
            $data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";

            foreach( $result as $item ) {

                $data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";

            }

            $data .= "</table>";

            return $data;

        }
        else {

            return "Checked but no discrepancies found!";

        }

    }

?>

Extract Number from String in Python

Your regex looks correct. Are you sure you haven't made a mistake with the variable names? In your code above you mixup total_hotel_reviews_string and str.

>>> import re
>>> s = "3158 reviews"
>>> 
>>> print(re.findall("\d+", s))
['3158']

How to Add Stacktrace or debug Option when Building Android Studio Project

To Increase Maximum heap: Click to open your Android Studio, look at below pictures. Step by step. ANDROID STUDIO v2.1.2

Click to navigate to Settings from the Configure or GO TO FILE SETTINGS at the top of Android Studio.

enter image description here

check also the android compilers from the link to confirm if it also change if not increase to the same size you modify from the compiler link.

Note: You can increase the size base on your memory capacity and remember this setting is base on Android Studio v2.1.2

Adb install failure: INSTALL_CANCELED_BY_USER

I had the same problem before. Here was my solution:

  1. Go to Setting ? find Developer options in System, and click.
  2. TURN ON install via USB in the Debuging section.
  3. Try Run app in Android Studio again!

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

Edit

I've modified the provided code and I believe it now conforms to what is desired:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

Center button under form in bootstrap

Try giving

default width, display it with block and center it with margin: 0 auto;

like this:

<p style="display:block; line-height: 70px; width:200px; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I had the same error today, with XCode 6.1

What I found was that, no matter what I tried, I couldn't get XCode to stop complaining about this Provisioning Profile with a GUID as its name.

The solution was to search for this GUID in the .pbxproj file, which lives within the XCode .xcodeproj folder.

Just find the line containing your GUID:

PROVISIONING_PROFILE = "A9234343-.....34"

and change it to:

PROVISIONING_PROFILE = ""

One other thing to check: Your XCode PROJECT settings contain your Provisioning Profile & Code Signing settings, but, there is a second set under your project's "TARGETS" tab.

So, if XCode is complaining about a Provisioning Profile which isn't the one quoted in your project settings, then go have have a look at the settings shown under "TARGETS" in your XCode project.

(I wish someone had given me this advice, 4 painful hours ago..)

How to drop a database with Mongoose?

Since the remove method is depreciated in the mongoose library we can use the deleteMany function with no parameters passed.

Model.deleteMany();

This will delete all content of this particular Model and your collection will be empty.

What is the Maximum Size that an Array can hold?

Since Length is an int I'd say Int.MaxValue

Inserting a tab character into text using C#

In addition to the anwsers above you can use PadLeft or PadRight:

string name = "John";
string surname = "Smith";

Console.WriteLine("Name:".PadRight(15)+"Surname:".PadRight(15));
Console.WriteLine( name.PadRight(15) + surname.PadRight(15));

This will fill in the string with spaces to the left or right.

SQL - How do I get only the numbers after the decimal?

Make it very simple by query:

select substr('123.123',instr('123.123','.')+1, length('123.123')) from dual;

Put your number or column name instead 123.122

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The big thing to get your head around is that the File class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt or /usr/muggins). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".

  • getPath() fetches the path that the File was created with (../foo.txt)
  • getAbsolutePath() fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt)
  • getCanonicalPath() attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt).

Note I say attempts - in forming a Canonical Path, the VM can throw an IOException. This usually occurs because it is performing some filesystem operations, any one of which could fail.

What should I use to open a url instead of urlopen in urllib3

You do not have to install urllib3. You can choose any HTTP-request-making library that fits your needs and feed the response to BeautifulSoup. The choice is though usually requests because of the rich feature set and convenient API. You can install requests by entering pip install requests in the command line. Here is a basic example:

from bs4 import BeautifulSoup
import requests

url = "url"
response = requests.get(url)

soup = BeautifulSoup(response.content, "html.parser")

How do I set a variable to the output of a command in Bash?

Just to be different:

MOREF=$(sudo run command against $VAR1 | grep name | cut -c7-)

OpenSSL: unable to verify the first certificate for Experian URL

If you are using MacOS use:

sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs

after this Trust anchor not found error disappears

How to automate drag & drop functionality using Selenium WebDriver Java

I used below piece of code. Here dragAndDrop(x,y) is a method of Action class. Which takes two parameters (x,y), source location, and target location respectively

try {
                System.out.println("Drag and Drom started :");
                Thread.sleep(12000);
                Actions actions = new Actions(webdriver);
                WebElement srcElement = webdriver.findElement(By.xpath("source Xpath"));
                WebElement targetElement = webdriver.findElement(By.xpath("Target Xpath"));
                actions.dragAndDrop(srcElement, targetElement); 
                actions.build().perform();
                System.out.println("Drag and Drom complated :");
            } catch (Exception e) {
                System.out.println(e.getMessage());
                resultDetails.setFlag(true);
            }

Install a module using pip for specific python version

Alternatively, if you want to install specific version of the package with the specific version of python, this is the way

sudo python2.7 -m pip install pyudev=0.16

if the "=" doesnt work, use ==

x@ubuntuserv:~$ sudo python2.7 -m pip install pyudev=0.16

Invalid requirement: 'pyudev=0.16' = is not a valid operator. Did you mean == ?

x@ubuntuserv:~$ sudo python2.7 -m pip install pyudev==0.16

works fine

How to generate keyboard events?

For Python2.7(windows32) I installed only pywin32-223. And I wrote simple python`s code:

import win32api
import time
import win32con

# simulate the pressing-DOWN "ARROW key" of 200 times

for i in range(200):
   time.sleep(0.5)
   win32api.keybd_event(0x28, 0,0,0)
   time.sleep(.05)
   win32api.keybd_event(0x28,0 ,win32con.KEYEVENTF_KEYUP ,0)

It can be checked if you run the code and immediately go to the notepad window (where the text already exists) and place the cursor on the top line.

Why should hash functions use a prime number modulus?

I've read the popular wordpress website linked in some of the above popular answers at the top. From what I've understood, I'd like to share a simple observation I made.

You can find all the details in the article here, but assume the following holds true:

  • Using a prime number gives us the "best chance" of an unique value

A general hashmap implementation wants 2 things to be unique.

  • Unique hash code for the key
  • Unique index to store the actual value

How do we get the unique index? By making the initial size of the internal container a prime as well. So basically, prime is involved because it possesses this unique trait of producing unique numbers which we end up using to ID objects and finding indexes inside the internal container.

Example:

key = "key"

value = "value" uniqueId = "k" * 31 ^ 2 + "e" * 31 ^ 1` + "y"

maps to unique id

Now we want a unique location for our value - so we

uniqueId % internalContainerSize == uniqueLocationForValue , assuming internalContainerSize is also a prime.

I know this is simplified, but I'm hoping to get the general idea through.

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

Empty set literal?

Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ? = frozenset() (? is U+03D5) and use it instead.

How to JSON decode array elements in JavaScript?

JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.

You will then have a JavaScript datastructure that you can traverse for the data you need.

How to get document height and width without using jquery

This should work for all browsers/devices:

function getActualWidth()
{
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

Set today's date as default date in jQuery UI datepicker

$("#date").datepicker.regional[""].dateFormat = 'dd/mm/yy';
$("#date").datepicker("setDate", new Date());

Always work for me

In php, is 0 treated as empty?

From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.

Upload Progress Bar in PHP

One PHP-ish (5.2+) & no-Flash way that worked nicely for me:

First, see this post explaining how to get "uploadprogress" extension up and running.

Then, in the page containing the form that you are uploading file(s) from, create the following iframe:

<iframe id="progress_iframe" src="" style="display:none;" scrolling="no" frameborder="0"></iframe>

Next, add this code to your "Submit" button:

onclick="function set() { f=document.getElementById('progress_iframe'); f.style.display='block'; f.src='uploadprogress.php?id=<?=$upload_id?>';} setTimeout(set);"

Now you have a hidden iframe in your form that will come visible and show contents of uploadprogress.php when you click "Submit" to start uploading files. $upload_id must be the same that you are using as the value of hidden field "UPLOAD_IDENTIFIER" in your form.

The uploadprogress.php itself looks about like this (fix and adjust to your needs):

<html>
<head>
<META HTTP-EQUIV='REFRESH' CONTENT='1;URL=?id=<?=$_GET['id']?>'>
</head>
<body>
Upload progress:<br />
<?php
    if(!$_GET['id']) die;
    $info = uploadprogress_get_info($_GET['id']);
    $kbytes_total = round($info['bytes_total'] / 1024);
    $kbytes_uploaded = round($info['bytes_uploaded'] / 1024);
    echo $kbytes_uploaded.'/'.$kbytes_total.' KB';
?>
</body>
</html>

Note that is self-refreshes every second. You can surely add some nice visual progress bar here (like 2 nested <div>s with different colors) if you like. The iframe with upload progress naturally only works while the upload is in progress, and ends its visible life once the form is submitted and browser reloads to the next page.

How to upload (FTP) files to server in a bash script?

echo -e "open <ftp.hostname>\nuser <username> <password>\nbinary\nmkdir New_Folder\nquit"|ftp -nv

Telling Python to save a .txt file to a certain directory on Windows and Mac

A small update to this. raw_input() is renamed as input() in Python 3.

Python 3 release note

How do I increase memory on Tomcat 7 when running as a Windows Service?

If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8

08/14/2019  10:24 PM           116,648 Tomcat-Custom.exe
08/14/2019  10:24 PM           119,720 Tomcat-Customw.exe
               2 File(s)        236,368 bytes

Running the "w" terminated executable will let you configure Xmx in the Java tab
enter image description here

Fastest way to check if a value exists in a list

It sounds like your application might gain advantage from the use of a Bloom Filter data structure.

In short, a bloom filter look-up can tell you very quickly if a value is DEFINITELY NOT present in a set. Otherwise, you can do a slower look-up to get the index of a value that POSSIBLY MIGHT BE in the list. So if your application tends to get the "not found" result much more often then the "found" result, you might see a speed up by adding a Bloom Filter.

For details, Wikipedia provides a good overview of how Bloom Filters work, and a web search for "python bloom filter library" will provide at least a couple useful implementations.

Calling a JavaScript function named in a variable

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

eval(variable + '();');

Standard dry-code warning applies.

Error handling with PHPMailer

We wrote a wrapper class that captures the buffer and converts the printed output to an exception. this lets us upgrade the phpmailer file without having to remember to comment out the echo statements each time we upgrade.

The wrapper class has methods something along the lines of:

public function AddAddress($email, $name = null) {
    ob_start();
    parent::AddAddress($email, $name);
    $error = ob_get_contents();
    ob_end_clean();
    if( !empty($error) ) {
        throw new Exception($error);
    }
}

Check if a varchar is a number (TSQL)

I ran into the need to allow decimal values, so I used not Value like '%[^0-9.]%'

How can you run a Java program without main method?

Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

public class Hello {
  static {
    System.out.println("Hello, World!");
  }
}

Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.

As of JDK6 onward, you no longer see the message from the static initializer block; details here.

Plotting multiple curves same graph and same scale

You aren't being very clear about what you want here, since I think @DWin's is technically correct, given your example code. I think what you really want is this:

y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)

# first plot
plot(x, y1,ylim = range(c(y1,y2)))

# Add points
points(x, y2)

DWin's solution was operating under the implicit assumption (based on your example code) that you wanted to plot the second set of points overlayed on the original scale. That's why his image looks like the points are plotted at 1, 101, etc. Calling plot a second time isn't what you want, you want to add to the plot using points. So the above code on my machine produces this:

enter image description here

But DWin's main point about using ylim is correct.

Transaction isolation levels relation with locks on table

I want to understand the lock each transaction isolation takes on the table

For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT statement to read data. C reads and updates data. All these process work on the same table T.

  • READ UNCOMMITTED - no lock on the table. You can read data in the table while writing on it. This means A writes data (uncommitted) and B can read this uncommitted data and use it (for any purpose). If A executes a rollback, B still has read the data and used it. This is the fastest but most insecure way to work with data since can lead to data holes in not physically related tables (yes, two tables can be logically but not physically related in real-world apps =\).
  • READ COMMITTED - lock on committed data. You can read the data that was only committed. This means A writes data and B can't read the data saved by A until A executes a commit. The problem here is that C can update data that was read and used on B and B client won't have the updated data.
  • REPEATABLE READ - lock on a block of SQL(which is selected by using select query). This means B reads the data under some condition i.e. WHERE aField > 10 AND aField < 20, A inserts data where aField value is between 10 and 20, then B reads the data again and get a different result.
  • SERIALIZABLE - lock on a full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, especially the bosses).

I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also

Using JDBC, you define it using Connection#setTransactionIsolation.

Using Hibernate:

<property name="hibernate.connection.isolation">2</property>

Where

  • 1: READ UNCOMMITTED
  • 2: READ COMMITTED
  • 4: REPEATABLE READ
  • 8: SERIALIZABLE

Hibernate configuration is taken from here (sorry, it's in Spanish).

By the way, you can set the isolation level on RDBMS as well:

and on and on...

List all kafka topics

You have a stale version of the package with commands that no longer accept zookeeper but rather bootstrap-server as the connection. Confluent will then connect with Zookeeper internally.

https://www.confluent.io/download/ (5.3 or greater)

Spring cron expression for every after 30 minutes

If someone is using @Sceduled this might work for you.

@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")

This worked for me.

How to make a JSONP request from Javascript without JQuery?

function foo(data)
{
    // do stuff with JSON
}

var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'

document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers

Couldn't load memtrack module Logcat Error

do you called the ViewTreeObserver and not remove it.

    mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
         // do nothing here can cause such problem
    });

What is the difference between URI, URL and URN?

URI (Uniform Resource Identifier) according to Wikipedia:

a string of characters used to identify a resource.

URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.

URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax

IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.

Is there a constraint that restricts my generic method to numeric types?

Beginning with C# 7.3, you can use closer approximation - the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.

class SomeGeneric<T> where T : unmanaged
{
//...
}

The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.

A type is an unmanaged type if it's any of the following types:

  • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
  • Any enum type
  • Any pointer type
  • Any user-defined struct type that contains fields of unmanaged types only and, in C# 7.3 and earlier, is not a constructed type (a type that includes at least one type argument)

To restrict further and eliminate pointer and user-defined types that do not implement IComparable add IComparable (but enum is still derived from IComparable, so restrict enum by adding IEquatable < T >, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):

    class SomeGeneric<T> where T : unmanaged, IComparable, IEquatable<T>
    {
    //...
    }

But this doesn't prevent from DateTime instantiation.

find path of current folder - cmd

2015-03-30: Edited - Missing information has been added

To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory

set "curpath=%cd%"

This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with

for %%a in ("%cd%\") do set "curpath=%%~fa"

Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash.

Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory

for %%a in (".\") do set "curpath=%%~fa"

Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command).

BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.

set "curpath=%~dp0"

It will return the directory where the batch file is stored, with an ending backslash.

BUT this will fail if in the batch file the shift command has been used

shift
echo %~dp0

As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost.

To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine

@echo off
    setlocal enableextensions

    rem Destroy batch file reference
    shift
    echo batch folder is "%~dp0"

    rem Call the subroutine to get the batch folder 
    call :getBatchFolder batchFolder
    echo batch folder is "%batchFolder%"

    exit /b

:getBatchFolder returnVar
    set "%~1=%~dp0" & exit /b

This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).

What's the difference between equal?, eql?, ===, and ==?

I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.

Side note: if you want to try these out for yourself on different objects, use something like this:

class Object
  def all_equals(o)
    ops = [:==, :===, :eql?, :equal?]
    Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
  end
end

"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}

== — generic "equality"

At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.

=== — case equality

For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

This is incredibly useful. Examples of things which have interesting === implementations:

  • Range
  • Regex
  • Proc (in Ruby 1.9)

So you can do things like:

case some_object
when /a regex/
  # The regex matches
when 2..4
  # some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
  # the lambda returned true
end

See my answer here for a neat example of how case+Regex can make code a lot cleaner. And of course, by providing your own === implementation, you can get custom case semantics.

eql?Hash equality

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

So you're free to override this for your own uses, or you can override == and use alias :eql? :== so the two methods behave the same way.

equal? — identity comparison

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

This is effectively pointer comparison.

JSON: why are forward slashes escaped?

The JSON spec says you CAN escape forward slash, but you don't have to.

How to Execute a Python File in Notepad ++?

In case someone is interested in passing arguments to cmd.exe and running the python script in a Virtual Environment, these are the steps I used:

On the Notepad++ -> Run -> Run , I enter the following:

cmd /C cd $(CURRENT_DIRECTORY) && "PATH_to_.bat_file" $(FULL_CURRENT_PATH)

Here I cd into the directory in which the .py file exists, so that it enables accessing any other relevant files which are in the directory of the .py code.

And on the .bat file I have:

@ECHO off
set File_Path=%1

call activate Venv
python %File_Path%
pause

Permissions error when connecting to EC2 via SSH on Mac OSx

I had the same problem using the AWS Toolkit for Eclipse. I created the Getting Started instance OK and opened a shell. However, the user was set to ec2-user. I used the Open Shell As... command and set the user to root. Then it worked.

How do I calculate a trendline for a graph?

Regarding a previous answer

if (B) y = offset + slope*x

then (C) offset = y/(slope*x) is wrong

(C) should be:

offset = y-(slope*x)

See: http://zedgraph.org/wiki/index.php?title=Trend

Pass connection string to code-first DbContext

I have a little solution example for that problem.

MyDBContext.cs

 public MyDBContext(DBConnectionType ConnectionType) //: base("ConnMain")
  {
      if(ConnectionType==DBConnectionType.MainConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnMain"].ConnectionString;
       }
      else if(ConnectionType==DBConnectionType.BackupConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnBackup"].ConnectionString;
       }
  }

MyClass.cs

public enum DBConnectionType
 {
    MainConnection=0,
    BackupConnection=1
 }

frmMyForm.cs

 MyDBContext db = new MyDBContext(DBConnectionType.MainConnection);
                               //or
//MyDBContext db = new MyDBContext(DBConnectionType.BackupConnection);

Recursively look for files with a specific extension

To find all the pom.xml files in your current directory and print them, you can use:

find . -name 'pom.xml' -print

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

C# - How to get Program Files (x86) on Windows 64 bit

I am writing an application which can run on both x86 and x64 platform for Windows 7 and querying the below variable just pulls the right program files folder path on any platform.

Environment.GetEnvironmentVariable("PROGRAMFILES")

Is there an XSL "contains" directive?

From Zvon.org XSLT Reference:

XPath function: boolean contains (string, string) 

Hope this helps.

JAX-WS client : what's the correct path to access the local WSDL?

The best option is to use jax-ws-catalog.xml

When you compile the local WSDL file , override the WSDL location and set it to something like

http://localhost/wsdl/SOAService.wsdl

Don't worry this is only a URI and not a URL , meaning you don't have to have the WSDL available at that address.
You can do this by passing the wsdllocation option to the wsdl to java compiler.

Doing so will change your proxy code from

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "file:/C:/local/path/to/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'file:/C:/local/path/to/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

to

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "http://localhost/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'http://localhost/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

Notice file:// changed to http:// in the URL constructor.

Now comes in jax-ws-catalog.xml. Without jax-ws-catalog.xml jax-ws will indeed try to load the WSDL from the location

http://localhost/wsdl/SOAService.wsdl
and fail, as no such WSDL will be available.

But with jax-ws-catalog.xml you can redirect jax-ws to a locally packaged WSDL whenever it tries to access the WSDL @

http://localhost/wsdl/SOAService.wsdl
.

Here's jax-ws-catalog.xml

<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
        <system systemId="http://localhost/wsdl/SOAService.wsdl"
                uri="wsdl/SOAService.wsdl"/>
    </catalog>

What you are doing is telling jax-ws that when ever it needs to load WSDL from

http://localhost/wsdl/SOAService.wsdl
, it should load it from local path wsdl/SOAService.wsdl.

Now where should you put wsdl/SOAService.wsdl and jax-ws-catalog.xml ? That's the million dollar question isn't it ?
It should be in the META-INF directory of your application jar.

so something like this

ABCD.jar  
|__ META-INF    
    |__ jax-ws-catalog.xml  
    |__ wsdl  
        |__ SOAService.wsdl  

This way you don't even have to override the URL in your client that access the proxy. The WSDL is picked up from within your JAR, and you avoid having to have hard-coded filesystem paths in your code.

More info on jax-ws-catalog.xml http://jax-ws.java.net/nonav/2.1.2m1/docs/catalog-support.html

Hope that helps

how to open an URL in Swift3

import UIKit 
import SafariServices 

let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!) 
present(vc, animated: true, completion: nil)

Plot multiple boxplot in one graph

Using base graphics, we can use at = to control box position , combined with boxwex = for the width of the boxes. The 1st boxplot statement creates a blank plot. Then add the 2 traces in the following two statements.

Note that in the following, we use df[,-1] to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.

boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red", 
  boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue", 
  boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15

enter image description here

Some dummy data:

df <- data.frame(
  id = c(rep("Good",200), rep("Bad", 200)),
  F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
  F2 = c(rnorm(200,7,1),  rnorm(200,6,1)),
  F3 = c(rnorm(200,6,2),  rnorm(200,9,3)),
  F4 = c(rnorm(200,12,3), rnorm(200,8,2)))

ASP.NET custom error page - Server.GetLastError() is null

Try using something like Server.Transfer("~/ErrorPage.aspx"); from within the Application_Error() method of global.asax.cs

Then from within Page_Load() of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();

Server.Transfer() seems to keep the exception hanging around.

Trying to Validate URL Using JavaScript

I checked a lot of url validators in google and no one works for me. For example I'd like to see valid on links like 'aa.com'. I like silly check for dot sign in string.

function isValidUri(str) {
  var dotIndex = str.indexOf('.');
  return (dotIndex > 0 && dotIndex < str.length - 2);
}

It should not stay on beginning and end of string (for now we don't have top level domain names with one character).