Programs & Examples On #Editorformodel

HTML helper that returns an HTML input element for each property in the model.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

you can use indexing if your enumerable type is string like below

((string[])MyEnumerableStringList)[0]

How to make jQuery UI nav menu horizontal?

changing:

.ui-menu .ui-menu-item { 
    margin: 0; 
    padding: 0; 
    zoom: 1; 
    width: 100%; 
}

to:

.ui-menu .ui-menu-item { 
    margin: 0; 
    padding: 0; 
    zoom: 1; 
    width: auto; 
    float:left; 
 }

should start you off.

In Bootstrap 3,How to change the distance between rows in vertical?

Instead of adding any tag which is never a good solution. You can always use margin property with the required element.

You can add the margin on row class itself. So it will affect globally.

.row{
  margin-top: 30px;
  margin-bottom: 30px
}

Update: Better solution in all cases would be to introduce a new class and then use it along with .row class.

.row-m-t{
  margin-top : 20px
}

Then use it wherever you want

<div class="row row-m-t"></div>

What is the difference between Cloud, Grid and Cluster?

my two cents worth ~

Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.

Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers

Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers

Custom method names in ASP.NET Web API

Web Api by default expects URL in the form of api/{controller}/{id}, to override this default routing. you can set routing with any of below two ways.

First option:

Add below route registration in WebApiConfig.cs

config.Routes.MapHttpRoute(
    name: "CustomApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Decorate your action method with HttpGet and parameters as below

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

 {

// your code here

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

Second option Add route prefix to Controller class and Decorate your action method with HttpGet as below. In this case no need change any WebApiConfig.cs. It can have default routing.

[RoutePrefix("api/{controller}/{action}")]
public class MyDataController : ApiController
{

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

{

// your code here

}

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

Hibernate: best practice to pull all lazy collections

There are some kind of misunderstanding about lazy collections in JPA-Hibernate. First of all let's clear that why trying to read a lazy collection throws exceptions and not just simply returns NULL for converting or further use cases?.

That's because Null fields in Databases especially in joined columns have meaning and not simply not-presented state, like programming languages. when you're trying to interpret a lazy collection to Null value it means (on Datastore-side) there is no relations between these entities and it's not true. so throwing exception is some kind of best-practice and you have to deal with that not the Hibernate.

So as mentioned above I recommend to :

  1. Detach the desired object before modifying it or using stateless session for querying
  2. Manipulate lazy fields to desired values (zero,null,etc.)

also as described in other answers there are plenty of approaches(eager fetch, joining etc.) or libraries and methods for doing that, but you have to setting up your view of what's happening before dealing with the problem and solving it.

How to get file's last modified date on Windows command line?

What output (exactly) does dir myfile.txt give in the current directory? What happens if you set the delimiters?

FOR /f "tokens=1,2* delims= " %%a in ('dir myfile.txt^|find /i " myfile.txt"') DO SET fileDate=%%a 

(note the space after delims=)
(to make life easier, you can do this from the command line by replacing %%a with %a)

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

How to write multiple conditions in Makefile.am with "else if"

ptomato's code can also be written in a cleaner manner like:

ifeq ($(TARGET_CPU),x86)
  TARGET_CPU_IS_X86 := 1
else ifeq ($(TARGET_CPU),x86_64)
  TARGET_CPU_IS_X86 := 1
else
  TARGET_CPU_IS_X86 := 0
endif

This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.

How to use mongoimport to import csv

C:\wamp\mongodb\bin>mongoexport --db proj_mmm --collection offerings --csv --fieldFile offerings_fields.txt --out offerings.csv

Iptables setting multiple multiports in one rule

You need to use multiple rules to implement OR-like semantics, since matches are always AND-ed together within a rule. Alternatively, you can do matching against port-indexing ipsets (ipset create blah bitmap:port).

Python convert decimal to hex

Instead of printing everything in the function, you could just allow it to return the value in hex, and do whatever you want with it.

def ChangeHex(n):
    x = (n % 16)
    c = ""
    if (x < 10):
        c = x
    if (x == 10):
        c = "A"
    if (x == 11):
        c = "B"
    if (x == 12):
        c = "C"
    if (x == 13):
        c = "D"
    if (x == 14):
        c = "E"
    if (x == 15):
        c = "F"

    if (n - x != 0):
        return ChangeHex(n / 16) + str(c)
    else:
        return str(c)

print(ChangeHex(52))

There are probably more elegant ways of parsing the alphabetic components of the hex, instead of just using conditionals.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

Pass a PHP string to a JavaScript variable (and escape newlines)

function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}

How to parse JSON response from Alamofire API in Swift?

I usually use Gloss library to serialize or deserialize JSON in iOS. For example, I have JSON that looks like this:

{"ABDC":[{"AB":"qwerty","CD":"uiop"}],[{"AB":"12334","CD":"asdf"}]}

First, I model the JSON array in Gloss struct:

Struct Struct_Name: Decodable {
   let IJ: String?
   let KL: String?
   init?(json: JSON){
       self.IJ = "AB" <~~ json
       self.KL = "CD" <~~ json
   }
}

And then in Alamofire responseJSON, I do this following thing:

Alamofire.request(url, method: .get, paramters: parametersURL).validate(contentType: ["application/json"]).responseJSON{ response in
 switch response.result{
   case .success (let data):
    guard let value = data as? JSON,
       let eventsArrayJSON = value["ABDC"] as? [JSON]
    else { fatalError() }
    let struct_name = [Struct_Name].from(jsonArray: eventsArrayJSON)//the JSON deserialization is done here, after this line you can do anything with your JSON
    for i in 0 ..< Int((struct_name?.count)!) {
       print((struct_name?[i].IJ!)!)
       print((struct_name?[i].KL!)!)
    }
    break

   case .failure(let error):
    print("Error: \(error)")
    break
 }
}

The output from the code above:

qwerty
uiop
1234
asdf

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

awk without printing newline

If Perl is an option, here is a solution using fedorqui's example:

seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'

Explanation:
chomp removes the newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

Sequence contains no matching element

From the MSDN library:

The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault method.

How to vertically center a "div" element for all browsers using CSS?

I did it with this (change width, height, margin-top and margin-left accordingly):

.wrapper {
    width:960px;
    height:590px;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-295px;
    margin-left:-480px;
}

<div class="wrapper"> -- Content -- </div>

Reading a registry key in C#

using Microsoft.Win32;

  string chkRegVC = "NO";
   private void checkReg_vcredist() {

        string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
        using (Microsoft.Win32.RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(regKey))
        {
            if (uninstallKey != null)
            {
                string[] productKeys = uninstallKey.GetSubKeyNames();
                foreach (var keyName in productKeys)
                {

                    if (keyName == "{196BB40D-1578-3D01-B289-BEFC77A11A1E}" ||//Visual C++ 2010 Redistributable Package (x86) 
                        keyName == "{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}" ||//Visual C++ 2010 Redistributable Package (x64) 
                        keyName == "{C1A35166-4301-38E9-BA67-02823AD72A1B}" ||//Visual C++ 2010 Redistributable Package (ia64) 
                        keyName == "{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}" ||//Visual C++ 2010 SP1 Redistributable Package (x86) 
                        keyName == "{1D8E6291-B0D5-35EC-8441-6616F567A0F7}" ||//Visual C++ 2010 SP1 Redistributable Package (x64) 
                        keyName == "{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}"   //Visual C++ 2010 SP1 Redistributable Package (ia64) 
                        ) { chkRegVC = "OK"; break; }
                    else { chkRegVC = "NO"; }
                }
            }
        }
    }

Making LaTeX tables smaller?

if it's too long for one page, use the longtable package. and if it's too wide for the page, use p{width} in place of l,r, or c for the column specifier. you can also go smaller than \small, i.e. \footnotesize and \tiny. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace or something like that.

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

try avoiding use of view in xml design.I too had the same probem but when I removed the view. its worked perfectly.

like example:

             <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"                   
                android:hint="Username"
                android:inputType="number"                   
                android:textColor="#fff" />

            <view
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#f9d7db" />

also check and try changing by trial and error android:inputType="number" to android:inputType="text" or better not using it if not required .Sometimes keyboard stuck and gets error in some of the devices.

Ignore case in Python strings

You could translate each string to lowercase once --- lazily only when you need it, or as a prepass to the sort if you know you'll be sorting the entire collection of strings. There are several ways to attach this comparison key to the actual data being sorted, but these techniques should be addressed in a separate issue.

Note that this technique can be used not only to handle upper/lower case issues, but for other types of sorting such as locale specific sorting, or "Library-style" title sorting that ignores leading articles and otherwise normalizes the data before sorting it.

Angular 2 filter/search list

try this html code

<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of filteredItems | search: name">
   {{item.name}}
</div>

use search pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    if(!value)return null;
    if(!args)return value;

    args = args.toLowerCase();

    return value.filter(function(item){
        return JSON.stringify(item).toLowerCase().includes(args);
    });
}

}

