Programs & Examples On #Word wrap

In text display, line wrap is the feature of continuing on a new line when a line is full, such that each line fits in the viewable window, allowing text to be read from top to bottom without any horizontal scrolling.

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

How to wrap text in LaTeX tables?

Use p{width} for your column specifiers instead of l/r/c.

\begin{tabular}{|p{1cm}|p{3cm}|}
  This text will be wrapped & Some more text \\
\end{tabular}

EDIT: (based on the comments)

\begin{table}[ht]
    \centering
    \begin{tabular}{p{0.35\linewidth} | p{0.6\linewidth}}
      Column 1  & Column2 \\ \hline
      This text will be wrapped & Some more text \\
      Some text here & This text maybe wrapped here if its tooooo long \\
    \end{tabular}
    \caption{Caption}
    \label{tab:my_label}
\end{table}

we get:

enter image description here

Wrapping text inside input type="text" element HTML/CSS

That is the textarea's job - for multiline text input. The input won't do it; it wasn't designed to do it.

So use a textarea. Besides their visual differences, they are accessed via JavaScript the same way (use value property).

You can prevent newlines being entered via the input event and simply using a replace(/\n/g, '').

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

There's a huge difference. break-all is basically unusable for rendering readable text.

Let's say you've got the string This is a text from an old magazine in a container which only fits 6 chars per row.

word-break: break-all

This i
s a te
xt fro
m an o
ld mag
azine

As you can see the result is awful. break-all will try to fit as many chararacters into each row as possible, it will even split a 2 letter word like "is" onto 2 rows! It's ridiculous. This is why break-all is rarely ever used.

word-wrap: break-word

This
is a
text
from
an old
magazi
ne

break-word will only break words which are too long to ever fit the container (like "magazine", which is 8 chars, and the container only fits 6 chars). It will never break words that could fit the container in their entirety, instead it will push them to a new line.

_x000D_
_x000D_
<div style="width: 100px; border: solid 1px black; font-family: monospace;">_x000D_
  <h1 style="word-break: break-all;">This is a text from an old magazine</h1>_x000D_
  <hr>_x000D_
  <h1 style="word-wrap: break-word;">This is a text from an old magazine</h1>_x000D_
</div
_x000D_
_x000D_
_x000D_

Stop floating divs from wrapping

The CSS property display: inline-block was designed to address this need. You can read a bit about it here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Below is an example of its use. The key elements are that the row element has white-space: nowrap and the cell elements have display: inline-block. This example should work on most major browsers; a compatibility table is available here: http://caniuse.com/#feat=inline-block

<html>
<body>
<style>

.row {
    float:left;
    border: 1px solid yellow;
    width: 100%;
    overflow: auto;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    width: 200px;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">a</div>
    <div class="cell">b</div>
    <div class="cell">c</div>
</div>


</body>
</html>

How to wrap text of HTML button with fixed width?

I have found that a button works, but that you'll want to add style="height: 100%;" to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

CSS to stop text wrapping under image

Wrap a div around the image and the span and add the following to CSS like so:

HTML

        <li id="CN2787">
          <div><img class="fav_star" src="images/fav.png"></div>
          <div><span>Text, text and more text</span></div>
        </li>

CSS

            #CN2787 > div { 
                display: inline-block;
                vertical-align: top;
            }

            #CN2787 > div:first-of-type {
                width: 35%;
            }

            #CN2787 > div:last-of-type {
                width: 65%;
            }

LESS

        #CN2787 {
            > div { 
                display: inline-block;
                vertical-align: top;
            }

            > div:first-of-type {
                width: 35%;
            }
            > div:last-of-type {
                width: 65%;
            }
        }

Wrap text in <td> tag

use word-break it can be used without styling table to table-layout: fixed

_x000D_
_x000D_
table {_x000D_
  width: 140px;_x000D_
  border: 1px solid #bbb_x000D_
}_x000D_
_x000D_
.tdbreak {_x000D_
  word-break: break-all_x000D_
}
_x000D_
<p>without word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>LOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>with word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="tdbreak">LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to turn off word wrapping in HTML?

white-space: nowrap;: Will never break text, will keep other defaults

white-space: pre;: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)

How to remove word wrap from textarea?

If you can use JavaScript, the following might be the most portable option today (tested Firefox 31, Chrome 36):

http://jsfiddle.net/cirosantilli/eaxgesoq/

<style>
  div#editor {
    white-space: pre;
    word-wrap: normal;
    overflow-x: scroll;
  }
<style>
<div contenteditable="true"></div>

There seems to be no standard, portable CSS solution:

Also, if you can use Javascript, you might as well use the ACE editor:

http://jsfiddle.net/cirosantilli/bL9vr8o8/

<script src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<div id="editor">content</div>
<script>
  var editor = ace.edit('editor')
  editor.renderer.setShowGutter(false)
</script>

Probably works with ACE because it does not use a textarea either which is underspecified / incoherently implemented, but not sure if it is uses contenteditable.

How to make a DIV not wrap?

you can use

display: table;

for your container and therfore avoid the overflow: hidden;. It should do the job if you used it just for warpping purpose.

How can I force a long string without any blank to be wrapped?

For me this works,

<td width="170px" style="word-wrap:break-word;">
  <div style="width:140px;overflow:auto">
    LONGTEXTGOESHERELONGDIVGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESLONGTEXTGOESHERELONGDIVLONGTEXTLONGTEXT
  </div>
</td>

You can also use a div inside another div instead of td. I used overflow:auto, as it shows all the text both in my Opera and IE browsers.

UILabel - Wordwrap text

Xcode 10, Swift 4

Wrapping the Text for a label can also be done on Storyboard by selecting the Label, and using Attributes Inspector.

Lines = 0 Linebreak = Word Wrap

enter image description here

How to wrap text in textview in Android

Strange enough - I created my TextView in Code and it wrapped - despite me not setting anything except standard stuff - but see for yourself:

LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
childParams.setMargins(5, 5, 5, 5);

Label label = new Label(this);
label.setText("This is a testing label This is a testing label This is a testing label This is a testing labelThis is a testing label This is a testing label");
label.setLayoutParams(childParams);

As you can see from the params definition I am using a LinearLayout. The class Label simply extends TextView - not doing anything there except setting the font size and the font color.

When running it in the emulator (API Level 9) it automatically wraps the text across 3 lines.

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

How can I wrap text in a label using WPF?

We need to put some kind of control that can wrap text like textblock/textbox

 <Label Width="120" Height="100" >
        <TextBlock TextWrapping="Wrap">
            this is a very long text inside a textblock and this needs to be on multiline.
        </TextBlock>
    </Label>

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

How do I wrap text in a span?

Wrapping can be done in various ways. I'll mention 2 of them:

1.) text wrapping - using white-space property http://www.w3schools.com/cssref/pr_text_white-space.asp

2.) word wrapping - using word-wrap property http://webdesignerwall.com/tutorials/word-wrap-force-text-to-wrap

By the way, in order to work using these 2 approaches, I believe you need to set the "display" property to block of the corresponding span element.

However, as Kirill already mentioned, it's a good idea to think about it for a moment. You're talking about forcing the text into a paragraph. PARAGRAPH. That should ring some bells in your head, shouldn't it? ;)

How can I toggle word wrap in Visual Studio?

In Visual Studio 2008 it is Ctrl + E + W.

Auto Scale TextView Text to Fit within Bounds

Warning, bug in Android Honeycomb and Ice Cream Sandwich

Androids versions: 3.1 - 4.04 have a bug, that setTextSize() inside of TextView works only for the 1st time (1st invocation).

Bug is described here: http://code.google.com/p/android/issues/detail?id=22493 http://code.google.com/p/android/issues/detail?id=17343#c9

workaround is to add new line character to text assigned to TextView before changing size:

final String DOUBLE_BYTE_SPACE = "\u3000";
textView.append(DOUBLE_BYTE_SPACE);

I use it in my code as follow:

final String DOUBLE_BYTE_SPACE = "\u3000";
AutoResizeTextView textView = (AutoResizeTextView) view.findViewById(R.id.aTextView);
String fixString = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
   && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {  
    fixString = DOUBLE_BYTE_SPACE;
}
textView.setText(fixString + "The text" + fixString);

I add this "\u3000" character on left and right of my text, to keep it centered. If you have it aligned to left then append to the right only. Of course it can be also embedded with AutoResizeTextView widget, but I wanted to keep fix code outside.

How to word wrap text in HTML?

You can use a soft hyphen like so:

aaaaaaaaaaaaaaa&shy;aaaaaaaaaaaaaaa

This will appear as

aaaaaaaaaaaaaaa-
aaaaaaaaaaaaaaa

if the containing box isn't big enough, or as

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

if it is.

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

Auto line-wrapping in SVG text

The textPath may be good for some case.

<svg width="200" height="200"
    xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <defs>
  <!-- define lines for text lies on -->
  <path id="path1" d="M10,30 H190 M10,60 H190 M10,90 H190 M10,120 H190"></path>
 </defs>
 <use xlink:href="#path1" x="0" y="35" stroke="blue" stroke-width="1" />
 <text transform="translate(0,35)" fill="red" font-size="20">
  <textPath xlink:href="#path1">This is a long long long text ......</textPath>
 </text>
</svg>

How to prevent line breaks in list items using CSS

You could add this little snippet of code to add a nice "…" to the ending of the line if the content is to large to fit on one line:

li {
  overflow: hidden; 
  text-overflow: ellipsis;
  white-space: nowrap;
}

Mapping object to dictionary and vice versa

Reflection can take you from an object to a dictionary by iterating over the properties.