Is there a standard sign function (signum, sgn) in C/C++?

Apparently, the answer to the original poster's question is no. There is no standard C++ sgn function.

Laravel Soft Delete posts

In Laravel 5.5 Soft Deleted works ( for me ).

Data Base

deleted_at Field, default NULL value

Model

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}

Controller

public function destroy($id)
{
    User::find($id)->delete();
}

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

SQL Server Convert Varchar to Datetime

You could do it this way but it leaves it as a varchar

declare @s varchar(50)

set @s = '2011-09-28 18:01:00'

select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)

or

select convert(varchar(20), @s, 105)

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

And I simply got this error because I used a totally different DocumentRoot directory.

My main DocumentRoot was the default /var/www/html and on the VirtualHost I used /sites/example.com

I have created a link on /var/www/html/example.com (to /sites/example.com). DocumentRoot was set to /var/www/html/example.com

It worked like a charm.

How to convert an OrderedDict into a regular dict in python3

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

How to execute a shell script in PHP?

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');

How do I specify different layouts for portrait and landscape orientations?

Just a reminder:

Remove orientation from android:configChanges attribute for the activity in your manifest xml file if you defined it:

android:configChanges="orientation|screenLayout|screenSize"

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Pointer arithmetic for void pointer in C

Compiler knows by type cast. Given a void *x:

  • x+1 adds one byte to x, pointer goes to byte x+1
  • (int*)x+1 adds sizeof(int) bytes, pointer goes to byte x + sizeof(int)
  • (float*)x+1 addres sizeof(float) bytes, etc.

Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql to fix the problem:

grant all privileges on . to root@'localhost' identified by 'Your password';

grant all privileges on . to root@'IP ADDRESS' identified by 'Your password?';

your can try this on any mysql user, its working.

Use below command to login mysql with iP address.

mysql -h 10.0.0.23 -u root -p

how to upload a file to my server using html

<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
   <input id="fileupload" name="myfile" type="file" />
   <input type="submit" value="submit" id="submit" />
</form>

To upload a file, it is essential to set enctype="multipart/form-data" on your form

You need that form type and then some php to process the file :)

You should probably check out Uploadify if you want something very customisable out of the box.

CSS3 selector to find the 2nd div of the same class

Selectors can be combined:

.bar:nth-child(2)

means "thing that has class bar" that is also the 2nd child.

Is nested function a good approach when required by only one function?

I found this question because I wanted to pose a question why there is a performance impact if one uses nested functions. I ran tests for the following functions using Python 3.2.5 on a Windows Notebook with a Quad Core 2.5 GHz Intel i5-2530M processor

def square0(x):
    return x*x

def square1(x):
    def dummy(y):
        return y*y
    return x*x

def square2(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    return x*x

def square5(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    def dummy3(y):
        return y*y
    def dummy4(y):
        return y*y
    def dummy5(y):
        return y*y
    return x*x

I measured the following 20 times, also for square1, square2, and square5:

s=0
for i in range(10**6):
    s+=square0(i)

and got the following results

>>> 
m = mean, s = standard deviation, m0 = mean of first testcase
[m-3s,m+3s] is a 0.997 confidence interval if normal distributed

square? m     s       m/m0  [m-3s ,m+3s ]
square0 0.387 0.01515 1.000 [0.342,0.433]
square1 0.460 0.01422 1.188 [0.417,0.503]
square2 0.552 0.01803 1.425 [0.498,0.606]
square5 0.766 0.01654 1.979 [0.717,0.816]
>>> 

square0 has no nested function, square1 has one nested function, square2 has two nested functions and square5 has five nested functions. The nested functions are only declared but not called.

So if you have defined 5 nested funtions in a function that you don't call then the execution time of the function is twice of the function without a nested function. I think should be cautious when using nested functions.

The Python file for the whole test that generates this output can be found at ideone.

Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

Changing three.js background to transparent or other color

I'd also like to add that if using the three.js editor don't forget to set the background colour to clear as well in the index.html.

background-color:#00000000

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Right click your project and choose properties in the properties dialog check the Java Compiler settings, maybe you have different workspace settings.

remove space between paragraph and unordered list

You can (A) change the markup to not use paragraphs

<span>Text</span>
<br>
<ul>
  <li>One</li>
</ul>
<span>Text 2</span>

Or (B) change the css

p{margin:0px;}

Demos here: http://jsfiddle.net/ZnpVu/1

Is it possible to specify the schema when connecting to postgres with JDBC?

I don't believe there is a way to specify the schema in the connection string. It appears you have to execute

set search_path to 'schema'

after the connection is made to specify the schema.

Find html label associated with a given input

There is a labels property in the HTML5 standard which points to labels which are associated to an input element.

So you could use something like this (support for native labels property but with a fallback for retrieving labels in case the browser doesn't support it)...

var getLabelsForInputElement = function(element) {
    var labels = [];
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && Array.prototype.push
        .apply(labels, document.querySelector("label[for='" + id + "']"));

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

// ES6
var getLabelsForInputElement = (element) => {
    let labels;
    let id = element.id;

    if (element.labels) {
        return element.labels;
    }

    if (id) {
        labels = Array.from(document.querySelector(`label[for='${id}']`)));
    }

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

Even easier if you're using jQuery...

var getLabelsForInputElement = function(element) {
    var labels = $();
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && (labels = $("label[for='" + id  + "']")));

    labels = labels.add($(element).parents("label"));

    return labels;
};

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

If you are allowed to run real native binaries, then this is your compiler:

https://github.com/ircmaxell/php-compiler

It's a PHP compiler written in PHP!

It compiles PHP code to its own VM code. This VM code can then either be interpreted by its own interpreter (also written in PHP, isn't that crazy?) or it can be translated to Bitcode. And using the LLVM compiler framework (clang and co), this Bitcode can be compiled into a native binary for any platform that LLVM supports (pretty much any platform that matters today). You can choose to either do that statically or each time just before the code is executed (JIT style). So the only two requirements for this compiler to work on your system is an installed PHP interpreter and an installed clang compiler.

If you are not allowed to run native binaries, you could use the compiler above as an interpreter and let it interpret its own VM code, yet this will be slow as you are running a PHP interpreter that itself is running on a PHP engine, so you have a "double interpretation".

Pythonic way to return list of every nth item in a larger list

Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:

>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> l = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']

But this is still far slower than just using list slicing.

Exception from HRESULT: 0x800A03EC Error

An additional cause for this error. The code sample below returns the error when the datatable (dtTable) has a blank tablename:

  ' Open Excel workbook
  objExcelApp = New Application
  objExcelWorkbook = objExcelApp.Workbooks.Add()
  objExcelSheet = objExcelWorkbook.ActiveSheet
  objExcelSheet.Name = dtTable.TableName

Another git process seems to be running in this repository

For me for any reason :

rm .git/index.lock

Didn't work, so I just went to the .git file and deleted it manually which worked fantastically.

How can I trigger the click event of another element in ng-click using angularjs?

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}
.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

Create a folder and sub folder in Excel VBA

This is a recursive version that works with letter drives as well as UNC. I used the error catching to implement it but if anyone can do one without, I would be interested to see it. This approach works from the branches to the root so it will be somewhat usable when you don't have permissions in the root and lower parts of the directory tree.

' Reverse create directory path. This will create the directory tree from the top    down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
    On Error GoTo goUpOneDir:
    If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
        MkDir strCheckPath
    End If
    Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
    If Err.Number = 76 Then
        Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "\") - 1))
        Call RevCreateDir(strCheckPath)
    End If
End Sub

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

Fastest method of screen capturing on Windows

This is what I use to collect single frames, but if you modify this and keep the two targets open all the time then you could "stream" it to disk using a static counter for the file name. - I can't recall where I found this, but it has been modified, thanks to whoever!

void dump_buffer()
{
   IDirect3DSurface9* pRenderTarget=NULL;
   IDirect3DSurface9* pDestTarget=NULL;
     const char file[] = "Pickture.bmp";
   // sanity checks.
   if (Device == NULL)
      return;

   // get the render target surface.
   HRESULT hr = Device->GetRenderTarget(0, &pRenderTarget);
   // get the current adapter display mode.
   //hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);

   // create a destination surface.
   hr = Device->CreateOffscreenPlainSurface(DisplayMde.Width,
                         DisplayMde.Height,
                         DisplayMde.Format,
                         D3DPOOL_SYSTEMMEM,
                         &pDestTarget,
                         NULL);
   //copy the render target to the destination surface.
   hr = Device->GetRenderTargetData(pRenderTarget, pDestTarget);
   //save its contents to a bitmap file.
   hr = D3DXSaveSurfaceToFile(file,
                              D3DXIFF_BMP,
                              pDestTarget,
                              NULL,
                              NULL);

   // clean up.
   pRenderTarget->Release();
   pDestTarget->Release();
}

Which HTTP methods match up to which CRUD methods?

It depends on the concrete situation.. but in general:

PUT = update or change a concrete resource with a concrete URI of the resource.

POST = create a new resource under the source of the given URI.

I.e.

Edit a blog post:

PUT: /blog/entry/1

Create a new one:

POST: /blog/entry

PUT may create a new resource in some circumstances where the URI of the new ressource is clear before the request. POST can be used to implement several other use cases, too, which are not covered by the others (GET, PUT, DELETE, HEAD, OPTIONS)

The general understanding for CRUD systems is GET = request, POST = create, Put = update, DELETE = delete

How do I use Wget to download all images into a single folder, from a URL?

Try this one:

wget -nd -r -P /save/location/ -A jpeg,jpg,bmp,gif,png http://www.domain.com

and wait until it deletes all extra information

jQuery: How can I show an image popup onclick of the thumbnail?

I like prettyPhoto

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Pass parameter from a batch file to a PowerShell script

Add the parameter declaration at the top of ps1 file

test.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

Result

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

You should run the $ mvn spring-boot:run from the folder where your pom.xml file is located and refer to this answer https://stackoverflow.com/a/33602837/4918021

Add context path to Spring Boot application

We can set it using WebServerFactoryCustomizer. This can be added directly in the spring boot main method class which starts up the Spring ApplicationContext.

@Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
      webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/demo");
}

How do I copy directories recursively with gulp?

So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.

One way I solved this problem was by making the beginning of the path relative. For your case:

gulp.src([
    'index.php',
    '*css/**/*',
    '*js/**/*',
    '*src/**/*',
])
.pipe(gulp.dest('/var/www/'));

The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)

This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/ at the same level as js, you would end up matching both.

This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.

On a CSS hover event, can I change another div's styling?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

How can I output leading zeros in Ruby?

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")

Whitespaces in java

If you want to consider a regular expression based way of doing it

if(text.split("\\s").length > 1){
    //text contains whitespace
}

Can you split a stream into two streams?

A collector can be used for this.

  • For two categories, use Collectors.partitioningBy() factory.

This will create a Map from Boolean to List, and put items in one or the other list based on a Predicate.

Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output.

Also, no need for the iterator, not even in the heads-only example you provided.

  • Binary splitting looks like this:
Random r = new Random();

Map<Boolean, List<String>> groups = stream
    .collect(Collectors.partitioningBy(x -> r.nextBoolean()));

System.out.println(groups.get(false).size());
System.out.println(groups.get(true).size());
  • For more categories, use a Collectors.groupingBy() factory.
Map<Object, List<String>> groups = stream
    .collect(Collectors.groupingBy(x -> r.nextInt(3)));
System.out.println(groups.get(0).size());
System.out.println(groups.get(1).size());
System.out.println(groups.get(2).size());

In case the streams are not Stream, but one of the primitive streams like IntStream, then this .collect(Collectors) method is not available. You'll have to do it the manual way without a collector factory. It's implementation looks like this:

[Example 2.0 since 2020-04-16]

    IntStream    intStream = IntStream.iterate(0, i -> i + 1).limit(100000).parallel();
    IntPredicate predicate = ignored -> r.nextBoolean();

    Map<Boolean, List<Integer>> groups = intStream.collect(
            () -> Map.of(false, new ArrayList<>(100000),
                         true , new ArrayList<>(100000)),
            (map, value) -> map.get(predicate.test(value)).add(value),
            (map1, map2) -> {
                map1.get(false).addAll(map2.get(false));
                map1.get(true ).addAll(map2.get(true ));
            });

In this example I initialize the ArrayLists with the full size of the initial collection (if this is known at all). This prevents resize events even in the worst-case scenario, but can potentially gobble up 2*N*T space (N = initial number of elements, T = number of threads). To trade-off space for speed, you can leave it out or use your best educated guess, like the expected highest number of elements in one partition (typically just over N/2 for a balanced split).

I hope I don't offend anyone by using a Java 9 method. For the Java 8 version, look at the edit history.

Convert decimal to binary in python

Without the 0b in front:

"{0:b}".format(int)

Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:

f"{int:b}"

How to find my Subversion server version number?

If you use VisualSVN Server, you can find out the version number by several different means.

Use VisualSVN Server Manager

Follow these steps to find out the version via the management console:

  1. Start the VisualSVN Server Manager console.
  2. See the Version at the bottom-right corner of the dashboard.

enter image description here

If you click Version you will also see the versions of the components.

enter image description here

Check the README.txt file

Follow these steps to find out the version from the readme.txt file:

  1. Start notepad.exe.
  2. Open the %VISUALSVN_SERVER%README.txt file. The first line shows the version number.

enter image description here

WPF MVVM: How to close a window

I think the most simple way has not been included already (almost). Instead of using Behaviours which adds new dependencies just use attached properties:

    using System;
    using System.Windows;
    using System.Windows.Controls;

    public class DialogButtonManager
    {
        public static readonly DependencyProperty IsAcceptButtonProperty = DependencyProperty.RegisterAttached("IsAcceptButton", typeof(bool), typeof(DialogButtonManager), new FrameworkPropertyMetadata(OnIsAcceptButtonPropertyChanged));
        public static readonly DependencyProperty IsCancelButtonProperty = DependencyProperty.RegisterAttached("IsCancelButton", typeof(bool), typeof(DialogButtonManager), new FrameworkPropertyMetadata(OnIsCancelButtonPropertyChanged));

        public static void SetIsAcceptButton(UIElement element, bool value)
        {
            element.SetValue(IsAcceptButtonProperty, value);
        }

        public static bool GetIsAcceptButton(UIElement element)
        {
            return (bool)element.GetValue(IsAcceptButtonProperty);
        }

        public static void SetIsCancelButton(UIElement element, bool value)
        {
            element.SetValue(IsCancelButtonProperty, value);
        }

        public static bool GetIsCancelButton(UIElement element)
        {
            return (bool)element.GetValue(IsCancelButtonProperty);
        }

        private static void OnIsAcceptButtonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            Button button = sender as Button;

            if (button != null)
            {
                if ((bool)e.NewValue)
                {
                    SetAcceptButton(button);
                }
                else
                {
                    ResetAcceptButton(button);
                }
            }
        }

        private static void OnIsCancelButtonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            Button button = sender as Button;

            if (button != null)
            {
                if ((bool)e.NewValue)
                {
                    SetCancelButton(button);
                }
                else
                {
                    ResetCancelButton(button);
                }
            }
        }

        private static void SetAcceptButton(Button button)
        {
            Window window = Window.GetWindow(button);
            button.Command = new RelayCommand(new Action<object>(ExecuteAccept));
            button.CommandParameter = window;
        }

        private static void ResetAcceptButton(Button button)
        {
            button.Command = null;
            button.CommandParameter = null;
        }

        private static void ExecuteAccept(object buttonWindow)
        {
            Window window = (Window)buttonWindow;

            window.DialogResult = true;
        }

        private static void SetCancelButton(Button button)
        {
            Window window = Window.GetWindow(button);
            button.Command = new RelayCommand(new Action<object>(ExecuteCancel));
            button.CommandParameter = window;
        }

        private static void ResetCancelButton(Button button)
        {
            button.Command = null;
            button.CommandParameter = null;
        }

        private static void ExecuteCancel(object buttonWindow)
        {
            Window window = (Window)buttonWindow;

            window.DialogResult = false;
        }
    }

Then just set it on your dialog buttons:

<UniformGrid Grid.Row="2" Grid.Column="1" Rows="1" Columns="2" Margin="3" >
    <Button Content="Accept" IsDefault="True" Padding="3" Margin="3,0,3,0" DialogButtonManager.IsAcceptButton="True" />
    <Button Content="Cancel" IsCancel="True" Padding="3" Margin="3,0,3,0" DialogButtonManager.IsCancelButton="True" />
</UniformGrid>

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

Read file from line 2 or skip header row

If slicing could work on iterators...

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

A Simply Swift,

Step 1: Create One SubClass of UITableViewCell
Step 2: Add this method to SubClass of UITableViewCell

override func layoutSubviews() {
    super.layoutSubviews()
    self.imageView?.frame = CGRectMake(0, 0, 10, 10)
}