To go the other way, you'll have to use a dynamic ExpandoObject (which, in fact, already inherits from IDictionary, and so has done this for you) in C#, unless you can infer the type from the collection of entries in the dictionary somehow.

So, if you're in .NET 4.0 land, use an ExpandoObject, otherwise you've got a lot of work to do...

Passing arrays as parameters in bash

Just to add to the accepted answer, as I found it doesn't work well if the array contents are someting like:

RUN_COMMANDS=(
  "command1 param1... paramN"
  "command2 param1... paramN"
)

In this case, each member of the array gets split, so the array the function sees is equivalent to:

RUN_COMMANDS=(
    "command1"
    "param1"
     ...
    "command2"
    ...
)

To get this case to work, the way I found is to pass the variable name to the function, then use eval:

function () {
    eval 'COMMANDS=( "${'"$1"'[@]}" )'
    for COMMAND in "${COMMANDS[@]}"; do
        echo $COMMAND
    done
}

function RUN_COMMANDS

Just my 2©

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

I made a method to solve this. My approach is:

1 - Create a abstract class that have a method to convert Objects to Array (including private attr) using Regex. 2 - Convert the returned array to json.

I use this Abstract class as parent of all my domain classes

Class code:

namespace Project\core;

abstract class AbstractEntity {
    public function getAvoidedFields() {
        return array ();
    }
    public function toArray() {
        $temp = ( array ) $this;

        $array = array ();

        foreach ( $temp as $k => $v ) {
            $k = preg_match ( '/^\x00(?:.*?)\x00(.+)/', $k, $matches ) ? $matches [1] : $k;
            if (in_array ( $k, $this->getAvoidedFields () )) {
                $array [$k] = "";
            } else {

                // if it is an object recursive call
                if (is_object ( $v ) && $v instanceof AbstractEntity) {
                    $array [$k] = $v->toArray();
                }
                // if its an array pass por each item
                if (is_array ( $v )) {

                    foreach ( $v as $key => $value ) {
                        if (is_object ( $value ) && $value instanceof AbstractEntity) {
                            $arrayReturn [$key] = $value->toArray();
                        } else {
                            $arrayReturn [$key] = $value;
                        }
                    }
                    $array [$k] = $arrayReturn;
                }
                // if it is not a array and a object return it
                if (! is_object ( $v ) && !is_array ( $v )) {
                    $array [$k] = $v;
                }
            }
        }

        return $array;
    }
}

How to include JavaScript file or library in Chrome console?

Install tampermonkey and add the following UserScript with one (or more) @match with specific page url (or a match of all pages: https://*) e.g.:

// ==UserScript==
// @name         inject-rx
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Inject rx library on the page
// @author       Me
// @match        https://www.some-website.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
     window.injectedRx = rxjs;
     //Or even:  window.rxjs = rxjs;

})();

Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.

This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end 

How to use Bootstrap in an Angular project?

The most popular option is to use some third party library distributed as npm package like ng2-bootstrap project https://github.com/valor-software/ng2-bootstrap or Angular UI Bootstrap library.

I personally use ng2-bootstrap. There are many ways to configure it, because configuration depends on how your Angular project is build. Underneath I post example configuration based on Angular 2 QuickStart project https://github.com/angular/quickstart

Firstly we add dependencies in our package.json

    { ...
"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",

    ...

    "bootstrap": "^3.3.7",
    "ng2-bootstrap": "1.1.16-11"
  },
... }

Then we have to map names to proper URL's in systemjs.config.js

(function (global) {
  System.config({
    ...
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      //bootstrap
      'moment': 'npm:moment/bundles/moment.umd.js',
      'ng2-bootstrap': 'npm:ng2-bootstrap/bundles/ng2-bootstrap.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
...
  });
})(this);

We have to import bootstrap .css file in index.html. We can get it from /node_modules/bootstrap directory on our hard drive (because we added bootstrap 3.3.7 dependency) or from web. There we are obtaining it from web:

<!DOCTYPE html>
<html>
  <head>
    ...
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    ...
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

We should edit our app.module.ts file from /app directory

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

//bootstrap alert import part 1
import {AlertModule} from 'ng2-bootstrap';

import { AppComponent }  from './app.component';


@NgModule({
  //bootstrap alert import part 2
  imports:      [ BrowserModule, AlertModule.forRoot() ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

And finally our app.component.ts file from /app directory

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `
    <alert type="success">
        Well done!
    </alert>
    `
})

export class AppComponent {

    constructor() { }

}

Then we have to install our bootstrap and ng2-bootstrap dependencies before we run our app. We should go to our project directory and type

npm install

Finally we can start our app

npm start

There are many code samples on ng2-bootstrap project github showing how to import ng2-bootstrap to various Angular 2 project builds. There is even plnkr sample. There is also API documentation on Valor-software (authors of the library) website.

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

Inner text shadow with CSS

Try this little gem of a variation:

text-shadow:0 1px 1px rgba(255, 255, 255, 0.5);

I usually take "there's no answer" as a challenge

destination path already exists and is not an empty directory

This error comes up when you try to clone a repository in a folder which still contains .git folder (Hidden folder).

If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.

Open terminal & change the directory to the destination folder (where you want to clone).

Now type: ls -a

You may see a folder named .git.

You have to remove that folder by the following command: rm -rf .git

Now you are ready to clone your project.

How to check Django version

go the setting of the Django Project. there find your Django Version.

How to set caret(cursor) position in contenteditable element (div)?

If you don't want to use jQuery you can try this approach:

public setCaretPosition() {
    const editableDiv = document.getElementById('contenteditablediv');
    const lastLine = this.input.nativeElement.innerHTML.replace(/.*?(<br>)/g, '');
    const selection = window.getSelection();
    selection.collapse(editableDiv.childNodes[editableDiv.childNodes.length - 1], lastLine.length);
}

editableDiv you editable element, don't forget to set an id for it. Then you need to get your innerHTML from the element and cut all brake lines. And just set collapse with next arguments.

How can I use nohup to run process as a background process in linux?

  • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

  • Make a script that takes your "1" as a parameter, run nohup yourscript:

    #!/bin/bash
    (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
    

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

For my project, I had to delete these two lines from .csproj file

<ProjectGuid>{3AA499DF-4A65-43B7-8965-D08A4C811834}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

I tried deleting only the first one, but it wasn't enough.

EDIT: As many users have pointed out, this can change your project type or mess with your source control program. I can't investigate these issues as it was a school project I do not have anymore. Please be careful when trying this. At least make a copy of what you delete.

Compiling LaTex bib source

You have to run 'bibtex':

latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi

How to get config parameters in Symfony2 Twig Templates

With a Twig extension, you can create a parameterTwig function:

{{ parameter('jira_host') }}

TwigExtension.php:

class TwigExtension extends \Twig_Extension
{
    public $container;

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('parameter', function($name)
            {
                return $this->container->getParameter($name);
            })
        ];
    }


    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'iz';
    }
}

service.yml:

  iz.twig.extension:
    class: IzBundle\Services\TwigExtension
    properties:
      container: "@service_container"
    tags:
      - { name: twig.extension }

What is the use of join() in Python threading?

Straight from the docs

join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

This means that the main thread which spawns t and d, waits for t to finish until it finishes.

Depending on the logic your program employs, you may want to wait until a thread finishes before your main thread continues.

Also from the docs:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

A simple example, say we have this:

def non_daemon():
    time.sleep(5)
    print 'Test non-daemon'

t = threading.Thread(name='non-daemon', target=non_daemon)

t.start()

Which finishes with:

print 'Test one'
t.join()
print 'Test two'

This will output:

Test one
Test non-daemon
Test two

Here the master thread explicitly waits for the t thread to finish until it calls print the second time.

Alternatively if we had this:

print 'Test one'
print 'Test two'
t.join()

We'll get this output:

Test one
Test two
Test non-daemon

Here we do our job in the main thread and then we wait for the t thread to finish. In this case we might even remove the explicit joining t.join() and the program will implicitly wait for t to finish.

Re-ordering columns in pandas dataframe based on column name

You can just do:

df[sorted(df.columns)]

Edit: Shorter is

df[sorted(df)]

Create Hyperlink in Slack

I know you wanted only a hypertext link, but if you copy & paste a link address into Slack that does work very nicely. i.e. if referring to VersionOne ticket number (V1 mouseover the ticket window to open the mouseover window, then right click on the ticket number for the option to "copy link address", then in Slack paste. It'll paste the full ticket URL but then it shows a nice summary of the ticket number and name and you can click it to go right into the ticket.)

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to add a column in TSQL after a specific column?

Unfortunately you can't.

If you really want them in that order you'll have to create a new table with the columns in that order and copy data. Or rename columns etc. There is no easy way.

"Correct" way to specifiy optional arguments in R functions

Just wanted to point out that the built-in sink function has good examples of different ways to set arguments in a function:

> sink
function (file = NULL, append = FALSE, type = c("output", "message"),
    split = FALSE)
{
    type <- match.arg(type)
    if (type == "message") {
        if (is.null(file))
            file <- stderr()
        else if (!inherits(file, "connection") || !isOpen(file))
            stop("'file' must be NULL or an already open connection")
        if (split)
            stop("cannot split the message connection")
        .Internal(sink(file, FALSE, TRUE, FALSE))
    }
    else {
        closeOnExit <- FALSE
        if (is.null(file))
            file <- -1L
        else if (is.character(file)) {
            file <- file(file, ifelse(append, "a", "w"))
            closeOnExit <- TRUE
        }
        else if (!inherits(file, "connection"))
            stop("'file' must be NULL, a connection or a character string")
        .Internal(sink(file, closeOnExit, FALSE, split))
    }
}

What strategies and tools are useful for finding memory leaks in .NET?

We've used Ants Profiler Pro by Red Gate software in our project. It works really well for all .NET language-based applications.

We found that the .NET Garbage Collector is very "safe" in its cleaning up of in-memory objects (as it should be). It would keep objects around just because we might be using it sometime in the future. This meant we needed to be more careful about the number of objects that we inflated in memory. In the end, we converted all of our data objects over to an "inflate on-demand" (just before a field is requested) in order to reduce memory overhead and increase performance.

EDIT: Here's a further explanation of what I mean by "inflate on demand." In our object model of our database we use Properties of a parent object to expose the child object(s). For example if we had some record that referenced some other "detail" or "lookup" record on a one-to-one basis we would structure it like this:

class ParentObject
   Private mRelatedObject as New CRelatedObject
   public Readonly property RelatedObject() as CRelatedObject
      get
         mRelatedObject.getWithID(RelatedObjectID)
         return mRelatedObject
      end get
   end property
End class

We found that the above system created some real memory and performance problems when there were a lot of records in memory. So we switched over to a system where objects were inflated only when they were requested, and database calls were done only when necessary:

class ParentObject
   Private mRelatedObject as CRelatedObject
   Public ReadOnly Property RelatedObject() as CRelatedObject
      Get
         If mRelatedObject is Nothing
            mRelatedObject = New CRelatedObject
         End If
         If mRelatedObject.isEmptyObject
            mRelatedObject.getWithID(RelatedObjectID)
         End If
         return mRelatedObject
      end get
   end Property
end class

This turned out to be much more efficient because objects were kept out of memory until they were needed (the Get method was accessed). It provided a very large performance boost in limiting database hits and a huge gain on memory space.

JQuery .each() backwards

I think u need

.parentsUntill()

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Using different syntax (flags ...), can cause this problem from version to another in webpack (3,4,5...), you have to read new webpack configuration updated and deprecated features.

How do you check if a JavaScript Object is a DOM Object?

Not to hammer on this or anything but for ES5-compliant browsers why not just:

function isDOM(e) {
  return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
}

Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.

Implementing multiple interfaces with Java - is there a way to delegate?

There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.

MySQL Update Inner Join tables query

For MySql WorkBench, Please use below :

update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12); 

Detect HTTP or HTTPS then force HTTPS in JavaScript

You can do:

  <script type="text/javascript">        
        if (window.location.protocol != "https:") {
           window.location.protocol = "https";
        }
    </script>

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();
?>

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

Python - Extracting and Saving Video Frames

This code extract frames from the video and save the frames in .jpg formate

import cv2
import numpy as np
import os

# set video file path of input video with name and extension
vid = cv2.VideoCapture('VideoPath')


if not os.path.exists('images'):
    os.makedirs('images')

#for frame identity
index = 0
while(True):
    # Extract images
    ret, frame = vid.read()
    # end of frames
    if not ret: 
        break
    # Saves images
    name = './images/frame' + str(index) + '.jpg'
    print ('Creating...' + name)
    cv2.imwrite(name, frame)

    # next frame
    index += 1

CSS: Truncate table cells, but fit as much as possible

you can set the width of right cell to minimum of required width, then apply overflow-hidden+text-overflow to the inside of left cell, but Firefox is buggy here...

although, seems, flexbox can help

Javascript .querySelector find <div> by innerTEXT

Since there are no limits to the length of text in a data attribute, use data attributes! And then you can use regular css selectors to select your element(s) like the OP wants.

_x000D_
_x000D_
for (const element of document.querySelectorAll("*")) {_x000D_
  element.dataset.myInnerText = element.innerText;_x000D_
}_x000D_
_x000D_
document.querySelector("*[data-my-inner-text='Different text.']").style.color="blue";
_x000D_
<div>SomeText, text continues.</div>_x000D_
<div>Different text.</div>
_x000D_
_x000D_
_x000D_

Ideally you do the data attribute setting part on document load and narrow down the querySelectorAll selector a bit for performance.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

Answers above describe well why and how it is used on twitter and facebook, what I missed is explanation what # does by default...

On a 'normal' (not a single page application) you can do anchoring with hash to any element that has id by placing that elements id in url after hash #

Example:

(on Chrome) Click F12 or Rihgt Mouse and Inspect element

enter image description here

then take id="answer-10831233" and add to url like following

https://stackoverflow.com/questions/3009380/whats-the-shebang-hashbang-in-facebook-and-new-twitter-urls-for#answer-10831233

and you will get a link that jumps to that element on the page

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

By using # in a way described in the answers above you are introducing conflicting behaviour... although I wouldn't loose sleep over it... since Angular it became somewhat of a standard....

How to create multiple page app using react

The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:

    entry: {
            outputone: './source/fileone.jsx',
            outputtwo: './source/filetwo.jsx'
            },
    output: {
            path: path.resolve(__dirname, './wwwroot/js/dist'),
            filename: '[name].js'      
            },

This will generate 2 files: outputone.js und outputtwo.js in the target folder.

Excel VBA Check if directory exists error

To check for the existence of a directory using Dir, you need to specify vbDirectory as the second argument, as in something like:

If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then

Note that, with vbDirectory, Dir will return a non-empty string if the specified path already exists as a directory or as a file (provided the file doesn't have any of the read-only, hidden, or system attributes). You could use GetAttr to be certain it's a directory and not a file.

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

How do I select the parent form based on which submit button is clicked?

i used the following method & it worked fine for me

$('#mybutton').click(function(){
        clearForm($('#mybutton').closest("form"));
    });

$('#mybutton').closest("form") did the trick for me.

Markdown and image alignment

You can embed HTML in Markdown, so you can do something like this:

<img style="float: right;" src="whatever.jpg">

Continue markdown text...

How can I get the assembly file version

See my comment above asking for clarification on what you really want. Hopefully this is it:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;

How do I use CSS with a ruby on rails application?

Put the CSS files in public/stylesheets and then use:

<%= stylesheet_link_tag "filename" %>

to link to the stylesheet in your layouts or erb files in your views.

Similarly you put images in public/images and javascript files in public/javascripts.

How to get resources directory path programmatically

import org.springframework.core.io.ClassPathResource;

...

File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

How to write inside a DIV box with javascript

If you are using jQuery and you want to add content to the existing contents of the div, you can use .html() within the brackets:

_x000D_
_x000D_
$("#log").html($('#log').html() + " <br>New content!");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="log">Initial Content</div>
_x000D_
_x000D_
_x000D_

Import existing Gradle Git project into Eclipse

The simpliest way is to use sts gradle integration and import project

http://static.springsource.org/sts/docs/2.7.0.M1/reference/html/gradle/gradle-sts-tutorial.html

Don't forget to click "Build Model" button.

PostgreSQL next value of the sequences?

RETURNING

Since PostgreSQL 8.2, that's possible with a single round-trip to the database:

INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;

tbl_id would typically be a serial or IDENTITY (Postgres 10 or later) column. More in the manual.

Explicitly fetch value

If filename needs to include tbl_id (redundantly), you can still use a single query.

Use lastval() or the more specific currval():

INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq')   -- or lastval()
RETURNING tbl_id;

See:

If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq').

Name of sequence

The string literal 'tbl_tbl_id_seq' in my example is supposed to be the actual name of the sequence and is cast to regclass, which raises an exception if no sequence of that name can be found in the current search_path.

tbl_tbl_id_seq is the automatically generated default for a table tbl with a serial column tbl_id. But there are no guarantees. A column default can fetch values from any sequence if so defined. And if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.

If you don't know the name of the sequence for a serial column, use the dedicated function pg_get_serial_sequence(). Can be done on the fly:

INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;

db<>fiddle here
Old sqlfiddle

String concatenation in Jinja

Just another hack can be like this.

I have Array of strings which I need to concatenate. So I added that array into dictionary and then used it inside for loop which worked.

{% set dict1 = {'e':''} %}
{% for i in list1 %}
{% if dict1.update({'e':dict1.e+":"+i+"/"+i}) %} {% endif %}
{% endfor %}
{% set layer_string = dict1['e'] %}

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Go Back to Previous Page

Depends what it is that you're trying to do it with. You could use something like this:

echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";

That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.

Just edited, orig version wasn't indented and looked like nothing. ;)

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

SDK Manager.exe doesn't work

I fixed this issue by reinstalling it in Program Files, it originally tried to install it in c:/Users/.../AppData/Android/....

Mine was caused by a user permission issue that running as admin didn't seem to fix (perhaps because they call batch files?).

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Using a SELECT statement within a WHERE clause

In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link

Create an array of integers property in Objective-C

C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:

Supported Types

You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”

POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

If you need an array, you should use NSArray or NSData.

The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

I'm hoping someone can provide some concrete examples of best use cases for each.

Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.

Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, an unsupported, "throw the code over the wall and do an I|O presentation on it" library.

EDIT - Volley is now officially supported by Google. Kindly refer Google Developer Guide

From what I've read, seems like OkHTTP is the most robust of the 3

Retrofit uses OkHTTP automatically if available. There is a Gist from Jake Wharton that connects Volley to OkHTTP.

and could handle the requirements of this project (mentioned above).

Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". Instead, Android's media framework will handle those HTTP requests for you.

That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

How to create a file in Android?

From here: http://www.anddev.org/working_with_files-t115.html

//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

java.lang.OutOfMemoryError: Java heap space

No, I think you are thinking of stack space. Heap space is occupied by objects. The way to increase it is -Xmx256m, replacing the 256 with the amount you need on the command line.

How to export html table to excel using javascript

I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.

The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).