Step 3: Create cell object using that SubClass in cellForRowAtIndexPath,

Ex: let customCell:CustomCell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

Step 4: Enjoy

XPath test if node value is number

I've been dealing with 01 - which is a numeric.

string(number($v)) != string($v) makes the segregation

simulate background-size:cover on <video> or <img>

Based on Daniel de Wit's answer and comments, I searched a bit more. Thanks to him for the solution.

The solution is to use object-fit: cover; which has a great support (every modern browser support it). If you really want to support IE, you can use a polyfill like object-fit-images or object-fit.

Demos :

_x000D_
_x000D_
img {_x000D_
  float: left;_x000D_
  width: 100px;_x000D_
  height: 80px;_x000D_
  border: 1px solid black;_x000D_
  margin-right: 1em;_x000D_
}_x000D_
.fill {_x000D_
  object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
  object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
  object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
  object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
  object-fit: scale-down;_x000D_
}
_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
_x000D_
_x000D_
_x000D_

and with a parent:

_x000D_
_x000D_
div {_x000D_
  float: left;_x000D_
  width: 100px;_x000D_
  height: 80px;_x000D_
  border: 1px solid black;_x000D_
  margin-right: 1em;_x000D_
}_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
.fill {_x000D_
  object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
  object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
  object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
  object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
  object-fit: scale-down;_x000D_
}
_x000D_
<div>_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to delete an app from iTunesConnect / App Store Connect

As the instructions state on the iTuneconnect Developer Guidelines you need to ensure that you are the "team agent" to delete apps. This is stated in the quote below from the developer guidelines.

If the Delete App button isn’t displayed, check that you’re the team agent and that the app is in one of the statuses that allow the app to be deleted.

I have just checked on my account by logging in as the main account holder and the delete button is there for an app that I have previously removed from sale but when I have looked in as another user they don't have this permission, only the main account holder seems to have it.

Accessing dict keys like an attribute?

Here's a short example of immutable records using built-in collections.namedtuple:

def record(name, d):
    return namedtuple(name, d.keys())(**d)

and a usage example:

rec = record('Model', {
    'train_op': train_op,
    'loss': loss,
})

print rec.loss(..)

How to install an apk on the emulator in Android Studio?

EDIT: Even though this answer is marked as the correct answer (in 2013), currently, as answered by @user2511630 below, you can drag-n-drop apk files directly into the emulator to install them.


Original Answer:

You can install .apk files to emulator regardless of what you are using (Eclipse or Android Studio)

here's what I always do: (For full beginners)

1- Run the emulator, and wait until it's completely started.

2- Go to your sdk installation folder then go to platform-tools (you should see an executable called adb.exe)

3- create a new file and call it run.bat, edit the file with notepad and write CMD in it and save it.

4- copy your desired apk to the same folder

5- now open run.bat and write adb install "your_apk_file.apk"

6- wait until the installation is complete

7- voila your apk is installed to your emulator.

Note: to re-install the application if it already existe use adb install -r "your_apk_file.apk"

sorry for the detailed instruction as I said for full beginners

Hope this help.

Regards,

Tarek

Example 1

Example 2

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

How to use border with Bootstrap

What others have mentioned about border vs border box is definitely correct. You can still get this to work without having to create any custom classes though: http://jsfiddle.net/panchroma/yfzdD/

HTML

<div class="container">
<div class="row" >
    <div class="span12">
       <div class="row">
        <div class="span4"> 1 </div>
        <div class="span4"> 2 </div>
        <div class="span4"> 3 </div>
        </div><!-- end nested row -->
    </div><!-- end span 12 -->

</div> <!-- end row -->
</div><!-- end container -->

CSS

.span12{
border:solid 2px black;
background-color:grey;  
}  

Good luck!

Multiple actions were found that match the request in Web Api

You can add [Route("api/[controller]/[action]")] to your controller class.

[Route("api/[controller]/[action]")]
[ApiController]
public class MySuperController : ControllerBase
{
 ...
}

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

In my case I parsed an S3 url into its components.

For example:

Url:    s3://bucket-name/path/to/file

Was parsed into:

Bucket: bucket-name
Path:   /path/to/file

Having the path part containing a leading '/' failed the request.

How to play a notification sound on websites?

I wrote a clean functional method of playing sounds:

sounds = {
    test : new Audio('/assets/sounds/test.mp3')
};

sound_volume = 0.1;

function playSound(sound) {
    sounds[sound].volume = sound_volume;
    sounds[sound].play();
}
function stopSound(sound) {
    sounds[sound].pause();
}
function setVolume(sound, volume) {
    sounds[sound].volume = volume;
    sound_volume = volume;
}

How to convert JSON string to array

If you ever need to convert JSON file or structures to PHP-style arrays, with all the nesting levels, you can use this function. First, you must json_decode($yourJSONdata) and then pass it to this function. It will output to your browser window (or console) the correct PHP styled arrays.

https://github.com/mobsted/jsontophparray

How to change working directory in Jupyter Notebook?

Running os.chdir(NEW_PATH) will change the working directory.

import os
os.getcwd()
Out[2]:
'/tmp'
In [3]:

os.chdir('/')
In [4]:


os.getcwd()
Out[4]:
'/'
In [ ]:

changing minDate option in JQuery DatePicker not working

How to dynamically alter the minDate (after init)

The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.

All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):

$('#datePickerId').datepicker('option', 'minDate', '3');

minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:

$('#datePickerId').datepicker(
    'option', 'minDate', new Date($(".datePop.start").val())
);

How to set the default minDate (at init)

Just answering this for best practice; the minDate option expects one of:

  1. a string in the current dateFormat OR
  2. number of days from today (e.g. +7) OR
  3. string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '-1y -1m')

@bogart setting the string to "0" is a solution as it satisfies option 2 above

$('#datePickerId').datepicker('minDate': '3');

jQuery UI docs for minDate

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

Best way to do a PHP switch with multiple values per case?

Version 2 does not work!!

case 'users.online' || 'users.location' || ...

is exactly the same as:

case True:

and that case will be chosen for any value of $p, unless $p is the empty string.

|| Does not have any special meaning inside a case statement, you are not comparing $p to each of those strings, you are just checking to see if it's not False.

How can I tell jackson to ignore a property for which I don't have control over the source code?

If you want to ALWAYS exclude certain properties for any class, you could use setMixInResolver method:

    @JsonIgnoreProperties({"id", "index", "version"})
    abstract class MixIn {
    }

    mapper.setMixInResolver(new ClassIntrospector.MixInResolver(){
        @Override
        public Class<?> findMixInClassFor(Class<?> cls) {
            return MixIn.class;  
        }

        @Override
        public ClassIntrospector.MixInResolver copy() {
            return this;
        }
    });

SSL Connection / Connection Reset with IISExpress

The problem that I was experiencing had to do with me, at some point in time, enabling HSTS for localhost and not realizing that this would break my http://localhost:someport in IIS Express.

HSTS tells the browser (Chrome in my case) to ALWAYS request a URL using HTTPS. So therefor even though I hadnt even enabled SSL for my MVC 5 app, the browser would still try to access my site using HTTPS in the URL instead of HTTP.

The fix?

  1. Surf to chrome://net-internals/#hsts
  2. In the delete section, enter "localhost" and delete the record from Chrome.

Calling a PHP function from an HTML form in the same file

You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.

HTML

<form method = 'post' action = '' id = 'theForm'>
...
</form>

JavaScript

$(function() {
    $("#theForm").submit(function() {
        var data = "a=5&b=6&c=7";
        $.ajax({
            url: "path/to/php/file.php",
            data: data,
            success: function(html) {
                .. anything you want to do upon success here ..
                alert(html); // alert the output from the PHP Script
            }
        });
        return false;
    });
});

Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.

var data = "a=5&b=6&c=7";

If that is your data string, then the PHP script will see this as:

echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7

You, however, will need to construct the data from the form fields as they exist for your form, such as:

var data = "user=" + $("#user").val();

(You will need to tag each form field with an 'id', the above id is 'user'.)

After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.

...
success: function(html) {
    alert(html);
}
...

How to revert uncommitted changes including files and folders?

Use:

git reset HEAD filepath

For example:

git reset HEAD om211/src/META-INF/persistence.xml

How to update array value javascript?

"But i want to know a better way to do this, if there is one ?"

Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }

How to retrieve a module's path?

import a_module
print(a_module.__file__)

Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:

import os
path = os.path.abspath(a_module.__file__)

You can also try:

path = os.path.dirname(a_module.__file__)

To get the module's directory.

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

Finding partial text in range, return an index

This formula will do the job:

=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)

you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1.

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

MySQL root access from all hosts

MYSQL 8.0 - open mysql command line client

GRANT ALL PRIVILEGES ON \*.* TO 'root'@'localhost';  

use mysql

UPDATE mysql.user SET host='%' WHERE user='root';  

Restart mysql service

Dynamically adding HTML form field using jQuery

This will insert a new element after the input field with id "password".

$(document).ready(function(){
  var newInput = $("<input name='new_field' type='text'>");
  $('input#password').after(newInput);
});

Not sure if this answers your question.

Rails 4 LIKE query - ActiveRecord adds quotes

Your placeholder is replaced by a string and you're not handling it right.

Replace

"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search

with

"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"

The maximum message size quota for incoming messages (65536) has been exceeded

If you are using CustomBinding then you would rather need to make changes in httptransport element. Set it as

 <customBinding>
    <binding ...>
     ...
     <httpsTransport maxReceivedMessageSize="2147483647"/>
    </binding>
 </customBinding>

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

How to Define Callbacks in Android?

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

Just as a random example:

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callbackCall() {
      // callback code goes here
   }
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

   void callbackCall() {
      // callback code goes here
   }
};

I probably messed up the syntax in option 2. It's early.

AngularJS : ng-model binding not updating when changed with jQuery

Just use:

$('#selectedDueDate').val(dateText).trigger('input');

instead of:

$('#selectedDueDate').val(dateText);

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

How can I set a proxy server for gem?

You need to write this in the command prompt:

set HTTP_PROXY=http://your_proxy:your_port

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

How to abort a Task like aborting a Thread (Thread.Abort method)?

If you have Task constructor, then we may extract Thread from the Task, and invoke thread.abort.

Thread th = null;

Task.Factory.StartNew(() =>
{
    th = Thread.CurrentThread;

    while (true)
    {
        Console.WriteLine(DateTime.UtcNow);
    }
});

Thread.Sleep(2000);
th.Abort();
Console.ReadKey();

How to fix committing to the wrong Git branch?

For multiple commits on the wrong branch

If, for you, it is just about 1 commit, then there are plenty of other easier resetting solutions available. For me, I had about 10 commits that I'd accidentally created on master branch instead of, let's call it target, and I did not want to lose the commit history.

What you could do, and what saved me was using this answer as a reference, using a 4 step process, which is -

  1. Create a new temporary branch temp from master
  2. Merge temp into the branch originally intended for commits, i.e. target
  3. Undo commits on master
  4. Delete the temporary branch temp.

Here are the above steps in details -

  1. Create a new branch from the master (where I had accidentally committed a lot of changes)

    git checkout -b temp
    

    Note: -b flag is used to create a new branch
    Just to verify if we got this right, I'd do a quick git branch to make sure we are on the temp branch and a git log to check if we got the commits right.

  2. Merge the temporary branch into the branch originally intended for the commits, i.e. target.
    First, switch to the original branch i.e. target (You might need to git fetch if you haven't)

    git checkout target
    

    Note: Not using -b flag
    Now, let's merge the temporary branch into the branch we have currently checkout out target

    git merge temp
    

    You might have to take care of some conflicts here, if there are. You can push (I would) or move on to the next steps, after successfully merging.

  3. Undo the accidental commits on master using this answer as reference, first switch to the master

    git checkout master
    

    then undo it all the way back to match the remote using the command below (or to particular commit, using appropriate command, if you want)

    git reset --hard origin/master
    

    Again, I'd do a git log before and after just to make sure that the intended changes took effect.

  4. Erasing the evidence, that is deleting the temporary branch. For this, first you need to checkout the branch that the temp was merged into, i.e. target (If you stay on master and execute the command below, you might get a error: The branch 'temp' is not fully merged), so let's

    git checkout target
    

    and then delete the proof of this mishap

    git branch -d temp
    

There you go.

ORA-00979 not a group by expression

The group by is used to aggregate some data, depending on the aggregate function, and other than that you need to put column or columns to which you need the grouping.

for example:

select d.deptno, max(e.sal) 
from emp e, dept d
where e.deptno = d.deptno
group by d.deptno;

This will result in the departments maximum salary.

Now if we omit the d.deptno from group by clause it will give the same error.

Access parent's parent from javascript object

In this case, you could use life to reference the parent object. Or you could store a reference to life in the users object. There can't be a fixed parent available to you in the language, because users is just a reference to an object, and there could be other references...

var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
//  - because life.users references the same object as death.residents!

You might find it helpful to use something like this:

function addChild(ob, childName, childOb)
{
   ob[childName] = childOb;
   childOb.parent = ob;
}

var life= {
        mameAndDestroy : function(group){ },
        kiss : function(group){ }
};

addChild(life, 'users', {
   guys : function(){ this.parent.mameAndDestroy(this.girls); },
   girls : function(){ this.parent.kiss(this.boys); },
   });

// life.users.parent now exists and points to life

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

How to have a drop down <select> field in a rails form?

Or for custom options

<%= f.select :desired_attribute, ['option1', 'option2']%>

What is the difference between "is None" and "== None"

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

How do I add a bullet symbol in TextView?

Since android doesnt support <ol>, <ul> or <li> html elements, I had to do it like this

<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>&#8226;name1<br />&#8226;name2<br /></p>]]></string>

if you want to maintain custom space then use </pre> tag

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

If REST applications are supposed to be stateless, how do you manage sessions?

Historical view of user application state management

Sessions in the traditional sense keep the user's state in the application inside the server. This may be the current page in a flow or what has been previously entered but not persisted to the main database yet.

The reason for this need was the lack of standards on the client side to effectively maintain the state without making client specific (i.e. browser specific) applications or plug-ins.

HTML5 and XML Header Request has over time standardized the notion of storing complex data including application state in standard way on the client (i.e. browser) side without resorting to going back and forth between the server.

General usage of REST services

REST services are generally called when there is a transaction that needs to be performed or if it needs to retrieve data.

REST services are meant to be called by the client-side application and not the end user directly.

Authenticating

For any request to the server, part of the request should contain the authorization token. How it is implemented is application specific, but in general is either a BASIC or CERTIFICATE form of authentication.

Form based authentication is not used by REST services. However, as noted above REST services are not meant to be called by the user, but by the application. The application needs to manage getting the authentication token. In my case I used cookies with JASPIC with OAuth 2.0 to connect to Google for authentication and simple HTTP Authentication for automated testing. I also used HTTP Header authentication via JASPIC for local testing as well (though the same approach can be performed in SiteMinder)

As per those examples, the authentication is managed on the client side (though SiteMinder or Google would store the authentication session on their end), there's nothing that can be done about that state, but it is not part of the REST service application.

Retrieval requests

Retrieval requests in REST are GET operations where a specific resource is requested and is cacheable. There is no need for server sessions because the request has everything it would need to retrieve the data: authentication and the URI.

Transaction scripts

As noted above, the client-side application itself calls the REST services along with the authentication that it manages on the client side as well.

What this means for REST services [if done correctly] is to take a single request to the REST server will contain everything that is needed for a single user operation that does everything that is needed in a single transaction, a Transaction Script is what the pattern is called.

This is done through a POST request usually, but others such as PUT can also be used.

A lot of contrived examples of REST (I myself did this) tried to follow as much of what has been defined in the HTTP protocol, after going through that I decided to be more pragmatic and left it to GET and POST only. The POST method does not even have to implement the POST-REDIRECT-GET pattern.

Regardless though, as I had noted above, the client-side application will be the one calling the service and it will only call the POST request with all the data when it needs to (not every time). This prevents constant requests to the server.

Polling

Though REST can be used for polling as well, I won't recommend it unless you have to use it because of browser compatibility. For that I would use WebSockets which I had designed an API contract for as well. Another alternative for older browsers is CometD.

How to Deserialize JSON data?

You can write your own JSON parser and make it more generic based on your requirement. Here is one which served my purpose nicely, hope will help you too.

class JsonParsor
{
    public static DataTable JsonParse(String rawJson)
    {
        DataTable dataTable = new DataTable();
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawJson);
        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        bool reading_number = false;
        while (s >= 0)
        {
            s = bufferreader.Read();
            //open JSON
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading)
                {
                    reading = true;
                    continue;
                }
                if ((char)s == '}' && !inside_string && !reading)
                    break;
                if ((char)s == ']' && !inside_string && !reading)
                    continue;
                if ((char)s == ',')
                    continue;
            }
            else
            {
                if (reading_value)
                {
                    if (!inside_string && (char)s >= '0' && (char)s <= '9')
                    {
                        reading_number = true;
                        valuebufferbuilder.Append((char)s);
                        continue;
                    }
                }
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    if ((char)s == '\"' && !inside_string)
                        inside_string = true;
                    if ((char)s == '[' && !inside_string)
                    {
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                                reading = false;
                                inside_string = false;
                                reading_value = false;
                    }
                    if ((char)s == ',' && !inside_string && reading_number)
                    {
                        if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                            dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                        if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                        reading_value = false;
                        reading_number = false;
                    }
                    continue;
                }

                //if we reach end of the string
                if (inside_string)
                {
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read();
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //put the key-value pair into dictionary
                            if(!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(),typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            keybufferbuilder.Length = 0;
                            valuebufferbuilder.Length = 0;
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            ICollection key = outdict.Keys;
                            DataRow newrow = dataTable.NewRow();
                            foreach (string k_loopVariable in key)
                            {
                                CommonModule.LogTheMessage(outdict[k_loopVariable],"","","");
                                newrow[k_loopVariable] = outdict[k_loopVariable];
                            }
                            dataTable.Rows.Add(newrow);
                            CommonModule.LogTheMessage(dataTable.Rows.Count.ToString(), "", "row_count", "");
                            outdict.Clear();
                            keybufferbuilder.Length=0;
                            valuebufferbuilder.Length=0;
                            reading_value = false;
                            reading = false;
                            continue;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }

        return dataTable;
    }
}