It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files\PostgreSQL\8.4\data\postgresql.conf

How do I get the current date and time in PHP?

For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.

1. date method (PHP 4, PHP 5, PHP 7)

This is the very common and very easiest way to get the date and time in php.

// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

You can learn more about it in here

2. DateTime class (PHP 5 >= 5.2.0, PHP 7)

when you want to use PHP with OOP, this is the best way to get date and time.

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

You can learn more about it in here

3. Carbon Date time package

if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class. This in-built in frameworks like laravel so you don't have to install it separately.

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'

You can learn more about it in here

Hope this helps and if you know any other way to get the date and time feel free to edit the answer.

Validate SSL certificates with Python

Here's an example script which demonstrates certificate validation:

import httplib
import re
import socket
import sys
import urllib2
import ssl

class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
    def __init__(self, host, cert, reason):
        httplib.HTTPException.__init__(self)
        self.host = host
        self.cert = cert
        self.reason = reason

    def __str__(self):
        return ('Host %s returned an invalid certificate (%s) %s\n' %
                (self.host, self.reason, self.cert))

class CertValidatingHTTPSConnection(httplib.HTTPConnection):
    default_port = httplib.HTTPS_PORT

    def __init__(self, host, port=None, key_file=None, cert_file=None,
                             ca_certs=None, strict=None, **kwargs):
        httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
        self.key_file = key_file
        self.cert_file = cert_file
        self.ca_certs = ca_certs
        if self.ca_certs:
            self.cert_reqs = ssl.CERT_REQUIRED
        else:
            self.cert_reqs = ssl.CERT_NONE

    def _GetValidHostsForCert(self, cert):
        if 'subjectAltName' in cert:
            return [x[1] for x in cert['subjectAltName']
                         if x[0].lower() == 'dns']
        else:
            return [x[0][1] for x in cert['subject']
                            if x[0][0].lower() == 'commonname']

    def _ValidateCertificateHostname(self, cert, hostname):
        hosts = self._GetValidHostsForCert(cert)
        for host in hosts:
            host_re = host.replace('.', '\.').replace('*', '[^.]*')
            if re.search('^%s$' % (host_re,), hostname, re.I):
                return True
        return False

    def connect(self):
        sock = socket.create_connection((self.host, self.port))
        self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                          certfile=self.cert_file,
                                          cert_reqs=self.cert_reqs,
                                          ca_certs=self.ca_certs)
        if self.cert_reqs & ssl.CERT_REQUIRED:
            cert = self.sock.getpeercert()
            hostname = self.host.split(':', 0)[0]
            if not self._ValidateCertificateHostname(cert, hostname):
                raise InvalidCertificateException(hostname, cert,
                                                  'hostname mismatch')


class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
    def __init__(self, **kwargs):
        urllib2.AbstractHTTPHandler.__init__(self)
        self._connection_args = kwargs

    def https_open(self, req):
        def http_class_wrapper(host, **kwargs):
            full_kwargs = dict(self._connection_args)
            full_kwargs.update(kwargs)
            return CertValidatingHTTPSConnection(host, **full_kwargs)

        try:
            return self.do_open(http_class_wrapper, req)
        except urllib2.URLError, e:
            if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
                raise InvalidCertificateException(req.host, '',
                                                  e.reason.args[1])
            raise

    https_request = urllib2.HTTPSHandler.do_request_

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "usage: python %s CA_CERT URL" % sys.argv[0]
        exit(2)

    handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
    opener = urllib2.build_opener(handler)
    print opener.open(sys.argv[2]).read()

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

imageView_ProfileImage.layer.cornerRadius =10.0f;
imageView_ProfileImage.layer.borderColor = [[UIColor blackColor] CGColor];
imageView_ProfileImage.layer.borderWidth =.4f;
imageView_ProfileImage.layer.masksToBounds = YES;

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

How to append text to an existing file in Java?

If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

There are few points to note:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

How to align texts inside of an input?

Without CSS: Use the STYLE property of text input

STYLE="text-align: right;"

How to get the caller's method name in the called method?

Bit of an amalgamation of the stuff above. But here's my crack at it.

def print_caller_name(stack_size=3):
    def wrapper(fn):
        def inner(*args, **kwargs):
            import inspect
            stack = inspect.stack()

            modules = [(index, inspect.getmodule(stack[index][0]))
                       for index in reversed(range(1, stack_size))]
            module_name_lengths = [len(module.__name__)
                                   for _, module in modules]

            s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
            callers = ['',
                       s.format(index='level', module='module', name='name'),
                       '-' * 50]

            for index, module in modules:
                callers.append(s.format(index=index,
                                        module=module.__name__,
                                        name=stack[index][3]))

            callers.append(s.format(index=0,
                                    module=fn.__module__,
                                    name=fn.__name__))
            callers.append('')
            print('\n'.join(callers))

            fn(*args, **kwargs)
        return inner
    return wrapper

Use:

@print_caller_name(4)
def foo():
    return 'foobar'

def bar():
    return foo()

def baz():
    return bar()

def fizz():
    return baz()

fizz()

output is

level :             module             : name
--------------------------------------------------
    3 :              None              : fizz
    2 :              None              : baz
    1 :              None              : bar
    0 :            __main__            : foo

What is the Swift equivalent of isEqualToString in Objective-C?

In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

In Python How can I declare a Dynamic Array

you can declare a Numpy array dynamically for 1 dimension as shown below:

import numpy as np

n = 2
new_table = np.empty(shape=[n,1])

new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)

The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)

output is shown below:

[[2.] [3.]]

How do I create an array of strings in C?

Ack! Constant strings:

const char *strings[] = {"one","two","three"};

If I remember correctly.

Oh, and you want to use strcpy for assignment, not the = operator. strcpy_s is safer, but it's neither in C89 nor in C99 standards.

char arr[MAX_NUMBER_STRINGS][MAX_STRING_SIZE]; 
strcpy(arr[0], "blah");

Update: Thomas says strlcpy is the way to go.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.

The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.

RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."

How do I register a .NET DLL file in the GAC?

These responses don't tell you that gacutil resides in C:\WINDOWS\Microsoft.NET\Framework\v1.1* by the way.

I didn't have it in my v2.0 folder. But I tried dragging & dropping the DLL into the C:\WINDOWS\Assembly folder as was suggested here earlier and that was easier and does work, as long as it's a .NET library. I also tried a COM library and this failed with an error that it was expecting an assembly manifest. I know that wasn't the question here, but thought I'd mention that in case someone finds out they can't add it, that that might be why.

-Tom

What are the benefits of using C# vs F# or F# vs C#?

General benefits of functional programming over imperative languages:

You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) You will find many discussions like this when you google it or even search for it at SO.

Special F#-advantages:

  • Asynchronous programming is extremely easy and intuitive with async {}-expressions - Even with ParallelFX, the corresponding C#-code is much bigger

  • Very easy integration of compiler compilers and domain-specific languages

  • Extending the language as you need it: LOP

  • Units of measure

  • More flexible syntax

  • Often shorter and more elegant solutions

Take a look at this document

The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread.

Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

What is sr-only in Bootstrap 3?

According to bootstrap's documentation, the class is used to hide information intended only for screen readers from the layout of the rendered page.

Screen readers will have trouble with your forms if you don't include a label for every input. For these inline forms, you can hide the labels using the .sr-only class.

Here is an example styling used:

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  border: 0;
}

Is it important or can I remove it? Works fine without.

It's important, don't remove it.

You should always consider screen readers for accessibility purposes. Usage of the class will hide the element anyways, therefore you shouldn't see a visual difference.

If you're interested in reading about accessibility:

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

Error ITMS-90717: "Invalid App Store Icon"

changed the icon from .png format to .jpg and everything went well.

How to set seekbar min and max value

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

How do I clone a specific Git branch?

git clone -b <branch> <remote_repo>

Example:

git clone -b my-branch [email protected]:user/myproject.git

With Git 1.7.10 and later, add --single-branch to prevent fetching of all branches. Example, with OpenCV 2.4 branch:

git clone -b opencv-2.4 --single-branch https://github.com/Itseez/opencv.git

Mockito: InvalidUseOfMatchersException

I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.

It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq

when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
            .thenReturn(recommendedResults);

In this example 'metas' is an existing list of values

VB.Net Properties - Public Get, Private Set

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

used ast, example

In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...:      {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...:      {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
 {'end_city': 'bbb', 'number': 1, 'start_city': '2'},
 {'end_city': 'ccc', 'number': 1, 'start_city': '3'}]

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

nodejs module.js:340 error: cannot find module

I executed following command and it works for me.

PM> npm install ee-first [email protected] node_modules\ee-first

Using JavaMail with TLS

The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):

java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");

How can I get a side-by-side diff when I do "git diff"?

Here's an approach. If you pipe through less, the xterm width is set to 80, which ain't so hot. But if you proceed the command with, e.g. COLS=210, you can utilize your expanded xterm.

gitdiff()
{
    local width=${COLS:-$(tput cols)}
    GIT_EXTERNAL_DIFF="diff -yW$width \$2 \$5; echo >/dev/null" git diff "$@"
}

C++11 rvalues and move semantics confusion (return statement)

The simple answer is you should write code for rvalue references like you would regular references code, and you should treat them the same mentally 99% of the time. This includes all the old rules about returning references (i.e. never return a reference to a local variable).

Unless you are writing a template container class that needs to take advantage of std::forward and be able to write a generic function that takes either lvalue or rvalue references, this is more or less true.

One of the big advantages to the move constructor and move assignment is that if you define them, the compiler can use them in cases were the RVO (return value optimization) and NRVO (named return value optimization) fail to be invoked. This is pretty huge for returning expensive objects like containers & strings by value efficiently from methods.

Now where things get interesting with rvalue references, is that you can also use them as arguments to normal functions. This allows you to write containers that have overloads for both const reference (const foo& other) and rvalue reference (foo&& other). Even if the argument is too unwieldy to pass with a mere constructor call it can still be done:

std::vector vec;
for(int x=0; x<10; ++x)
{
    // automatically uses rvalue reference constructor if available
    // because MyCheapType is an unamed temporary variable
    vec.push_back(MyCheapType(0.f));
}


std::vector vec;
for(int x=0; x<10; ++x)
{
    MyExpensiveType temp(1.0, 3.0);
    temp.initSomeOtherFields(malloc(5000));

    // old way, passed via const reference, expensive copy
    vec.push_back(temp);

    // new way, passed via rvalue reference, cheap move
    // just don't use temp again,  not difficult in a loop like this though . . .
    vec.push_back(std::move(temp));
}

The STL containers have been updated to have move overloads for nearly anything (hash key and values, vector insertion, etc), and is where you will see them the most.

You can also use them to normal functions, and if you only provide an rvalue reference argument you can force the caller to create the object and let the function do the move. This is more of an example than a really good use, but in my rendering library, I have assigned a string to all the loaded resources, so that it is easier to see what each object represents in the debugger. The interface is something like this:

TextureHandle CreateTexture(int width, int height, ETextureFormat fmt, string&& friendlyName)
{
    std::unique_ptr<TextureObject> tex = D3DCreateTexture(width, height, fmt);
    tex->friendlyName = std::move(friendlyName);
    return tex;
}

It is a form of a 'leaky abstraction' but allows me to take advantage of the fact I had to create the string already most of the time, and avoid making yet another copying of it. This isn't exactly high-performance code but is a good example of the possibilities as people get the hang of this feature. This code actually requires that the variable either be a temporary to the call, or std::move invoked:

// move from temporary
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string("Checkerboard"));

or

// explicit move (not going to use the variable 'str' after the create call)
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, std::move(str));

or

// explicitly make a copy and pass the temporary of the copy down
// since we need to use str again for some reason
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string(str));

but this won't compile!

string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, str);

Truncate a SQLite table if it exists?

"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...

example :

private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";


public void reset_table(String table_name){
    open_db();

    mydb.execSQL("Delete from "+table_name);
    mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");

    close_db();
}

public void open_db(){

    mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){

    mydb.close();
}

Configure DataSource programmatically in Spring Boot

My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:

spring:
  # (DataSourceAutoConfiguration & DataSourceProperties)
  datasource:
    name: ds-h2
    url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
    username: h2
    password: h2
    driver-class: org.h2.Driver

Custom DataSource

@Configuration
@Component
public class DataSourceBean {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    @Primary
    public DataSource getDataSource() {
        return DataSourceBuilder
                .create()
//                .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
//                .username("h2")
//                .password("h2")
//                .driverClassName("org.h2.Driver")
                .build();
    }
}

AssertContains on strings in jUnit

You can use assertj-fluent assertions. It has lot of capabilities to write assertions in more human readable - user friendly manner.

In your case, it would be

 String x = "foo bar";
 assertThat(x).contains("foo");

It is not only for the strings, it can be used to assert lists, collections etc.. in a friendlier way

javascript date + 7 days

Using the Date object's methods will could come in handy.

e.g.:

myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));

Dynamic constant assignment

Because constants in Ruby aren't meant to be changed, Ruby discourages you from assigning to them in parts of code which might get executed more than once, such as inside methods.

Under normal circumstances, you should define the constant inside the class itself:

class MyClass
  MY_CONSTANT = "foo"
end

MyClass::MY_CONSTANT #=> "foo"

If for some reason though you really do need to define a constant inside a method (perhaps for some type of metaprogramming), you can use const_set:

class MyClass
  def my_method
    self.class.const_set(:MY_CONSTANT, "foo")
  end
end

MyClass::MY_CONSTANT
#=> NameError: uninitialized constant MyClass::MY_CONSTANT

MyClass.new.my_method
MyClass::MY_CONSTANT #=> "foo"

Again though, const_set isn't something you should really have to resort to under normal circumstances. If you're not sure whether you really want to be assigning to constants this way, you may want to consider one of the following alternatives:

Class variables

Class variables behave like constants in many ways. They are properties on a class, and they are accessible in subclasses of the class they are defined on.

The difference is that class variables are meant to be modifiable, and can therefore be assigned to inside methods with no issue.

class MyClass
  def self.my_class_variable
    @@my_class_variable
  end
  def my_method
    @@my_class_variable = "foo"
  end
end
class SubClass < MyClass
end

MyClass.my_class_variable
#=> NameError: uninitialized class variable @@my_class_variable in MyClass
SubClass.my_class_variable
#=> NameError: uninitialized class variable @@my_class_variable in MyClass

MyClass.new.my_method
MyClass.my_class_variable #=> "foo"
SubClass.my_class_variable #=> "foo"

Class attributes

Class attributes are a sort of "instance variable on a class". They behave a bit like class variables, except that their values are not shared with subclasses.

class MyClass
  class << self
    attr_accessor :my_class_attribute
  end
  def my_method
    self.class.my_class_attribute = "blah"
  end
end
class SubClass < MyClass
end

MyClass.my_class_attribute #=> nil
SubClass.my_class_attribute #=> nil

MyClass.new.my_method
MyClass.my_class_attribute #=> "blah"
SubClass.my_class_attribute #=> nil

SubClass.new.my_method
SubClass.my_class_attribute #=> "blah"

Instance variables

And just for completeness I should probably mention: if you need to assign a value which can only be determined after your class has been instantiated, there's a good chance you might actually be looking for a plain old instance variable.

class MyClass
  attr_accessor :instance_variable
  def my_method
    @instance_variable = "blah"
  end
end

my_object = MyClass.new
my_object.instance_variable #=> nil
my_object.my_method
my_object.instance_variable #=> "blah"

MyClass.new.instance_variable #=> nil

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

How do I split a multi-line string into multiple lines?

Use str.splitlines().

splitlines() handles newlines properly, unlike split("\n").

It also has the the advantage mentioned by @efotinis of optionally including the newline character in the split result when called with a True argument.


Why you shouldn't use split("\n"):

\n, in Python, represents a Unix line-break (ASCII decimal code 10), independently from the platform where you run it. However, the linebreak representation is platform-dependent. On Windows, \n is two characters, CR and LF (ASCII decimal codes 13 and 10, AKA \r and \n), while on any modern Unix (including OS X), it's the single character LF.

print, for example, works correctly even if you have a string with line endings that don't match your platform:

>>> print " a \n b \r\n c "
 a 
 b 
 c

However, explicitly splitting on "\n", will yield platform-dependent behaviour:

>>> " a \n b \r\n c ".split("\n")
[' a ', ' b \r', ' c ']

Even if you use os.linesep, it will only split according to the newline separator on your platform, and will fail if you're processing text created in other platforms, or with a bare \n:

>>> " a \n b \r\n c ".split(os.linesep)
[' a \n b ', ' c ']

splitlines solves all these problems:

>>> " a \n b \r\n c ".splitlines()
[' a ', ' b ', ' c ']

Reading files in text mode partially mitigates the newline representation problem, as it converts Python's \n into the platform's newline representation. However, text mode only exists on Windows. On Unix systems, all files are opened in binary mode, so using split('\n') in a UNIX system with a Windows file will lead to undesired behavior. Also, it's not unusual to process strings with potentially different newlines from other sources, such as from a socket.

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Why does dividing two int not yield the right value when assigned to double?

c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is

  1. a/b is evaluated, creating a temporary of type int
  2. the value of the temporary is assigned to c after conversion to type double.

The value of a/b is determined without reference to its context (assignment to double).

Get MAC address using shell script

None of the above worked for me because my devices are in a balance-rr bond. Querying either would say the same MAC address with ip l l, ifconfig, or /sys/class/net/${device}/address, so one of them is correct, and one is unknown.

But this works if you haven't renamed the device (any tips on what I missed?):

udevadm info -q all --path "/sys/class/net/${device}"

And this works even if you rename it (eg. ip l set name x0 dev p4p1):

cat /proc/net/bonding/bond0

or my ugly script that makes it more parsable (untested driver/os/whatever compatibility):

awk -F ': ' '
         $0 == "" && interface != "" {
            printf "%s %s %s\n", interface, mac, status;
            interface="";
            mac=""
         }; 
         $1 == "Slave Interface" {
            interface=$2
         }; 
         $1 == "Permanent HW addr" {
            mac=$2
         };
         $1 == "MII Status" {
            status=$2
         };
         END {
            printf "%s %s %s\n", interface, mac, status
         }' /proc/net/bonding/bond0

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

How to bind inverse boolean properties in WPF?

Add one more property in your view model, which will return reverse value. And bind that to button. Like;

in view model:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

in xaml:

IsEnabled="{Binding IsNotReadOnly"}

Should I learn C before learning C++?

My two cents:

I suggest to learn C first, because :

  • it is a fundamental language - a lot of languages descended from C
  • more platforms supports C compiler than C++,- be it embedded systems, GPU chips, etc.
  • according to TIOBE index C is still about 2 times more popular than C++.

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Should I write script in the body or the head of the html?