Python - How to convert JSON File to Dataframe

jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T

This should look like this:.

         FirstName LastName MiddleName password    username
0001      John     Mark      Lewis     2910  johnlewis2

Find the server name for an Oracle database

I use this query in order to retrieve the server name of my Oracle database.

SELECT program FROM v$session WHERE program LIKE '%(PMON)%';

MySQL parameterized queries

The linked docs give the following example:

   cursor.execute ("""
         UPDATE animal SET name = %s
         WHERE name = %s
       """, ("snake", "turtle"))
   print "Number of rows updated: %d" % cursor.rowcount

So you just need to adapt this to your own code - example:

cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%s, %s, %s, %s, %s, %s)

        """, (var1, var2, var3, var4, var5, var6))

(If SongLength is numeric, you may need to use %d instead of %s).

Generating a UUID in Postgres for Insert statement?

Without extensions (cheat)

SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);

output>> c2d29867-3d0b-d497-9191-18a9d8ee7830

(works at least in 8.4)

  • Thanks to @Erwin Brandstetter for clock_timestamp() explanation.

If you need a valid v4 UUID

SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);

enter image description here * Thanks to @Denis Stafichuk @Karsten and @autronix


Also, in modern Postgres, you can simply cast:

SELECT md5(random()::text || clock_timestamp()::text)::uuid

React native text going off my screen, refusing to wrap. What to do?

The solution to that issue is flexShrink: 1.

<View
    style={{ flexDirection: 'row' }}
> 
   <Text style={{ flexShrink: 1 }}>
       Really really long text...
   </Text>
</View>

Depending on your set up, you may also also need to add flexShrink: 1 to the <View>'s parent as well, to get this to work, so play with that and you'll make it.

The solution was discovered by Adam Pietrasiak in this thread.

JavaScript naming conventions

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase could equally well be used the opposite way, it's just that language users tend to follow the language authors.

having said that, i think most libraries tend to roughly follow a simplification of Java's CamelCase. I find Douglas Crockford advices tasteful enough for me.

Different color for each bar in a bar chart; ChartJS

You can call this function which generates random colors for each bars

var randomColorGenerator = function () { 
    return '#' + (Math.random().toString(16) + '0000000').slice(2, 8); 
};

var barChartData = {
        labels: ["001", "002", "003", "004", "005", "006", "007"],
        datasets: [
            {
                label: "My First dataset",
                fillColor: randomColorGenerator(), 
                strokeColor: randomColorGenerator(), 
                highlightFill: randomColorGenerator(),
                highlightStroke: randomColorGenerator(),
                data: [20, 59, 80, 81, 56, 55, 40]
            }
        ]
    };

In Jenkins, how to checkout a project into a specific directory (using GIT)

I agree with @Lukasz Rzanek that we can use git plugin

But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory

enter image description here

Node.js global proxy setting

I finally created a module to get this question (partially) resolved. Basically this module rewrites http.request function, added the proxy setting then fire. Check my blog post: https://web.archive.org/web/20160110023732/http://blog.shaunxu.me:80/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

jQuery Datepicker onchange event issue

DatePicker selected value change event code below

/* HTML Part */
<p>Date: <input type="text" id="datepicker"></p>

/* jQuery Part */
$("#datepicker").change(function() {
                selectedDate= $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
                alert(selectedDate);        
            });

How to get memory available or used in C#

You might want to check the GC.GetTotalMemory method.

It retrieves the number of bytes currently thought to be allocated by the garbage collector.

What is the purpose of "&&" in a shell command?

It's to execute a second statement if the first statement ends succesfully. Like an if statement:

 if (1 == 1 && 2 == 2)
  echo "test;"

Its first tries if 1==1, if that is true it checks if 2==2

Select method in List<t> Collection

you can also try

var query = from p in list
            where p.Age > 18
            select p;

HTML table with 100% width, with vertical scroll inside tbody

Adding a fixed width to td,th after making tbody & thead display block works perfectly and also we can use slimscroll plugin to make the scroll bar beautiful.

enter image description here

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <title> Scrollable table </title>_x000D_
    <style>_x000D_
        body {_x000D_
            font-family: sans-serif;_x000D_
            font-size: 0.9em;_x000D_
        }_x000D_
        table {_x000D_
            border-collapse: collapse;_x000D_
            border-bottom: 1px solid #ddd;_x000D_
        }_x000D_
        thead {_x000D_
            background-color: #333;_x000D_
            color: #fff;_x000D_
        }_x000D_
        thead,tbody {_x000D_
            display: block;_x000D_
        }_x000D_
        th,td {_x000D_
            padding: 8px 10px;_x000D_
            border: 1px solid #ddd;_x000D_
            width: 117px;_x000D_
            box-sizing: border-box;_x000D_
        }_x000D_
        tbody {_x000D_
            height: 160px;_x000D_
            overflow-y: scroll_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <table class="example-table">_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th> Header 1 </th>_x000D_
                <th> Header 2 </th>_x000D_
                <th> Header 3 </th>_x000D_
                <th> Header 4 </th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td> Row 1- Col 1 </td>_x000D_
                <td> Row 1- Col 2 </td>_x000D_
                <td> Row 1- Col 3 </td>_x000D_
                <td> Row 1- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 2- Col 1 </td>_x000D_
                <td> Row 2- Col 2 </td>_x000D_
                <td> Row 2- Col 3 </td>_x000D_
                <td> Row 2- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 3- Col 1 </td>_x000D_
                <td> Row 3- Col 2 </td>_x000D_
                <td> Row 3- Col 3 </td>_x000D_
                <td> Row 3- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 4- Col 1 </td>_x000D_
                <td> Row 4- Col 2 </td>_x000D_
                <td> Row 4- Col 3 </td>_x000D_
                <td> Row 4- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 5- Col 1 </td>_x000D_
                <td> Row 5- Col 2 </td>_x000D_
                <td> Row 5- Col 3 </td>_x000D_
                <td> Row 5- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 6- Col 1 </td>_x000D_
                <td> Row 6- Col 2 </td>_x000D_
                <td> Row 6- Col 3 </td>_x000D_
                <td> Row 6- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 7- Col 1 </td>_x000D_
                <td> Row 7- Col 2 </td>_x000D_
                <td> Row 7- Col 3 </td>_x000D_
                <td> Row 7- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 8- Col 1 </td>_x000D_
                <td> Row 8- Col 2 </td>_x000D_
                <td> Row 8- Col 3 </td>_x000D_
                <td> Row 8- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 9- Col 1 </td>_x000D_
                <td> Row 9- Col 2 </td>_x000D_
                <td> Row 9- Col 3 </td>_x000D_
                <td> Row 9- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 10- Col 1 </td>_x000D_
                <td> Row 10- Col 2 </td>_x000D_
                <td> Row 10- Col 3 </td>_x000D_
                <td> Row 10- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 11- Col 1 </td>_x000D_
                <td> Row 11- Col 2 </td>_x000D_
                <td> Row 11- Col 3 </td>_x000D_
                <td> Row 11- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 12- Col 1 </td>_x000D_
                <td> Row 12- Col 2 </td>_x000D_
                <td> Row 12- Col 3 </td>_x000D_
                <td> Row 12- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 13- Col 1 </td>_x000D_
                <td> Row 13- Col 2 </td>_x000D_
                <td> Row 13- Col 3 </td>_x000D_
                <td> Row 13- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 14- Col 1 </td>_x000D_
                <td> Row 14- Col 2 </td>_x000D_
                <td> Row 14- Col 3 </td>_x000D_
                <td> Row 14- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 15- Col 1 </td>_x000D_
                <td> Row 15- Col 2 </td>_x000D_
                <td> Row 15- Col 3 </td>_x000D_
                <td> Row 15- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 16- Col 1 </td>_x000D_
                <td> Row 16- Col 2 </td>_x000D_
                <td> Row 16- Col 3 </td>_x000D_
                <td> Row 16- Col 4 </td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
_x000D_
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js"></script>_x000D_
    <script>_x000D_
        $('.example-table tbody').slimscroll({_x000D_
            height: '160px',_x000D_
            alwaysVisible: true,_x000D_
            color: '#333'_x000D_
        })_x000D_
    </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

If you already have "bash", "powershell" and "cmd" CLI's and have correct path settings then switching from one CLI to another can done by the following ways.

Ctrl + ' : Opens the terminal window with default CLI.

bash + enter : Switch from your default/current CLI to bash CLI.

powershell + enter : Switch from your default/current CLI to powershell CLI.

cmd + enter : Switch from your default/current CLI to cmd CLI.

VS Code Version I'm using is 1.45.0

Set up a scheduled job?

I personally use cron, but the Jobs Scheduling parts of django-extensions looks interesting.

SQL Server : Transpose rows to columns

Based on the solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
--        table and FIeldToTranspose should be written using single quotes
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

Throwing exceptions from constructors

Apart from the fact that you do not need to throw from the constructor in your specific case because pthread_mutex_lock actually returns an EINVAL if your mutex has not been initialized and you can throw after the call to lock as is done in std::mutex:

void
lock()
{
  int __e = __gthread_mutex_lock(&_M_mutex);

  // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
  if (__e)
__throw_system_error(__e);
}

then in general throwing from constructors is ok for acquisition errors during construction, and in compliance with RAII ( Resource-acquisition-is-Initialization ) programming paradigm.

Check this example on RAII

void write_to_file (const std::string & message) {
    // mutex to protect file access (shared across threads)
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    // scope (regardless of exception)
}

Focus on these statements:

  1. static std::mutex mutex
  2. std::lock_guard<std::mutex> lock(mutex);
  3. std::ofstream file("example.txt");

The first statement is RAII and noexcept. In (2) it is clear that RAII is applied on lock_guard and it actually can throw , whereas in (3) ofstream seems not to be RAII , since the objects state has to be checked by calling is_open() that checks the failbit flag.

At first glance it seems that it is undecided on what it the standard way and in the first case std::mutex does not throw in initialization , *in contrast to OP implementation * . In the second case it will throw whatever is thrown from std::mutex::lock, and in the third there is no throw at all.

Notice the differences:

(1) Can be declared static, and will actually be declared as a member variable (2) Will never actually be expected to be declared as a member variable (3) Is expected to be declared as a member variable, and the underlying resource may not always be available.

All these forms are RAII; to resolve this, one must analyse RAII.

  • Resource : your object
  • Acquisition ( allocation ) : you object being created
  • Initialization : your object is in its invariant state

This does not require you to initialize and connect everything on construction. For example when you would create a network client object you would not actually connect it to the server upon creation, since it is a slow operation with failures. You would instead write a connect function to do just that. On the other hand you could create the buffers or just set its state.

Therefore, your issue boils down to defining your initial state. If in your case your initial state is mutex must be initialized then you should throw from the constructor. In contrast it is just fine not to initialize then ( as is done in std::mutex ), and define your invariant state as mutex is created . At any rate the invariant is not compromized necessarily by the state of its member object, since the mutex_ object mutates between locked and unlocked through the Mutex public methods Mutex::lock() and Mutex::unlock().

class Mutex {
private:
  int e;
  pthread_mutex_t mutex_;

public:
  Mutex(): e(0) {
  e = pthread_mutex_init(&mutex_);
  }

  void lock() {

    e = pthread_mutex_lock(&mutex_);
    if( e == EINVAL ) 
    { 
      throw MutexInitException();
    }
    else (e ) {
      throw MutexLockException();
    }
  }

  // ... the rest of your class
};

Full width image with fixed height

Set the height of the parent element, and give that the width. Then use a background image with the rule "background-size: cover"

    .parent {
       background-image: url(../img/team/bgteam.jpg);
       background-repeat: no-repeat;
       background-position: center center;
       -webkit-background-size: cover;
       background-size: cover;
    }

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

What is the difference between bool and Boolean types in C#

They are the same, Bool is just System.Boolean shortened. Use Boolean when you are with a VB.net programmer, since it works with both C# and Vb

Hash function that produces short hashes?

If you don't need an algorithm that's strong against intentional modification, I've found an algorithm called adler32 that produces pretty short (~8 character) results. Choose it from the dropdown here to try it out:

http://www.sha1-online.com/

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

Pylint "unresolved import" error in Visual Studio Code

This issue has already been opened on GitHub:

Python unresolved import issue #3840

There are two very useful answers, by MagnuesBrzenk and SpenHouet.

The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:

PYTHONPATH=YOUR/MODULES/PATH

And in your settings.json add:

"python.envFile": ".env"

Adding a new line/break tag in XML

The easiest way to give a line break is to do the following :
1> Add the following in CSS - e{display:block}
2> Now wherever you want to give a line break, type -

<e></e>

inherit from two classes in C#

Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.

The basic idea is to define an interface for the members on class B that you wish to access (call it IB), and then have C inherit from A and implement IB by internally storing an instance of B, for example:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

There are also a couple of other alternaitve patterns explained on that page.

Use of contains in Java ArrayList<String>

Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.

EDIT: Initialize your ArrayList<String> then attempt to add an item.

Get the key corresponding to the minimum value within a dictionary

Is this what you are looking for?

d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'

print d[min(d.keys())]

Prints 'fourteen'

When to use extern in C++

This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.

header:

#ifndef HEADER_H
#define HEADER_H

// any source file that includes this will be able to use "global_x"
extern int global_x;

void print_global_x();

#endif

source 1:

#include "header.h"

// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;

int main()
{
    //set global_x here:
    global_x = 5;

    print_global_x();
}

source 2:

#include <iostream>
#include "header.h"

void print_global_x()
{
    //print global_x here:
    std::cout << global_x << std::endl;
}

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

How do I pretty-print existing JSON data with Java?

Underscore-java library has methods U.formatJson(json) and U.formatXml(xml). I am the maintainer of the project.

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

These are the installation i had to run in order to make it work on fedora 22 :-

glibc-2.21-7.fc22.i686

alsa-lib-1.0.29-1.fc22.i686

qt3-3.3.8b-64.fc22.i686

libusb-1:0.1.5-5.fc22.i686

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

How to pass parameters in GET requests with jQuery

Here is the syntax using jQuery $.get

$.get(url, data, successCallback, datatype)

So in your case, that would equate to,

var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';

function success(response) {
// do something here 
}

$.get('ajax.aspx', data, success, datatype)

Note $.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below

$.get(url, data, success, datatype)
 .fail(function(){
})

The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.

If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility

Python and pip, list all versions of a package that's available?

I didn't have any luck with yolk, yolk3k or pip install -v but so I ended up using this (adapted to Python 3 from eric chiang's answer):

import json
import requests
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/{}/json".format(package_name)
    data = requests.get(url).json()
    return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)

>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...

convert an enum to another type of enum

Based on Justin's answer above I came up with this:

    /// <summary>
    /// Converts Enum Value to different Enum Value (by Value Name) See https://stackoverflow.com/a/31993512/6500501.
    /// </summary>
    /// <typeparam name="TEnum">The type of the enum to convert to.</typeparam>
    /// <param name="source">The source enum to convert from.</param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public static TEnum ConvertTo<TEnum>(this Enum source)
    {
        try
        {
            return (TEnum) Enum.Parse(typeof(TEnum), source.ToString(), ignoreCase: true);
        }
        catch (ArgumentException aex)
        {
            throw new InvalidOperationException
            (
                $"Could not convert {source.GetType().ToString()} [{source.ToString()}] to {typeof(TEnum).ToString()}", aex
            );
        }
    }

Is there a way to @Autowire a bean that requires constructor arguments?

You can also configure your component like this :

package mypackage;
import org.springframework.context.annotation.Configuration;
   @Configuration
   public class MyConstructorClassConfig {


   @Bean
   public MyConstructorClass myConstructorClass(){
      return new myConstructorClass("foobar");
   }
  }
}

With the Bean annotation, you are telling Spring to register the returned bean in the BeanFactory.

So you can autowire it as you wish.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

When you run the command git checkout commit_id then HEAD detached from 13ca5593d(say commit-id) and branch will be on longer available.

Move back to previous location run the command step wise -

  1. git pull origin branch_name (say master)
  2. git checkout branch_name
  3. git pull origin branch_name

You will be back to the previous location with an updated commit from the remote repository.

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

VBoxManage: error: Failed to create the host-only adapter

If you are on Linux:

sudo service virtualbox restart

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

How To Set Up GUI On Amazon EC2 Ubuntu server

1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:

sudo apt-get update    sudo apt-get upgrade

5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.

sudo vim /etc/ssh/sshd_config

6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.

sudo /etc/init.d/ssh restart

8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.

sudo –i
passwd ubuntu

9) Switch back to the ubuntu user account and cd to the ubuntu home directory.

su ubuntu
cd

10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop

11) Install xrdp

sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies

12) Make xfce4 the default window manager for RDP connections.

echo xfce4-session > ~/.xsession

13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.

sudo cp /home/ubuntu/.xsession /etc/skel

14) Open the xrdp.ini file to allow changing of the host port you will connect to.

sudo vim /etc/xrdp/xrdp.ini

(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)

15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).

port=-1
- to -
port=ask-1

16) Restart xrdp.

sudo service xrdp restart

17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.

18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.

19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.

See more details: https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

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

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

Linq style "For Each"

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

There is no extension method in the BCL that implements ForEach directly.


Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.

How do you get centered content using Twitter Bootstrap?

My preferred method for centering blocks of information while maintaining responsiveness (mobile compatibility) is to place two empty span1 divs before and after the content you wish to center.

<div class="row-fluid">

    <div class="span1">
    </div>

        <div class="span10">
          <div class="hero-unit">
            <h1>Reading Resources</h1>
            <p>Read here...</p>
          </div>
        </div><!--/span-->

    <div class="span1">
    </div>

</div><!--/row-->

Make scrollbars only visible when a Div is hovered over?

Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover

#div { 
     overflow:hidden;
     height:whatever px; 
}
#div:hover { 
     overflow-y:scroll; 
     margin-right: -15px; // adjust according to scrollbar width  
}

Easiest way to loop through a filtered list with VBA?

a = 2
x = 0

Do Until Cells(a, 1).Value = ""
If Rows(a).Hidden = False Then
x = Cells(a, 1).Value + x
End If
a = a + 1
Loop

End Sub

Converting ArrayList to Array in java

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

for(String str : dsf){
   System.out.println(str);
}

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

How to validate numeric values which may contain dots or commas?

\d{1,2}[,.]\d{1,2}

\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.

How to identify and switch to the frame in selenium webdriver when frame does not have id

I struggled with this for a while; a particularly frustrating website had several nested frames throughout the site. I couldn't find any way to identify the frames- no name, id, xpath, css selector- nothing.

Eventually I realised that frames are numbered with the top level being frame(0) the second frame(1) etc.

As I still didn't know which frame the element I needed was sitting in, I wrote a for loop to start from 0 and cycle to 50 continually moving to the next frame and attempting to access my required element; if it failed I got it to print a message and continue.

Spent too much time on this problem for such a simple solution -_-

driver.switch_to.default_content()
for x in range(50):
    try:
        driver.switch_to.frame(x)
        driver.find_element_by_xpath("//*[@id='23']").click()
        driver.find_element_by_xpath("/html/body/form/table/tbody/tr[1]/td/ul/li[49]/a").click()
    except:
        print("It's not: ", x)
        continue

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I've solved the problem , and I will explain how :

  1. Download Github For Windows client and install it.
  2. After The client successfully installed , connect it with your github account.It should be easy , just follow the wizard.
  3. Then you should add git.exe location to your "Path Variable". The location you should add will probably be something like : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin

Alternatively , if you don't want to add to environment variables. You can open the android studio and go to : Settings -> Version Control -> Git In text box next to "Path to Git Executable" you will see "git.exe" , just give it a full path like so : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin\git.exe

Hope it saved your time . Happy coding :)

EDIT : For latest Github for windows versions some can find the git.exe under "...\cmd\git.exe" rather than "...\bin\git.exe".

Access properties file programmatically with Spring?

You can get your properties through Environment class. As documentation stands:

Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.

Having Environment as a env variable, simply call:

env.resolvePlaceholders("${your-property:default-value}")

You can get your 'raw' properties through:

env.getProperty("your-property")

It will search through all properties source that spring has registered.

You can either obtain Environment through:

  • inject ApplicationContext by implementing ApplicationContextAware and then call getEnvironment() on context
  • implement EnvironmentAware.

It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.

Read more on documentation: spring Environment documentation

How to allow users to check for the latest app version from inside the app?

There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:

http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp

Error:(23, 17) Failed to resolve: junit:junit:4.12

I couldn't work out why Android Studio was not syncing with gradle. It turned out that it didn't like my VPN, so watch for that!

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

just open the hive terminal from the hive folder,after editing (bashrc) and (hive-site.xml) files. Steps-- open hive folder where it is installed. now open terminal from folder.

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The clear() method removes all the elements of a single ArrayList. It's a fast operation, as it just sets the array elements to null.

The removeAll(Collection) method, which is inherited from AbstractCollection, removes all the elements that are in the argument collection from the collection you call the method on. It's a relatively slow operation, as it has to search through one of the collections involved.

Valid characters of a hostname?

Checkout this wiki, specifically the section Restrictions on valid host names

Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

PostgreSQL: export resulting data from SQL query to Excel/CSV

In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:

COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;

Note: The folder must be writable.

What is the difference between '@' and '=' in directive scope in AngularJS?

If you would like to see more how this work with a live example. http://jsfiddle.net/juanmendez/k6chmnch/

var app = angular.module('app', []);
app.controller("myController", function ($scope) {
    $scope.title = "binding";
});
app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclude: true,
        scope: {
            title1: "=",
            title2: "@"
        },
        template: "<div><p>{{title1}} {{title2}}</p></div>"
    };
});

What is Options +FollowSymLinks?

Parameter Options FollowSymLinks enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch can be used instead - this will allow you to link only to other files which you do own.

If you use Options directive in .htaccess with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.

Allowed .htaccess options are defined by directive AllowOverride in the main Apache config file. To allow symlinks, this directive need to be set to All or Options.

Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess context. But for this, also the more secure SymLinksIfOwnerMatch option can be used.

How can strip whitespaces in PHP's variable?

A regular expression does not account for UTF-8 characters by default. The \s meta-character only accounts for the original latin set. Therefore, the following command only removes tabs, spaces, carriage returns and new lines

// http://stackoverflow.com/a/1279798/54964
$str=preg_replace('/\s+/', '', $str);

With UTF-8 becoming mainstream this expression will more frequently fail/halt when it reaches the new utf-8 characters, leaving white spaces behind that the \s cannot account for.

To deal with the new types of white spaces introduced in unicode/utf-8, a more extensive string is required to match and removed modern white space.

Because regular expressions by default do not recognize multi-byte characters, only a delimited meta string can be used to identify them, to prevent the byte segments from being alters in other utf-8 characters (\x80 in the quad set could replace all \x80 sub-bytes in smart quotes)

$cleanedstr = preg_replace(
    "/(\t|\n|\v|\f|\r| |\xC2\x85|\xc2\xa0|\xe1\xa0\x8e|\xe2\x80[\x80-\x8D]|\xe2\x80\xa8|\xe2\x80\xa9|\xe2\x80\xaF|\xe2\x81\x9f|\xe2\x81\xa0|\xe3\x80\x80|\xef\xbb\xbf)+/",
    "_",
    $str
);

This accounts for and removes tabs, newlines, vertical tabs, formfeeds, carriage returns, spaces, and additionally from here:

nextline, non-breaking spaces, mongolian vowel separator, [en quad, em quad, en space, em space, three-per-em space, four-per-em space, six-per-em space, figure space, punctuation space, thin space, hair space, zero width space, zero width non-joiner, zero width joiner], line separator, paragraph separator, narrow no-break space, medium mathematical space, word joiner, ideographical space, and the zero width non-breaking space.

Many of these wreak havoc in xml files when exported from automated tools or sites which foul up text searches, recognition, and can be pasted invisibly into PHP source code which causes the parser to jump to next command (paragraph and line separators) which causes lines of code to be skipped resulting in intermittent, unexplained errors that we have begun referring to as "textually transmitted diseases"

[Its not safe to copy and paste from the web anymore. Use a character scanner to protect your code. lol]

HTTP Error 404 when running Tomcat from Eclipse

I had this or a similar problem after installing Tomcat.

The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.