I would answer this with multiple options actually, the some of which actually render in the body.

  • Place library script such as the jQuery library in the head section.
  • Place normal script in the head unless it becomes a performance/page load issue.
  • Place script associated with includes, within and at the end of that include. One example of this is .ascx user controls in asp.net pages - place the script at the end of that markup.
  • Place script that impacts the render of the page at the end of the body (before the body closure).
  • do NOT place script in the markup such as <input onclick="myfunction()"/> - better to put it in event handlers in your script body instead.
  • If you cannot decide, put it in the head until you have a reason not to such as page blocking issues.

Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).

EDIT: references:

Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; } on the div)

Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html

EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

How to reload/refresh jQuery dataTable?

Destroy the datatable first and then draw the datatable.

$('#table1').DataTable().destroy();
$('#table1').find('tbody').append("<tr><td><value1></td><td><value1></td></tr>");
$('#table1').DataTable().draw();

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

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

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

PHP - count specific array values

Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

ReactJS Two components communicating

The best approach would depend on how you plan to arrange those components. A few example scenarios that come to mind right now:

  1. <Filters /> is a child component of <List />
  2. Both <Filters /> and <List /> are children of a parent component
  3. <Filters /> and <List /> live in separate root components entirely.

There may be other scenarios that I'm not thinking of. If yours doesn't fit within these, then let me know. Here are some very rough examples of how I've been handling the first two scenarios:

Scenario #1

You could pass a handler from <List /> to <Filters />, which could then be called on the onChange event to filter the list with the current value.

JSFiddle for #1 ?

/** @jsx React.DOM */

var Filters = React.createClass({
  handleFilterChange: function() {
    var value = this.refs.filterInput.getDOMNode().value;
    this.props.updateFilter(value);
  },
  render: function() {
    return <input type="text" ref="filterInput" onChange={this.handleFilterChange} placeholder="Filter" />;
  }
});

var List = React.createClass({
  getInitialState: function() {
    return {
      listItems: ['Chicago', 'New York', 'Tokyo', 'London', 'San Francisco', 'Amsterdam', 'Hong Kong'],
      nameFilter: ''
    };
  },
  handleFilterUpdate: function(filterValue) {
    this.setState({
      nameFilter: filterValue
    });
  },
  render: function() {
    var displayedItems = this.state.listItems.filter(function(item) {
      var match = item.toLowerCase().indexOf(this.state.nameFilter.toLowerCase());
      return (match !== -1);
    }.bind(this));

    var content;
    if (displayedItems.length > 0) {
      var items = displayedItems.map(function(item) {
        return <li>{item}</li>;
      });
      content = <ul>{items}</ul>
    } else {
      content = <p>No items matching this filter</p>;
    }

    return (
      <div>
        <Filters updateFilter={this.handleFilterUpdate} />
        <h4>Results</h4>
        {content}
      </div>
    );
  }
});

React.renderComponent(<List />, document.body);

Scenario #2

Similar to scenario #1, but the parent component will be the one passing down the handler function to <Filters />, and will pass the filtered list to <List />. I like this method better since it decouples the <List /> from the <Filters />.

JSFiddle for #2 ?

/** @jsx React.DOM */

var Filters = React.createClass({
  handleFilterChange: function() {
    var value = this.refs.filterInput.getDOMNode().value;
    this.props.updateFilter(value);
  },
  render: function() {
    return <input type="text" ref="filterInput" onChange={this.handleFilterChange} placeholder="Filter" />;
  }
});

var List = React.createClass({
  render: function() {
    var content;
    if (this.props.items.length > 0) {
      var items = this.props.items.map(function(item) {
        return <li>{item}</li>;
      });
      content = <ul>{items}</ul>
    } else {
      content = <p>No items matching this filter</p>;
    }
    return (
      <div className="results">
        <h4>Results</h4>
        {content}
      </div>
    );
  }
});

var ListContainer = React.createClass({
  getInitialState: function() {
    return {
      listItems: ['Chicago', 'New York', 'Tokyo', 'London', 'San Francisco', 'Amsterdam', 'Hong Kong'],
      nameFilter: ''
    };
  },
  handleFilterUpdate: function(filterValue) {
    this.setState({
      nameFilter: filterValue
    });
  },
  render: function() {
    var displayedItems = this.state.listItems.filter(function(item) {
      var match = item.toLowerCase().indexOf(this.state.nameFilter.toLowerCase());
      return (match !== -1);
    }.bind(this));

    return (
      <div>
        <Filters updateFilter={this.handleFilterUpdate} />
        <List items={displayedItems} />
      </div>
    );
  }
});

React.renderComponent(<ListContainer />, document.body);

Scenario #3

When the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.

.htaccess redirect http to https

I had a problem with redirection also. I tried everything that was proposed on Stackoverflow. The one case I found by myself is:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP:SSL} !=1 [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

How to set xampp open localhost:8080 instead of just localhost

I agree and found this file under xammp-control the type of file is configuration. When I changed it to 8080 it worked automagically!

Get selected option from select element

Using the selectedOptions property (HTML5) you can get the selected option(s)

document.getElementbyId("id").selectedOptions; 

With JQuery can be achieved by doing this

$("#id")[0].selectedOptions; 

or

$("#id").prop("selectedOptions");

The property contains an HTMLCollection array similitar to this one selected option

[<option value=?"1">?ABC</option>]

or multiple selections

[<option value=?"1">?ABC</option>, <option value=?"2">?DEF</option> ...]

Getting pids from ps -ef |grep keyword

Try

ps -ef | grep "KEYWORD" | awk '{print $2}'

That command should give you the PID of the processes with KEYWORD in them. In this instance, awk is returning what is in the 2nd column from the output.

text box input height

Just use CSS to increase it's height:

<input type="text" style="height:30px;" name="item" align="left" />

Or, often times, you want to increase it's height by using padding instead of specifying an exact height:

<input type="text" style="padding: 5px;" name="item" align="left" />

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

Regex using javascript to return just numbers

As per @Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.

This will prevent errors if no matches are found and return an empty string:

('something'.match( /\d+/g )||[]).join('')

How to emulate GPS location in the Android Emulator?

For the new emulator:

http://developer.android.com/tools/devices/emulator.html#extended

Basically, click on the three dots button in the emulator controls (to the right of the emulator) and it will open up a menu which will allow you to control the emulator including location

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

Django CSRF check failing with an Ajax POST request

I've just encountered a bit different but similar situation. Not 100% sure if it'd be a resolution to your case, but I resolved the issue for Django 1.3 by setting a POST parameter 'csrfmiddlewaretoken' with the proper cookie value string which is usually returned within the form of your home HTML by Django's template system with '{% csrf_token %}' tag. I did not try on the older Django, just happened and resolved on Django1.3. My problem was that the first request submitted via Ajax from a form was successfully done but the second attempt from the exact same from failed, resulted in 403 state even though the header 'X-CSRFToken' is correctly placed with the CSRF token value as well as in the case of the first attempt. Hope this helps.

Regards,

Hiro

Reactjs: Unexpected token '<' Error

If you're like me and prone to silly mistakes, also check your package.json if it contains your babel preset:

  "babel": {
    "presets": [
      "env",
      "react",
      "stage-2"
    ]
  },

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I also tried http://www.eclipse.org/cdt/ in Ubuntu 12.04.2 LTS and works fine!

  1. First, I downloaded it from www.eclipse.org/downloads/, choosing Eclipse IDE for C/C++ Developers.
  2. I save the file somewhere, let´s say into my home directory. Open a console or terminal, and type:

    >>cd ~; tar xvzf eclipse*.tar.gz;

  3. Remember for having Eclipse running in Linux, it is required a JVM, so download a jdk file e.g jdk-7u17-linux-i586.rpm (I cann´t post the link due to my low reputation) ... anyway

  4. Install the .rpm file following http://www.wikihow.com/Install-Java-on-Linux

  5. Find the path to the Java installation, by typing:

    >>which java

  6. I got /usr/bin/java. To start up Eclipse, type:

    >>cd ~/eclipse; ./eclipse -vm /usr/bin/java

Also, once everything is installed, in the home directory, you can double-click the executable icon called eclipse, and then you´ll have it!. In case you like an icon, create a .desktop file in /usr/share/applications:

>>sudo gedit /usr/share/applications/eclipse.desktop

The .desktop file content is as follows:

[Desktop Entry]  
Name=Eclipse  
Type=Application  
Exec="This is the path of the eclipse executable on your machine"  
Terminal=false 
Icon="This is the path of the icon.xpm file on your machine"  
Comment=Integrated Development Environment  
NoDisplay=false  
Categories=Development;IDE  
Name[en]=eclipse.desktop  

Best luck!

Find and copy files

The reason for that error is that you are trying to copy a folder which requires -r option also to cp Thanks

How can I generate a unique ID in Python?

Perhaps uuid.uuid4() might do the job. See uuid for more information.

How to provide shadow to Button

Android now provides ExtendedFloatingActionButton which does the same thing for you.

Can a shell script set environment variables of the calling shell?

I don't see any answer documenting how to work around this problem with cooperating processes. A common pattern with things like ssh-agent is to have the child process print an expression which the parent can eval.

bash$ eval $(shh-agent)

For example, ssh-agent has options to select Csh or Bourne-compatible output syntax.

bash$ ssh-agent
SSH2_AUTH_SOCK=/tmp/ssh-era/ssh2-10690-agent; export SSH2_AUTH_SOCK;
SSH2_AGENT_PID=10691; export SSH2_AGENT_PID;
echo Agent pid 10691;

(This causes the agent to start running, but doesn't allow you to actually use it, unless you now copy-paste this output to your shell prompt.) Compare:

bash$ ssh-agent -c
setenv SSH2_AUTH_SOCK /tmp/ssh-era/ssh2-10751-agent;
setenv SSH2_AGENT_PID 10752;
echo Agent pid 10752;

(As you can see, csh and tcsh uses setenv to set varibles.)

Your own program can do this, too.

bash$ foo=$(makefoo)

Your makefoo script would simply calculate and print the value, and let the caller do whatever they want with it -- assigning it to a variable is a common use case, but probably not something you want to hard-code into the tool which produces the value.

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

Because python's math library is a thin wrapper around the C math library which returns floats.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

How to Git stash pop specific stash in 1.8.3?

If you want to be sure to not have to deal with quotes for the syntax stash@{x}, use Git 2.11 (Q4 2016)

See commit a56c8f5 (24 Oct 2016) by Aaron M Watson (watsona4).
(Merged by Junio C Hamano -- gitster -- in commit 9fa1f90, 31 Oct 2016)

stash: allow stashes to be referenced by index only

Instead of referencing "stash@{n}" explicitly, make it possible to simply reference as "n".
Most users only reference stashes by their position in the stash stack (what I refer to as the "index" here).

The syntax for the typical stash (stash@{n}) is slightly annoying and easy to forget, and sometimes difficult to escape properly in a script.

Because of this the capability to do things with the stash by simply referencing the index is desirable.

So:

git stash drop 1
git stash pop 1
git stash apply 1
git stash show 1

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Disabling swap files creation in vim

create no vim swap file just for a particular file

autocmd bufenter  c:/aaa/Dropbox/TapNote/Todo.txt :set noswapfile

"SDK Platform Tools component is missing!"

Before update SDK components, check in Android SDK Manager ? Tools ? Options and set HTTP proxy and port if it is set in local LAN.

How to get integer values from a string in Python?

>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498

If there are multiple integers in the string:

>>> map(int, re.findall(r'\d+', string1))
[498]

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I had this segmentation fault error because of Memory issues. My struct having many variables and arrays, had this Array of size 1024.

Reducing the size to 512, the error was gone.

P.S: This is a workaround and not a solution. It is necessary to find the struct size and dynamic memory allocation is a better option.

Python loop to run for certain amount of seconds

For those using asyncio, an easy way is to use asyncio.wait_for():

async def my_loop():
    res = False
    while not res:
        res = await do_something()

await asyncio.wait_for(my_loop(), 10)

The project description file (.project) for my project is missing

I am using Eclipse 3.5.1 on Ubuntu. After rebooting my machine my projects in PHP Explorer view were giving the warning that the .project file was missing. The problem was that the external directory where my projects are hosted was not mounted on reboot. So I did a mount -a from the command line and the Eclipse recognized the files.

How to sort findAll Doctrine's method?

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findBy([], ['username' => 'ASC']);

How to remove the default link color of the html hyperlink 'a' tag?

You can use System Color (18.2) values, introduced with CSS 2.0, but deprecated in CSS 3.

a:link, a:hover, a:active { color: WindowText; }

That way your anchor links will have the same color as normal document text on this system.

How to use awk sort by column 3

You can choose a delimiter, in this case I chose a colon and printed the column number one, sorting by alphabetical order:

awk -F\: '{print $1|"sort -u"}' /etc/passwd

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

Your question in somewhat confusing in that that you don't explain what you mean by "current element".

If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.

But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.

Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:

<form action="...">
    <input type="hidden" name="rowId" value="...">
    <button type="submit" name="myaction" value="edit">Edit</button>
    <button type="submit" name="myaction" value="delete">Delete</button>
</form>

When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).

Then on the server you just read the value of the variable "myaction" and decide what to do.

What is the difference between join and merge in Pandas?

One of the difference is that merge is creating a new index, and join is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge.

For example:

import pandas as pd

df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
                    'date': [201801, 201801, 201802, 201802],
                    'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1

       date  org_index  val
101  201801        101    1
102  201801        102    2
103  201802        103    3
104  201802        104    4

-

df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2

       dateval
date          
201801       A
201802       B

-

df1.merge(df2, on='date')

     date  org_index  val dateval
0  201801        101    1       A
1  201801        102    2       A
2  201802        103    3       B
3  201802        104    4       B

-

df1.join(df2, on='date')
       date  org_index  val dateval
101  201801        101    1       A
102  201801        102    2       A
103  201802        103    3       B
104  201802        104    4       B

Datatables Select All Checkbox

Base on Francisco Daniel's answer I modified some of the Jquery code here's My version. I removed some excess code and use "fa" instead of "far" for the icon. I also remove the "far fa-minus-square" since I can't understand its purpose.

-- Edited --

I added the "draw" event for the button icon to update whenever the table is redrawn or reloaded. Because I noticed when I tried to reload the table using "myTable.ajax.reload()" the button icon is not changing.

https://codepen.io/john-kenneth-larbo/pen/zXeYpz

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    let myTable = $('#example').DataTable({_x000D_
        columnDefs: [{_x000D_
            orderable: false,_x000D_
            className: 'select-checkbox',_x000D_
            targets: 0,_x000D_
        }],_x000D_
        select: {_x000D_
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'_x000D_
            selector: 'td:first-child',_x000D_
        },_x000D_
        order: [_x000D_
            [1, 'asc'],_x000D_
        ],_x000D_
    });_x000D_
_x000D_
       myTable.on('select deselect draw', function () {_x000D_
        var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
        var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
        if (selectedRows < all) {_x000D_
            $('#MyTableCheckAllButton i').attr('class', 'fa fa-square-o');_x000D_
        } else {_x000D_
            $('#MyTableCheckAllButton i').attr('class', 'fa fa-check-square-o');_x000D_
        }_x000D_
_x000D_
    });_x000D_
_x000D_
    $('#MyTableCheckAllButton').click(function () {_x000D_
        var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
        var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
_x000D_
        if (selectedRows < all) {_x000D_
            //Added search applied in case user wants the search items will be selected_x000D_
            myTable.rows({ search: 'applied' }).deselect();_x000D_
            myTable.rows({ search: 'applied' }).select();_x000D_
        } else {_x000D_
            myTable.rows({ search: 'applied' }).deselect();_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>_x000D_
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">_x000D_
                <i class="far fa-square"></i>  _x000D_
                </button>_x000D_
            </th>_x000D_
            <th>Name</th>_x000D_
            <th>Position</th>_x000D_
            <th>Office</th>_x000D_
            <th>Age</th>_x000D_
            <th>Salary</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Tiger Nixon</td>_x000D_
            <td>System Architect</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>61</td>_x000D_
            <td>$320,800</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Garrett Winters</td>_x000D_
            <td>Accountant</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>63</td>_x000D_
            <td>$170,750</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Ashton Cox</td>_x000D_
            <td>Junior Technical Author</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>66</td>_x000D_
            <td>$86,000</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Cedric Kelly</td>_x000D_
            <td>Senior Javascript Developer</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>22</td>_x000D_
            <td>$433,060</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Airi Satou</td>_x000D_
            <td>Accountant</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>33</td>_x000D_
            <td>$162,700</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Brielle Williamson</td>_x000D_
            <td>Integration Specialist</td>_x000D_
            <td>New York</td>_x000D_
            <td>61</td>_x000D_
            <td>$372,000</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Herrod Chandler</td>_x000D_
            <td>Sales Assistant</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>59</td>_x000D_
            <td>$137,500</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Rhona Davidson</td>_x000D_
            <td>Integration Specialist</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>55</td>_x000D_
            <td>$327,900</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Colleen Hurst</td>_x000D_
            <td>Javascript Developer</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>39</td>_x000D_
            <td>$205,500</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Sonya Frost</td>_x000D_
            <td>Software Engineer</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>23</td>_x000D_
            <td>$103,600</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Jena Gaines</td>_x000D_
            <td>Office Manager</td>_x000D_
            <td>London</td>_x000D_
            <td>30</td>_x000D_
            <td>$90,560</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
    <tfoot>_x000D_
        <tr>_x000D_
            <th></th>_x000D_
            <th>Name</th>_x000D_
            <th>Position</th>_x000D_
            <th>Office</th>_x000D_
            <th>Age</th>_x000D_
            <th>Salary</th>_x000D_
        </tr>_x000D_
    </tfoot>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Here is the solutions that worked for me:

  1. open index.php from the htdocs folder
  2. inside replace the word dashboard with your database name.
  3. restart the server

This should resolve the issue :-)

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to make div follow scrolling smoothly with jQuery?

I needed the div to stop when it reach a certain object, so i did it like this:

var el = $('#followdeal');
    var elpos_original = el.offset().top;
    $(window).scroll(function(){
        var elpos = el.offset().top;
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos;
        var stophere = ( $('#filtering').offset().top ) - 170;
        if(windowpos<elpos_original || windowpos>=stophere) {
            finaldestination = elpos_original;
            el.stop().animate({'top':10});
        } else {
            el.stop().animate({'top':finaldestination-elpos_original+10},500);
        }
    });

Converting Epoch time into the datetime

To convert your time value (float or int) to a formatted string, use:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

Script for rebuilding and reindexing the fragmented index?

Query for REBUILD/REORGANIZE Indexes

  • 30%<= Rebuild
  • 5%<= Reorganize
  • 5%> do nothing

Query:

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName, 
ind.name AS IndexName, indexstats.index_type_desc AS IndexType, 
indexstats.avg_fragmentation_in_percent,
'ALTER INDEX ' + QUOTENAME(ind.name)  + ' ON ' +QUOTENAME(object_name(ind.object_id)) + 
CASE    WHEN indexstats.avg_fragmentation_in_percent>30 THEN ' REBUILD ' 
        WHEN indexstats.avg_fragmentation_in_percent>=5 THEN 'REORGANIZE'
        ELSE NULL END as [SQLQuery]  -- if <5 not required, so no query needed
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats 
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id 
    AND ind.index_id = indexstats.index_id 
WHERE 
--indexstats.avg_fragmentation_in_percent , e.g. >10, you can specify any number in percent 
ind.Name is not null 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

Output

TableName      IndexName            IndexType              avg_fragmentation_in_percent SQLQuery
--------------------------------------------------------------------------------------- ------------------------------------------------------
Table1         PK_Table1            CLUSTERED INDEX        75                           ALTER INDEX [PK_Table1] ON [Table1] REBUILD 
Table1         IX_Table1_col1_col2  NONCLUSTERED INDEX     66,6666666666667             ALTER INDEX [IX_Table1_col1_col2] ON [Table1] REBUILD 
Table2         IX_Table2_           NONCLUSTERED INDEX     10                           ALTER INDEX [IX_Table2_] ON [Table2] REORGANIZE
Table2         IX_Table2_           NONCLUSTERED INDEX     3                            NULL

Multiline strings in VB.NET

You can also use System.Text.StringBuilder class in this way:

Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")

Then you get the multiline string using:

sValue.ToString()

Converting Integer to Long

Simply:

Integer i = 7;
Long l = new Long(i);

What's the difference between a mock & stub?

Plus useful answers, One of the most powerful point of using Mocks than Subs

If the collaborator [which the main code depend on it] is not under our control (e.g. from a third-party library),
In this case, stub is more difficult to write rather than mock.

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

How to push object into an array using AngularJS

Push only work for array .

Make your arrayText object to Array Object.

Try Like this

JS

this.arrayText = [{
  text1: 'Hello',
  text2: 'world',
}];

this.addText = function(text) {
  this.arrayText.push(text);
}
this.form = {
  text1: '',
  text2: ''
};

HTML

<div ng-controller="TestController as testCtrl">
  <form ng-submit="addText(form)">
    <input type="text" ng-model="form.text1" value="Lets go">
    <input type="text" ng-model="form.text2" value="Lets go again">
    <input type="submit" value="add">
  </form>
</div>

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had a key file & a crt file but it wouldn't show in IIS because I couldn't attach the key to the certificate during the import. Ended up creating a pfx file containing the certificate & the key, and after that it worked (When importing to the computer and not local user)

Created the file with OpenSSL (Download first).

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt

How do I print output in new line in PL/SQL?

Most likely you need to use this trick:

dbms_output.put_line('Hi' || chr(10) || 
                     'good' || chr(10) || 
                     'morning' || chr(10) || 
                     'friends' || chr(10));

Cut Corners using CSS

This code allows you to cut corners on each side of the rectangle:

div {
  display:block;
  height: 300px;
  width: 200px;
  background: url('http://lorempixel.com/180/290/') no-repeat;
  background-size:cover;

  -webkit-clip-path: polygon(10px 0%, calc(100% - 10px) 0%, 100% 10px, 100% calc(100% - 10px), calc(100% - 10px) 100%, 10px 100%, 0% calc(100% - 10px), 0% 10px);
  clip-path: polygon(10px 0%, calc(100% - 10px) 0%, 100% 10px, 100% calc(100% - 10px), calc(100% - 10px) 100%, 10px 100%, 0% calc(100% - 10px), 0% 10px);
}

http://jsfiddle.net/2bZAW/5552/

enter image description here

Virtualenv Command Not Found

this works in ubuntu 18 and above (not tested in previous versions):

sudo apt install python3-virtualenv

Calculate date from week number

I used one of the solutions but it gave me wrong results, simply because it counts Sunday as a first day of the week.

I changed:

var firstDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber - 1) * 7);
var lastDay = firstDay.AddDays(6);

to:

var lastDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber) * 7);
var firstDay = lastDay.AddDays(-6);

and now it is working as a charm.

Access mysql remote database from command line

This one worked for me in mysql 8, replace hostname with your hostname and port_number with your port_number, you can also change your mysql_user if he is not root

      mysql --host=host_name --port=port_number -u root -p

Further Information Here

Understanding the difference between Object.create() and new SomeFunction()

Accordingly to this answer and to this video new keyword does next things:

  1. Creates new object.

  2. Links new object to constructor function (prototype).

  3. Makes this variable point to the new object.

  4. Executes constructor function using the new object and implicit perform return this;

  5. Assigns constructor function name to new object's property constructor.

Object.create performs only 1st and 2nd steps!!!

SQL ORDER BY date problem

this should work for your date format

order by convert(date, your_column, 104) desc

Finding the Eclipse Version Number

(Update September 2012):

MRT points out in the comments that "Eclipse Version" question references a .eclipseproduct in the main folder, and it contains:

name=Eclipse Platform
id=org.eclipse.platform
version=3.x.0

So that seems more straightforward than my original answer below.

Also, Neeme Praks mentions below that there is a eclipse/configuration/config.ini which includes a line like:

eclipse.buildId=4.4.1.M20140925-0400

Again easier to find, as those are Java properties set and found with System.getProperty("eclipse.buildId").


Original answer (April 2009)

For Eclipse Helios 3.6, you can deduce the Eclipse Platform version directly from the About screen:
It is a combination of the Eclipse global version and the build Id:

alt text

Here is an example for Eclipse 3.6M6:
The version would be: 3.6.0.v201003121448, after the version 3.6.0 and the build Id I20100312-1448 (an Integration build from March 12th, 2010 at 14h48

To see it more easily, click on "Plugin Details" and sort by Version.


Note: Eclipse3.6 has a brand new cool logo:

alt text

And you can see the build Id now being displayed during the loading step of the different plugin.

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

how to check if List<T> element contains an item with a Particular Property Value

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

how to avoid extra blank page at end while printing?

Strangely setting a transparent border solved this for me:

@media print {
  div {
    border: 1px solid rgba(0,0,0,0)
  }
}

Maybe it will suffice to set the border on the container element. <- Untestet.

How to create an email form that can send email using html

Short answer, you can't.

HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.

Stop all active ajax requests in jQuery

Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.

I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

How to enter special characters like "&" in oracle database?

strAdd=strAdd.replace("&","'||'&'||'");

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

Converting URL to String and back again

fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use

let url = NSURL(string: urlstring)

to convert it back to NSURL. Example:

let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

to_string not declared in scope

//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);

How can I capture the right-click event in JavaScript?

I think that you are looking for something like this:

   function rightclick() {
    var rightclick;
    var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert(rightclick); // true or false, you can trap right click here by if comparison
}

(http://www.quirksmode.org/js/events_properties.html)

And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >

Bootstrap navbar Active State not working

For bootstrap mobile menu un-collapse after clicking a item you can use this

$("ul.nav.navbar-nav li a").click(function() {    

    $(".navbar-collapse").removeClass("in");
});

Change background color of edittext in android

one line of lazy code:

mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

Get the data received in a Flask request

Use request.get_json() to get posted JSON data.

data = request.get_json()
name = data.get('name', '')

Use request.form to get data when submitting a form with the POST method.

name = request.form.get('name', '')

Use request.args to get data passed in the query string of the URL, like when submitting a form with the GET method.

request.args.get("name", "")

request.form etc. are dict-like, use the get method to get a value with a default if it wasn't passed.

ImageView - have height match width?

For people passing by now, in 2017, the new best way to achieve what you want is by using ConstraintLayout like this:

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintDimensionRatio="1:1" />

And don't forget to add constraints to all of the four directions as needed by your layout.

Build a Responsive UI with ConstraintLayout

Furthermore, by now, PercentRelativeLayout has been deprecated (see Android documentation).

VLook-Up Match first 3 characters of one column with another column

Something neat...

I wanted to look up an "Exact Town ID" based on a "Partial Exact Town Name" BUT although I had the entire town name I was searching against a list of Partial town names. So I First found the "Exact Town Name" based on the part (which was actually a partial name since the "master list" is partial names unfortunately)... THEN searched for the "Exact Town ID" based on that Exact town name SO all my Vlookups/Index/Match-whatevers....were set to EXACT ....

=INDEX(county_cheatsheet!$E$1:$E$516,MATCH(VLOOKUP(LEFT(D3,3)&"*",county_cheatsheet!$E$1:$E$516,1,FALSE),county_cheatsheet!$E$1:E$516,0))

The lookup of the "first three letters of the partial town name against the list of partial town names is the MATCH(VLOOKUP(LEFT(D3,3)&"*" part

How can I remount my Android/system as read-write in a bash script using adb?

In addition to all the other answers you received, I want to explain the unknown option -- o error: Your command was

$ adb shell 'su -c  mount -o rw,remount /system'

which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell. However, su -c <cmd> also needs you to quote the command with arguments it shall pass to the shell's -c option. (YMMV depending on su variants.) Therefore, you might want to try

$ adb shell 'su -c "mount -o rw,remount /system"'

(and potentially add the actual device listed in the output of mount | grep system before the /system arg – see the other answers.)

Vue.js dynamic images not working

You can use try catch block to help with not found images

getProductImage(id) {
          var images = require.context('@/assets/', false, /\.jpg$/)
          let productImage = ''
          try {
            productImage = images(`./product${id}.jpg`)
          } catch (error) {
            productImage = images(`./no_image.jpg`)
          }
          return productImage
},