Programs & Examples On #Vc90

What is the difference between compare() and compareTo()?

There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable or Comparator for a method like this:

class Pokemon {
    int healthPoints;
    int attackDamage;
    public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
        if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
            System.out.println("battle won");
        } else {
            System.out.println("battle lost");
        }
    }
}

comparable would a lambda or an object, and there is no way for comparable to access the fields of this Pokemon. (In a lambda, this refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator with two arguments.

Including dependencies in a jar with Maven

If you want to do an executable jar file, them need set the main class too. So the full configuration should be.

    <plugins>
            <plugin>
                 <artifactId>maven-assembly-plugin</artifactId>
                 <executions>
                     <execution>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
                  <configuration>
                       <!-- ... -->
                       <archive>
                           <manifest>
                                 <mainClass>fully.qualified.MainClass</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                 </configuration>
         </plugin>
   </plugins>

Compiling a java program into an executable

You can convert .jar file to .exe on these ways:
alt text
(source: viralpatel.net)

1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.

JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!

Download: http://jsmooth.sourceforge.net/

2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe in their website:

  • Can generate “Console”, “Windows GUI”, “Windows Service” three types of exe files.
  • Generated exe files can add program icons and version information.
  • Generated exe files can encrypt and protect java programs, no temporary files will be generated when program runs.
  • Generated exe files provide system tray icon support.
  • Generated exe files provide record system event log support.
  • Generated windows service exe files are able to install/uninstall itself, and support service pause/continue.
  • New release of x64 version, can create 64 bits executives. (May 18, 2008)
  • Both wizard mode and command line mode supported. (May 18, 2008)

Download: http://www.brothersoft.com/jartoexe-75019.html

3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.

Download: http://mpowers.net/executor/

EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/

4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/ Let me know other tools that you have used to convert JAR to EXE.

Generating UML from C++ code?

I find that Wikipedia can be a great source of information about such tools, especially for comparison tables. There's a page on UML tools. See in particular the reverse engineered languages column.

How to add a where clause in a MySQL Insert statement?

UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

Signing a Windows EXE file

The ASP's magazine ASPects has a detailed description on how to sign code (You have to be a member to read the article). You can download it through http://www.asp-shareware.org/

Here's link to a description how you can make your own test certificate.

This might also be interesting.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

How to do something before on submit?

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

Fixing a systemd service 203/EXEC failure (no such file or directory)

To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.

#!/bin/bash

python -u alwayson.py    

How to call a Parent Class's method from Child Class in Python?

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

PHP: Split string

to explode with '.' use

explode('\\.','a.b');

C/C++ check if one bit is set in, i.e. int variable

There is, namely the _bittest intrinsic instruction.

Differences between "java -cp" and "java -jar"?

I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.

I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.

Disable sorting on last column when using jQuery DataTables

for disable sorting on any column in datatable use the following

aoColumnDefs: [{ "aTargets": [ 0 ], "bSortable": false}],

it means "aTargets": [ 0 ] is the column id starting from 0

so in your case it becomes:

 $(".tableSort").dataTable({
        aaSorting: [[0, 'asc']],
        aoColumnDefs: [
            { "aTargets": [ -1 ], "bSortable": false},
        ]
    });

"FATAL: Module not found error" using modprobe

The reason is that modprobe looks into /lib/modules/$(uname -r) for the modules and therefore won't work with local file path. That's one of differences between modprobe and insmod.

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

Convert serial.read() into a useable string using Arduino?

Here is a more robust implementation that handles abnormal input and race conditions.

  • It detects unusually long input values and safely discards them. For example, if the source had an error and generated input without the expected terminator; or was malicious.
  • It ensures the string value is always null terminated (even when buffer size is completely filled).
  • It waits until the complete value is captured. For example, transmission delays could cause Serial.available() to return zero before the rest of the value finishes arriving.
  • Does not skip values when multiple values arrive quicker than they can be processed (subject to the limitations of the serial input buffer).
  • Can handle values that are a prefix of another value (e.g. "abc" and "abcd" can both be read in).

It deliberately uses character arrays instead of the String type, to be more efficient and to avoid memory problems. It also avoids using the readStringUntil() function, to not timeout before the input arrives.

The original question did not say how the variable length strings are defined, but I'll assume they are terminated by a single newline character - which turns this into a line reading problem.

int read_line(char* buffer, int bufsize)
{
  for (int index = 0; index < bufsize; index++) {
    // Wait until characters are available
    while (Serial.available() == 0) {
    }

    char ch = Serial.read(); // read next character
    Serial.print(ch); // echo it back: useful with the serial monitor (optional)

    if (ch == '\n') {
      buffer[index] = 0; // end of line reached: null terminate string
      return index; // success: return length of string (zero if string is empty)
    }

    buffer[index] = ch; // Append character to buffer
  }

  // Reached end of buffer, but have not seen the end-of-line yet.
  // Discard the rest of the line (safer than returning a partial line).

  char ch;
  do {
    // Wait until characters are available
    while (Serial.available() == 0) {
    }
    ch = Serial.read(); // read next character (and discard it)
    Serial.print(ch); // echo it back
  } while (ch != '\n');

  buffer[0] = 0; // set buffer to empty string even though it should not be used
  return -1; // error: return negative one to indicate the input was too long
}

Here is an example of it being used to read commands from the serial monitor:

const int LED_PIN = 13;
const int LINE_BUFFER_SIZE = 80; // max line length is one less than this

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.print("> ");

  // Read command

  char line[LINE_BUFFER_SIZE];
  if (read_line(line, sizeof(line)) < 0) {
    Serial.println("Error: line too long");
    return; // skip command processing and try again on next iteration of loop
  }

  // Process command

  if (strcmp(line, "off") == 0) {
      digitalWrite(LED_PIN, LOW);
  } else if (strcmp(line, "on") == 0) {
      digitalWrite(LED_PIN, HIGH);
  } else if (strcmp(line, "") == 0) {
    // Empty line: no command
  } else {
    Serial.print("Error: unknown command: \"");
    Serial.print(line);
    Serial.println("\" (available commands: \"off\", \"on\")");
  }
}

jQuery validate: How to add a rule for regular expression validation?

You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use

_x000D_
_x000D_
$("#frm").validate({_x000D_
    rules: {_x000D_
        Textbox: {_x000D_
            pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
        },_x000D_
    },_x000D_
    messages: {_x000D_
        Textbox: {_x000D_
            pattern: 'The Textbox string format is invalid'_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>_x000D_
<form id="frm" method="get" action="">_x000D_
    <fieldset>_x000D_
        <p>_x000D_
            <label for="fullname">Textbox</label>_x000D_
            <input id="Textbox" name="Textbox" type="text">_x000D_
        </p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Get changes from master into branch in Git

For me, I had changes already in place and I wanted the latest from the base branch. I was unable to do rebase, and cherry-pick would have taken forever, so I did the following:

git fetch origin <base branch name>  
git merge FETCH_HEAD

so in this case:

git fetch origin master  
git merge FETCH_HEAD

Compute elapsed time

write java program that enter elapsed time in seconds for any cycling event & the output format should be like (hour : minute : seconds ) for EX : elapsed time in 4150 seconds= 1:09:10

@RequestParam vs @PathVariable

Both the annotations behave exactly in same manner.

Only 2 special characters '!' and '@' are accepted by the annotations @PathVariable and @RequestParam.

To check and confirm the behavior I have created a spring boot application that contains only 1 controller.

 @RestController 
public class Controller 
{
    @GetMapping("/pvar/{pdata}")
    public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
    {
        return pathdata;
    }

    @GetMapping("/rpvar")
    public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
    {
        return paramdata;
    }
}

Hitting following Requests I got the same response:

  1. localhost:7000/pvar/!@#$%^&*()_+-=[]{}|;':",./<>?
  2. localhost:7000/rpvar?param=!@#$%^&*()_+-=[]{}|;':",./<>?

!@ was received as response in both the requests

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

How to interactively (visually) resolve conflicts in SourceTree / git

I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.

If you'd like to use it as well, then:

  1. Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.

  2. Unzip TortoiseIDiff.exe and TortoiseMerge.exe to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\ in my case).

  3. In SourceTree open Tools > Options > Diff > External Diff / Merge. Select TortoiseMerge in both dropdown lists.

  4. Hit OK and point SourceTree to your location of TortoiseIDiff.exe and TortoiseMerge.exe.

After that, you can select Resolve Conflicts > Launch External Merge Tool from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.

The only problem is, that it automatically creates backup copy, even though proper option is unchecked.

How to write a large buffer into a binary file in C++, fast?

fstreams are not slower than C streams, per se, but they use more CPU (especially if buffering is not properly configured). When a CPU saturates, it limits the I/O rate.

At least the MSVC 2015 implementation copies 1 char at a time to the output buffer when a stream buffer is not set (see streambuf::xsputn). So make sure to set a stream buffer (>0).

I can get a write speed of 1500MB/s (the full speed of my M.2 SSD) with fstream using this code:

#include <iostream>
#include <fstream>
#include <chrono>
#include <memory>
#include <stdio.h>
#ifdef __linux__
#include <unistd.h>
#endif
using namespace std;
using namespace std::chrono;
const size_t sz = 512 * 1024 * 1024;
const int numiter = 20;
const size_t bufsize = 1024 * 1024;
int main(int argc, char**argv)
{
  unique_ptr<char[]> data(new char[sz]);
  unique_ptr<char[]> buf(new char[bufsize]);
  for (size_t p = 0; p < sz; p += 16) {
    memcpy(&data[p], "BINARY.DATA.....", 16);
  }
  unlink("file.binary");
  int64_t total = 0;
  if (argc < 2 || strcmp(argv[1], "fopen") != 0) {
    cout << "fstream mode\n";
    ofstream myfile("file.binary", ios::out | ios::binary);
    if (!myfile) {
      cerr << "open failed\n"; return 1;
    }
    myfile.rdbuf()->pubsetbuf(buf.get(), bufsize); // IMPORTANT
    for (int i = 0; i < numiter; ++i) {
      auto tm1 = high_resolution_clock::now();
      myfile.write(data.get(), sz);
      if (!myfile)
        cerr << "write failed\n";
      auto tm = (duration_cast<milliseconds>(high_resolution_clock::now() - tm1).count());
      cout << tm << " ms\n";
      total += tm;
    }
    myfile.close();
  }
  else {
    cout << "fopen mode\n";
    FILE* pFile = fopen("file.binary", "wb");
    if (!pFile) {
      cerr << "open failed\n"; return 1;
    }
    setvbuf(pFile, buf.get(), _IOFBF, bufsize); // NOT important
    auto tm1 = high_resolution_clock::now();
    for (int i = 0; i < numiter; ++i) {
      auto tm1 = high_resolution_clock::now();
      if (fwrite(data.get(), sz, 1, pFile) != 1)
        cerr << "write failed\n";
      auto tm = (duration_cast<milliseconds>(high_resolution_clock::now() - tm1).count());
      cout << tm << " ms\n";
      total += tm;
    }
    fclose(pFile);
    auto tm2 = high_resolution_clock::now();
  }
  cout << "Total: " << total << " ms, " << (sz*numiter * 1000 / (1024.0 * 1024 * total)) << " MB/s\n";
}

I tried this code on other platforms (Ubuntu, FreeBSD) and noticed no I/O rate differences, but a CPU usage difference of about 8:1 (fstream used 8 times more CPU). So one can imagine, had I a faster disk, the fstream write would slow down sooner than the stdio version.

Killing a process using Java

On Windows, you could use this command.

taskkill /F /IM <processname>.exe 

To kill it forcefully, you may use;

Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

Better way to find last used row

How is this?

dim rownum as integer
dim colnum as integer
dim lstrow as integer
dim lstcol as integer
dim r as range

'finds the last row

lastrow = ActiveSheet.UsedRange.Rows.Count

'finds the last column

lastcol = ActiveSheet.UsedRange.Columns.Count

'sets the range

set r = range(cells(rownum,colnum), cells(lstrow,lstcol))

Change link color of the current page with CSS

Use single class name something like class="active" and add it only to current page instead of all pages. If you are at Home something like below:

<ul id="navigation">
<li class="active"><a href="/">Home</a></li>
<li class=""><a href="theatre.php">Theatre</a></li>
<li class=""><a href="programming.php">Programming</a></li> 
</ul>

and your CSS like

li.active{
color: #640200;
}

How do I tell if an object is a Promise?

Not an answer to the full question but I think it's worth to mention that in Node.js 10 a new util function called isPromise was added which checks if an object is a native Promise or not:

const utilTypes = require('util').types
const b_Promise = require('bluebird')

utilTypes.isPromise(Promise.resolve(5)) // true
utilTypes.isPromise(b_Promise.resolve(5)) // false

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Column/Vertical selection with Keyboard in SublimeText 3

In my case (Linux) is alt+shift up/down

 { "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
 { "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },    

Setting the zoom level for a MKMapView

For Swift 3 it's pretty fast forward:

private func setMapRegion(for location: CLLocationCoordinate2D, animated: Bool)
{
    let viewRegion = MKCoordinateRegionMakeWithDistance(location, <#T##latitudinalMeters: CLLocationDistance##CLLocationDistance#>, <#T##longitudinalMeters: CLLocationDistance##CLLocationDistance#>)
    MapView.setRegion(viewRegion, animated: animated)
}

Just define the lat-, long-Meters <CLLocationDistance> and the mapView will fit the zoom level to your values.

plot different color for different categorical levels using matplotlib

You can pass plt.scatter a c argument which will allow you to select the colors. The code below defines a colors dictionary to map your diamond colors to the plotting colors.

import matplotlib.pyplot as plt
import pandas as pd

carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]

df = pd.DataFrame(dict(carat=carat, price=price, color=color))

fig, ax = plt.subplots()

colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}

ax.scatter(df['carat'], df['price'], c=df['color'].apply(lambda x: colors[x]))

plt.show()

df['color'].apply(lambda x: colors[x]) effectively maps the colours from "diamond" to "plotting".

(Forgive me for not putting another example image up, I think 2 is enough :P)

With seaborn

You can use seaborn which is a wrapper around matplotlib that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.

For this you could use seaborn.lmplot with fit_reg=False (which prevents it from automatically doing some regression).

The code below uses an example dataset. By selecting hue='color' you tell seaborn to split your dataframe up based on your colours and then plot each one.

import matplotlib.pyplot as plt
import seaborn as sns

import pandas as pd

carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]

df = pd.DataFrame(dict(carat=carat, price=price, color=color))

sns.lmplot('carat', 'price', data=df, hue='color', fit_reg=False)

plt.show()

enter image description here

Without seaborn using pandas.groupby

If you don't want to use seaborn then you can use pandas.groupby to get the colors alone and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:

fig, ax = plt.subplots()

colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}

grouped = df.groupby('color')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])

plt.show()

This code assumes the same DataFrame as above and then groups it based on color. It then iterates over these groups, plotting for each one. To select a color I've created a colors dictionary which can map the diamond color (for instance D) to a real color (for instance red).

enter image description here

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

How can I enable the Windows Server Task Scheduler History recording?

Step 1: Open an elevated Task Scheduler (ie. right-click on the Task Scheduler icon and choose Run as administrator)

Step 2: In the Actions pane (right pane, not the actions tab), click Enable All Tasks History

That's it. Not sure why this isn't on by default, but it isn't.

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

Please initialize the log4j system properly warning

Add the code

BasicConfigurator.configure();

in your static main class as below..

Note: add " \hadoop-2.7.1\share\hadoop\common\lib\commons-logging-1.1.3.jar & \hadoop-2.7.1\share\hadoop\common\lib\log4j-1.2.17.jar " as the external references

import org.apache.log4j.BasicConfigurator;

public class ViewCountDriver extends Configured implements Tool{

    public static void main(String[]args) throws Exception{

        BasicConfigurator.configure(); 

        int exitcode = ToolRunner.run(new ViewCountDriver(), args);
        System.exit(exitcode); 
    }
}

Java division by zero doesnt throw an ArithmeticException - why?

That's because you are dealing with floating point numbers. Division by zero returns Infinity, which is similar to NaN (not a number).

If you want to prevent this, you have to test tab[i] before using it. Then you can throw your own exception, if you really need it.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> x, z = dict(x), x.update(y) or x
>>> x
{'a': 1, 'b': 2}
>>> y
{'c': 11, 'b': 10}
>>> z
{'a': 1, 'c': 11, 'b': 10}

Mapping over values in a python dictionary

There is no such function; the easiest way to do this is to use a dict comprehension:

my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

As such, you could use the map() function for processing your dict as well:

my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))

but that's not that readable, really.

How do I force git pull to overwrite everything on every pull?

You could try this:

git reset --hard HEAD
git pull

(from How do I force "git pull" to overwrite local files?)

Another idea would be to delete the entire git and make a new clone.

Python: tf-idf-cosine: to find document similarity

This should help you.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity  

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine

and output will be:

[[ 0.34949812  0.81649658  1.        ]]

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

How do I commit only some files?

I think you may also use the command line :

git add -p

This allows you to review all your uncommited files, one by one and choose if you want to commit them or not.

Then you have some options that will come up for each modification: I use the "y" for "yes I want to add this file" and the "n" for "no, I will commit this one later".

Stage this hunk [y,n,q,a,d,K,g,/,e,?]?

As for the other options which are ( q,a,d,K,g,/,e,? ), I'm not sure what they do, but I guess the "?" might help you out if you need to go deeper into details.

The great thing about this is that you can then push your work, and create a new branch after and all the uncommited work will follow you on that new branch. Very useful if you have coded many different things and that you actually want to reorganise your work on github before pushing it.

Hope this helps, I have not seen it said previously (if it was mentionned, my bad)

How can I get a file's size in C++?

If you have the file descriptor fstat() returns a stat structure which contain the file size.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

How to add a title to a html select tag

Typically, I would suggest that you use the <optgroup> option, as that gives some nice styling and indenting to the element.

The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>.

But, since an <optgroup> cannot be a selected value, you can make an <option selected disabled> and then stylize it with CSS so that it behaves like an <optgroup>....

_x000D_
_x000D_
.optionGroup {
    font-weight: bold;
    font-style: italic;
}
_x000D_
<select>
    <option class="optionGroup" selected disabled>Choose one</option>
    <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
    <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
    <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
    <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_

SLF4J: Class path contains multiple SLF4J bindings

Check mvn dependency:tree and see if there are multiple repos from where slf4j belongs to two different JARs.

If so, add exclusion in one of the dependencies:

<exclusions>
    <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
</exclusions>

Register 32 bit COM DLL to 64 bit Windows 7

To register a comm .dll or .ocx on Windows 7 32-bit, do the following:

Copy .dll or .ocx to c:\windows\system32 Type cmd in Run menu, it will search cmd.exe, right click and click Run as Administrator

It will show a prompt at c:\windows\system32

Type

regsvr32 ocxname.ocx to register .ocx

or

type regsvr32 dllname.dll to register .dll

Upload file to FTP using C#

I have observed that -

  1. FtpwebRequest is missing.
  2. As the target is FTP, so the NetworkCredential required.

I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :

private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
        {
            //Get the Image Destination path
            string imageName = TargetFileName; //you can comment this
            string imgPath = TargetDestinationPath; 

            string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
            string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
            string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
            string fileurl = FiletoUpload;

            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
            ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
            ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpClient.UseBinary = true;
            ftpClient.KeepAlive = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer = new byte[4097];
            int bytes = 0;
            int total_bytes = (int)fi.Length;
            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream rs = ftpClient.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            string value = uploadResponse.StatusDescription;
            uploadResponse.Close();
        }

Let me know in case of any issue, or here is one more link that can help you:

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

Set initial focus in an Android application

@Someone Somewhere I used this to clear focus:

editText.clearFocus();

and it helps

Checking if an input field is required using jQuery

$('form#register input[required]')

It will only return inputs which have required attribute.

How do I iterate over a range of numbers defined by variables in Bash?

I've combined a few of the ideas here and measured performance.

TL;DR Takeaways:

  1. seq and {..} are really fast
  2. for and while loops are slow
  3. $( ) is slow
  4. for (( ; ; )) loops are slower
  5. $(( )) is even slower
  6. Worrying about N numbers in memory (seq or {..}) is silly (at least up to 1 million.)

These are not conclusions. You would have to look at the C code behind each of these to draw conclusions. This is more about how we tend to use each of these mechanisms for looping over code. Most single operations are close enough to being the same speed that it's not going to matter in most cases. But a mechanism like for (( i=1; i<=1000000; i++ )) is many operations as you can visually see. It is also many more operations per loop than you get from for i in $(seq 1 1000000). And that may not be obvious to you, which is why doing tests like this is valuable.

Demos

# show that seq is fast
$ time (seq 1 1000000 | wc)
 1000000 1000000 6888894

real    0m0.227s
user    0m0.239s
sys     0m0.008s

# show that {..} is fast
$ time (echo {1..1000000} | wc)
       1 1000000 6888896

real    0m1.778s
user    0m1.735s
sys     0m0.072s

# Show that for loops (even with a : noop) are slow
$ time (for i in {1..1000000} ; do :; done | wc)
       0       0       0

real    0m3.642s
user    0m3.582s
sys 0m0.057s

# show that echo is slow
$ time (for i in {1..1000000} ; do echo $i; done | wc)
 1000000 1000000 6888896

real    0m7.480s
user    0m6.803s
sys     0m2.580s

$ time (for i in $(seq 1 1000000) ; do echo $i; done | wc)
 1000000 1000000 6888894

real    0m7.029s
user    0m6.335s
sys     0m2.666s

# show that C-style for loops are slower
$ time (for (( i=1; i<=1000000; i++ )) ; do echo $i; done | wc)
 1000000 1000000 6888896

real    0m12.391s
user    0m11.069s
sys     0m3.437s

# show that arithmetic expansion is even slower
$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; i=$(($i+1)); done | wc)
 1000000 1000000 6888896

real    0m19.696s
user    0m18.017s
sys     0m3.806s

$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; ((i=i+1)); done | wc)
 1000000 1000000 6888896

real    0m18.629s
user    0m16.843s
sys     0m3.936s

$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $((i++)); done | wc)
 1000000 1000000 6888896

real    0m17.012s
user    0m15.319s
sys     0m3.906s

# even a noop is slow
$ time (i=1; e=1000000; while [ $((i++)) -le $e ]; do :; done | wc)
       0       0       0

real    0m12.679s
user    0m11.658s
sys 0m1.004s

Java 8: Lambda-Streams, Filter by Method with Exception

You can also propagate your static pain with lambdas, so the whole thing looks readable:

s.filter(a -> propagate(a::isActive))

propagate here receives java.util.concurrent.Callable as a parameter and converts any exception caught during the call into RuntimeException. There is a similar conversion method Throwables#propagate(Throwable) in Guava.

This method seems being essential for lambda method chaining, so I hope one day it will be added to one of the popular libs or this propagating behavior would be by default.

public class PropagateExceptionsSample {
    // a simplified version of Throwables#propagate
    public static RuntimeException runtime(Throwable e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException)e;
        }

        return new RuntimeException(e);
    }

    // this is a new one, n/a in public libs
    // Callable just suits as a functional interface in JDK throwing Exception 
    public static <V> V propagate(Callable<V> callable){
        try {
            return callable.call();
        } catch (Exception e) {
            throw runtime(e);
        }
    }

    public static void main(String[] args) {
        class Account{
            String name;    
            Account(String name) { this.name = name;}

            public boolean isActive() throws IOException {
                return name.startsWith("a");
            }
        }


        List<Account> accounts = new ArrayList<>(Arrays.asList(new Account("andrey"), new Account("angela"), new Account("pamela")));

        Stream<Account> s = accounts.stream();

        s
          .filter(a -> propagate(a::isActive))
          .map(a -> a.name)
          .forEach(System.out::println);
    }
}

Corrupt jar file

This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main() method and have it referenced in MANIFEST.MF.

In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.

Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe, which won't work for those kind of libary JARs.

How to get a value of an element by name instead of ID

This works fine .. here btnAddCat is button id

$('#btnAddCat').click(function(){
        var eventCategory=$("input[name=txtCategory]").val();
        alert(eventCategory);
    });

How do you run a Python script as a service in Windows?

https://www.chrisumbel.com/article/windows_services_in_python

  1. Follow up the PySvc.py

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

React Native TextInput that only accepts numeric characters

I wrote this function which I found to be helpful to prevent the user from being able to enter anything other than I was willing to accept. I also used keyboardType="decimal-pad" and my onChangeText={this.decimalTextChange}

  decimalTextChange = (distance) =>
{
    let decimalRegEx = new RegExp(/^\d*\.?\d*$/)
    if (distance.length === 0 || distance === "." || distance[distance.length - 1] === "."
        && decimalRegEx.test(distance)
    ) {
        this.setState({ distance })
    } else {
        const distanceRegEx = new RegExp(/^\s*-?(\d+(\.\d{ 1, 2 })?|\.\d{ 1, 2 })\s*$/)
        if (distanceRegEx.test(distance)) this.setState({ distance })
    }
}

The first if block is error handling for the event the user deletes all of the text, or uses a decimal point as the first character, or if they attempt to put in more than one decimal place, the second if block makes sure they can type in as many numbers as they want before the decimal place, but only up to two decimal places after the point.

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

The proper syntax is (in example):

$query = mysql_query('SELECT * FROM beer ORDER BY quality');
while($row = mysql_fetch_assoc($query)) $results[] = $row;

How to list only the file names that changed between two commits?

Based on git diff --name-status I wrote the git-diffview git extension that renders a hierarchical tree view of what changed between two paths.

Python Finding Prime Factors

Isn't largest prime factor of 27 is 3 ?? The above code might be fastest,but it fails on 27 right ? 27 = 3*3*3 The above code returns 1 As far as I know.....1 is neither prime nor composite

I think, this is the better code

def prime_factors(n):
    factors=[]
    d=2
    while(d*d<=n):
        while(n>1):            
            while n%d==0:
                factors.append(d)
                n=n/d
            d+=1
    return factors[-1]

What's the difference between SCSS and Sass?

SCSS is the new syntax for Sass. In Extension wise, .sass for the SASS while .scss for the SCSS. Here SCSS has more logical and complex approach for coding than SASS. Therefore, for a newbie to software field the better choice is SCSS.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In simple words,

applicationContext.xml defines the beans that are shared among all the servlets. If your application have more than one servlet, then defining the common resources in the applicationContext.xml would make more sense.

spring-servlet.xml defines the beans that are related only to that servlet. Here it is the dispatcher servlet. So, your Spring MVC controllers must be defined in this file.

There is nothing wrong in defining all the beans in the spring-servlet.xml if you are running only one servlet in your web application.

Android: how to make an activity return results to the activity which calls it?

Your error is in resultCode = Activity.RESULT_CANCELED, you should instance like resultCode == Activity.RESULT_CANCELED ==

Count number of occurrences of a pattern in a file (even on same line)

A belated post:
Use the search regex pattern as a Record Separator (RS) in awk
This allows your regex to span \n-delimited lines (if you need it).

printf 'X \n moo X\n XX\n' | 
   awk -vRS='X[^X]*X' 'END{print (NR<2?0:NR-1)}'

Convert array into csv

My solution requires the array be formatted differently than provided in the question:

<?
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );
?>

We define our function:

<?
    function outputCSV($data) {
        $outputBuffer = fopen("php://output", 'w');
        foreach($data as $val) {
            fputcsv($outputBuffer, $val);
        }
        fclose($outputBuffer);
    }
?>

Then we output our data as a CSV:

<?
    $filename = "example";

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    outputCSV($data);
?>

I have used this with several projects, and it works well. I should note that the outputCSV code is more clever than I am, so I am sure I am not the original author. Unfortunately I have lost track of where I got it, so I can't give the credit to whom it is due.

How do I put a clear button inside my HTML text input box like the iPhone does?

@Mahmoud Ali Kaseem

I have just changed some CSS to make it look different and added focus();

https://jsfiddle.net/xn9eogmx/81/

_x000D_
_x000D_
$('#clear').click(function() {_x000D_
  $('#input-outer input').val('');_x000D_
  $('#input-outer input').focus();_x000D_
});
_x000D_
body {_x000D_
  font-family: "Arial";_x000D_
  font-size: 14px;_x000D_
}_x000D_
#input-outer {_x000D_
  height: 2em;_x000D_
  width: 15em;_x000D_
  border: 1px #777 solid;_x000D_
  position: relative;_x000D_
  padding: 0px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#input-outer input {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: 0px;_x000D_
  outline: none;_x000D_
  margin: 0 0 0 0px;_x000D_
  color: #666;_x000D_
  box-sizing: border-box;_x000D_
  padding: 5px;_x000D_
  padding-right: 35px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#clear {_x000D_
  position: absolute;_x000D_
  float: right;_x000D_
  height: 2em;_x000D_
  width: 2em;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  background: #aaa;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
  border-radius: 0px 4px 4px 0px;_x000D_
}_x000D_
#clear:after {_x000D_
  content: "\274c";_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  right: 7px;_x000D_
}_x000D_
#clear:hover,_x000D_
#clear:focus {_x000D_
  background: #888;_x000D_
}_x000D_
#clear:active {_x000D_
  background: #666;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
  <input type="text">_x000D_
  <div id="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

- java.lang.NullPointerException - setText on null object reference

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);
}

If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.

More reading on null pointers: What is a NullPointerException, and how do I fix it?

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

Rails Active Record find(:all, :order => ) issue

This might help too:

Post.order(created_at: :desc)

Wait for Angular 2 to load/resolve model before rendering view/template

Try {{model?.person.name}} this should wait for model to not be undefined and then render.

Angular 2 refers to this ?. syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:

The Elvis Operator ( ?. ) and null property paths

The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

The current hero's name is {{currentHero?.firstName}}

Let’s elaborate on the problem and this particular solution.

What happens when the following data bound title property is null?

The title is {{ title }}

The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.

Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.

The null hero's name is {{nullHero.firstName}}

JavaScript throws a null reference error and so does Angular:

TypeError: Cannot read property 'firstName' of null in [null]

Worse, the entire view disappears.

We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.

On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.

While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.

Unfortunately, our app crashes when the currentHero is null.

We could code around that problem with NgIf

<!--No hero, div not displayed, no error --> <div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>

Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.

The null hero's name is {{nullHero && nullHero.firstName}}

These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.

The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.

<!-- No hero, no problem! --> The null hero's name is {{nullHero?.firstName}}

It works perfectly with long property paths too:

a?.b?.c?.d

Push origin master error on new repository

It looks like this question has a number of answers already, but I'll weigh in with mine since I haven't seen any that address the issue I had.

I had this error as well on a brand new github repository. It turns out the user I was pushing from did not have push access. For some reason, this results in an "ERROR: repository not found" error instead of some sort of access error.

Anyway, I hope this helps the poor soul who runs into the same issue.

How can I change or remove HTML5 form validation default error messages?

HTML:

<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  />

JAVASCRIPT :

function InvalidMsg(textbox) {

     if(textbox.validity.patternMismatch){
        textbox.setCustomValidity('please enter 10 numeric value.');
    }    
    else {
        textbox.setCustomValidity('');
    }
    return true;
}

Fiddle Demo

Composer: Command Not Found

Your composer.phar command lacks the flag for executable, or it is not inside the path.

The first problem can be fixed with chmod +x composer.phar, the second by calling it as ./composer.phar -v.

You have to prefix executables that are not in the path with an explicit reference to the current path in Unix, in order to avoid going into a directory that has an executable file with an innocent name that looks like a regular command, but is not. Just think of a cat in the current directory that does not list files, but deletes them.

The alternative, and better, fix for the second problem would be to put the composer.phar file into a location that is mentioned in the path

Changing Underline color

You can wrap your <span> with a <a> and use this little JQuery plugin to color the underline. You can modify the color by passing a parameter to the plugin.

    (function ($) {
        $.fn.useful = function (params) {

            var aCSS = {
                'color' : '#d43',
                'text-decoration' : 'underline'
            };

            $.extend(aCSS, params);

            this.wrap('<a></a>');
            var element = this.closest('a');
            element.css(aCSS);
            return element;
        };
    })(jQuery);

Then you call by writing this :

    $("span.name").useful({color:'red'});

_x000D_
_x000D_
$(function () {_x000D_
_x000D_
        var spanCSS = {_x000D_
            'color' : '#000',_x000D_
            'text-decoration': 'none'_x000D_
        };_x000D_
        _x000D_
        $.fn.useful = function (params) {_x000D_
            _x000D_
            var aCSS = {_x000D_
                'color' : '#d43',_x000D_
                'text-decoration' : 'underline'_x000D_
            };_x000D_
_x000D_
            $.extend(aCSS, params);_x000D_
            this.wrap('<a></a>');_x000D_
            this.closest('a').css(aCSS);_x000D_
        };_x000D_
_x000D_
        // Use example:_x000D_
        $("span.name").css(spanCSS).useful({color:'red'});_x000D_
_x000D_
_x000D_
_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<section class="container">_x000D_
_x000D_
    <div class="user important">_x000D_
        <span class="name">Bob</span>_x000D_
        -_x000D_
        <span class="location">Bali</span>_x000D_
    </div>_x000D_
_x000D_
    <div class="user">_x000D_
        <span class="name">Dude</span>_x000D_
        -_x000D_
        <span class="location">Los Angeles</span>_x000D_
    </div>_x000D_
_x000D_
_x000D_
    <div class="user">_x000D_
        <span class="name">Gérard</span>_x000D_
        -_x000D_
        <span class="location">Paris</span>_x000D_
    </div>_x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_

How can I read comma separated values from a text file in Java?

//lat=3434&lon=yy38&rd=1.0&| in that format o/p is displaying

public class ReadText {
    public static void main(String[] args) throws Exception {
        FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(f));
        String strline;
        StringBuffer sb = new StringBuffer();
        while ((strline = br.readLine()) != null)
        {
            String[] arraylist=StringUtils.split(strline, ",");
            if(arraylist.length == 2){
                sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");

            } else {
                System.out.println("Error: "+strline);
            }
        }
        System.out.println("Data: "+sb.toString());
    }
}

Comparing date part only without comparing time in JavaScript

If you are truly comparing date only with no time component, another solution that may feel wrong but works and avoids all Date() time and timezone headaches is to compare the ISO string date directly using string comparison:

> "2019-04-22" <= "2019-04-23"
true
> "2019-04-22" <= "2019-04-22"
true
> "2019-04-22" <= "2019-04-21"
false
> "2019-04-22" === "2019-04-22"
true

You can get the current date (UTC date, not neccesarily the user's local date) using:

> new Date().toISOString().split("T")[0]
"2019-04-22"

My argument in favor of it is programmer simplicity -- you're much less likely to botch this than trying to handle datetimes and offsets correctly, probably at the cost of speed (I haven't compared performance)

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

Best practices for copying files with Maven

I've had very good experience with copy-maven-plugin. It has a much more convenient and concise syntax in comparison to maven-resources-plugin.

Remove/ truncate leading zeros by javascript/jquery

const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

Express.js req.body undefined

Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately

npm install body-parser --save

and then do this in your code

var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Linq where clause compare only date value without time value

Try this,

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
         && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x.DateTimeValueColumn)
    .AsEnumerable()
    .select(p=>p.DateTimeValueColumn.value.toString("YYYY-MMM-dd");

Is there any way to return HTML in a PHP function? (without building the return value as a string)

This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:

function noStrings() {
    echo ''?>
        <div>[Whatever HTML you want]</div>
    <?php;
}

The just 'call' the function:

noStrings();

And it will output:

<div>[Whatever HTML you want]</div>

Using this method, you can also define PHP variables within the function and echo them out inside the HTML.

How to parse XML using jQuery?

There is the $.parseXML function for this: http://api.jquery.com/jQuery.parseXML/

You can use it like this:

var xml = $.parseXML(yourfile.xml),
  $xml = $( xml ),
  $test = $xml.find('test');

console.log($test.text());

If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON: http://www.fyneworks.com/jquery/xml-to-json/

How to remove carriage return and newline from a variable in shell script

use this command on your script file after copying it to Linux/Unix

perl -pi -e 's/\r//' scriptfilename

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I had the same problem after the most recent VS 2017 update (released March 14, 2017: build 26228.09). My program would debug fine in IE but would bomb out in Chrome. Killing all instances of Chrome within the Windows command line fixed the problem for me.

taskkill /im chrome.exe /f

I was then able to debug in Chrome.

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

How can I easily view the contents of a datatable or dataview in the immediate window

The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.

To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.

enter image description here

How to use readline() method in Java?

A DataInputStream is just a decorator over an InputStream (which System.in is) which allows to read using more convenient methods.

As to the Float.valueOf(), well, that's curious because Float has .parseFloat() as well. Here the code grabs a Float with .valueOf() which it turns into the primitive float type using .floatValue(), which is unnecessary with Java 1.5+ due to auto unboxing.

And as other answers rightly say, these methods are obsolete anyway.

Apache HttpClient Interim Error: NoHttpResponseException

Same problem for me on apache http client 4.5.5 adding default header

Connection: close

resolve the problem

Launching Spring application Address already in use

Close the application, then restart it after changing to a new port:

${port:8181}

You can use any new unused port. Here, I used port 8181.

Can I change the fill color of an svg path with CSS?

You can use this syntax but it will require some changes in the SVG file. And remove any fill/stroke from the SVG itself.

icon.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<!-- use symbol instead of defs and g, 
  must add viewBox on symbol just copy yhe viewbox from the svg tag itself
  must add id on symbol
-->
<symbol id="location" viewBox="0 0 430.114 430.114">
  <!-- add all the icon's paths and shapes here -->
  <path d="M356.208,107.051c-1.531-5.738-4.64-11.852-6.94-17.205C321.746,23.704,261.611,0,213.055,0   C148.054,0,76.463,43.586,66.905,133.427v18.355c0,0.766,0.264,7.647,0.639,11.089c5.358,42.816,39.143,88.32,64.375,131.136   c27.146,45.873,55.314,90.999,83.221,136.106c17.208-29.436,34.354-59.259,51.17-87.933c4.583-8.415,9.903-16.825,14.491-24.857   c3.058-5.348,8.9-10.696,11.569-15.672c27.145-49.699,70.838-99.782,70.838-149.104v-20.262   C363.209,126.938,356.581,108.204,356.208,107.051z M214.245,199.193c-19.107,0-40.021-9.554-50.344-35.939   c-1.538-4.2-1.414-12.617-1.414-13.388v-11.852c0-33.636,28.56-48.932,53.406-48.932c30.588,0,54.245,24.472,54.245,55.06   C270.138,174.729,244.833,199.193,214.245,199.193z"/>
</symbol>

icon.html

<svg><use xlink:href="file_path/location.svg#location"></use></svg>

C# Set collection?

I use a wrapper around a Dictionary<T, object>, storing nulls in the values. This gives O(1) add, lookup and remove on the keys, and to all intents and purposes acts like a set.

How do I use select with date condition?

Another feature is between:

Select * from table where date between '2009/01/30' and '2009/03/30'

Does HTTP use UDP?

UDP is the best protocol for streaming, because it doesn't make demands for missing packages like TCP. And if it doesn't make demands, the flow is far more faster and without any buffering.

Even the stream delay is lesser than TCP. That is because TCP (as a far more secure protocol) makes demands for missing packages, overwriting the existing ones.

So TCP is a protocol too advanced to be used for streaming.

How to hide a TemplateField column in a GridView

Am I missing something ?

If you can't set visibility on TemplateField then set it on its content

<asp:TemplateField>
  <ItemTemplate>
    <asp:LinkButton Visible='<%# MyBoolProperty %>' ID="foo" runat="server" ... />
  </ItemTemplate>
</asp:TemplateField> 

or if your content is complex then enclose it into a div and set visibility on the div

<asp:TemplateField>
  <ItemTemplate>
    <div runat="server" visible='<%# MyBoolProperty  %>' >
      <asp:LinkButton ID="attachmentButton" runat="server" ... />
    </div>
  </ItemTemplate>
</asp:TemplateField> 

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

Keep values selected after form submission

If you are using WordPress (as is the case with the OP), you can use the selected function.

<form method="get" action="">
  <select name="name">
    <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
    <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
  </select>
  <select name="location">
    <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
    <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
  </select>
  <input type="submit" value="Submit" class="submit" />
</form>

Format a JavaScript string using placeholders and an object of substitutions?

I have written a code that lets you format string easily.

Use this function.

function format() {
    if (arguments.length === 0) {
        throw "No arguments";
    }
    const string = arguments[0];
    const lst = string.split("{}");
    if (lst.length !== arguments.length) {
        throw "Placeholder format mismatched";
    }
    let string2 = "";
    let off = 1;
    for (let i = 0; i < lst.length; i++) {
        if (off < arguments.length) {
            string2 += lst[i] + arguments[off++]
        } else {
            string2 += lst[i]
        }
    }
    return string2;
}

Example

format('My Name is {} and my age is {}', 'Mike', 26);

Output

My Name is Mike and my age is 26

Failed to find 'ANDROID_HOME' environment variable

This solved my problem. Add below to your system path

PATH_TO_android\platforms

PATH_TO_android\platform-tools

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

CKEditor automatically strips classes from div

Following is the complete example for CKEDITOR 4.x :

HTML

<textarea name="post_content" id="post_content" class="form-control"></textarea>

SCRIPT

CKEDITOR.replace('post_content', {
   allowedContent:true,
});

The above code will allow all tags in the editor.

For more Detail : CK EDITOR Allowed Content Rules

Angular ng-if="" with multiple arguments

It is possible.

<span ng-if="checked && checked2">
  I'm removed when the checkbox is unchecked.
</span>

http://plnkr.co/edit/UKNoaaJX5KG3J7AswhLV?p=preview

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Get JSON Data from URL Using Android?

Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

JSON library for C#

The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace GoogleTranslator.GoogleJSON
{
    public class FooTest
    {
        public void Test()
        {
            const string json = @"{
              ""DisplayFieldName"" : ""ObjectName"", 
              ""FieldAliases"" : {
                ""ObjectName"" : ""ObjectName"", 
                ""ObjectType"" : ""ObjectType""
              }, 
              ""PositionType"" : ""Point"", 
              ""Reference"" : {
                ""Id"" : 1111
              }, 
              ""Objects"" : [
                {
                  ""Attributes"" : {
                    ""ObjectName"" : ""test name"", 
                    ""ObjectType"" : ""test type""
                  }, 
                  ""Position"" : 
                  {
                    ""X"" : 5, 
                    ""Y"" : 7
                  }
                }
              ]
            }";

            var ser = new JavaScriptSerializer();
            ser.Deserialize<Foo>(json);
        }
    }

    public class Foo
    {
        public Foo() { Objects = new List<SubObject>(); }
        public string DisplayFieldName { get; set; }
        public NameTypePair FieldAliases { get; set; }
        public PositionType PositionType { get; set; }
        public Ref Reference { get; set; }
        public List<SubObject> Objects { get; set; }
    }

    public class NameTypePair
    {
        public string ObjectName { get; set; }
        public string ObjectType { get; set; }
    }

    public enum PositionType { None, Point }
    public class Ref
    {
        public int Id { get; set; }
    }

    public class SubObject
    {
        public NameTypePair Attributes { get; set; }
        public Position Position { get; set; }
    }

    public class Position
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}

How to return the output of stored procedure into a variable in sql server

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.

If no return is explicitly set, then the stored procedure returns zero.

   CREATE PROCEDURE GetImmediateManager
      @employeeID INT,
      @managerID INT OUTPUT
   AS
   BEGIN
     SELECT @managerID = ManagerID 
     FROM HumanResources.Employee 
     WHERE EmployeeID = @employeeID

     if @@rowcount = 0 -- manager not found?
       return 1;
   END

And you call it this way:

DECLARE @return_status int;
DECLARE @managerID int;

EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
  print N'Immediate manager not found!';
else 
  print N'ManagerID is ' + @managerID;
go

You should use the return value for status codes only. To return data, you should use output parameters.

If you want to return a dataset, then use an output parameter of type cursor.

more on RETURN statement

Swift days between two NSDates

This is an updated version of Emin's answer for Swift 5 that incorporates the suggestion to use noon instead of midnight as the definitive time for comparing days. It also handles the potential failure of various date functions by returning an optional.

    ///
    /// This is an approximation; it does not account for time differences. It will set the time to 1200 (noon) and provide the absolute number
    /// of days between now and the given date. If the result is negative, it should be read as "days ago" instead of "days from today."
    /// Returns nil if something goes wrong initializing or adjusting dates.
    ///

    func daysFromToday() -> Int?
    {
        let calendar = NSCalendar.current

        // Replace the hour (time) of both dates with noon. (Noon is less likely to be affected by DST changes, timezones, etc. than midnight.)
        guard let date1 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: Date())),
              let date2 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: self)) else
        {
            return nil
        }

        return calendar.dateComponents([.day], from: date1, to: date2).day
    }

How to append data to a json file?

Using a instead of w should let you update the file instead of creating a new one/overwriting everything in the existing file.

See this answer for a difference in the modes.

GetType used in PowerShell, difference between variables

First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do:

$a.GetType();
$b.GetType();

You should see that $a is a [DayOfWeek], and $b is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only:

C:\> $b.DayOfWeek -eq $a
True

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

"Change to if (typeof $next == 'object' && $next.length) $next[0].offsetWidth" -did not help. if you convert Bootstrap 3 to php(for WordPress theme), when adding WP_Query ($loop = new WP_Query( $args );) insert $count = 0;. And and at the end before endwhile; add $count++;.

File Upload in WebView

hifarrer's full solution is very helpful to me.

but, I met many other problems - supporting other mime type, listing capture devices(camera, video, audio recoder), opening capture device immediately(ex: <input accept="image/*;capture"> )...

So, I made a solution that works exactly same as default web browser app.

I used android-4.4.3_r1/src/com/android/browser/UploadHandler.java. (thanks to Rupert Rawnsley )

package org.mospi.agatenativewebview;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webView1);

        initWebView(webView);
        webView.loadUrl("http://google.com"); // TODO input your url

    }

    private final static Object methodInvoke(Object obj, String method, Class<?>[] parameterTypes, Object[] args) {
        try {
            Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
            m.invoke(obj, args);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private void initWebView(WebView webView) {

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        // settings.setPluginsEnabled(true);
        methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
        // settings.setPluginState(PluginState.ON);
        methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON });
        // settings.setPluginsEnabled(true);
        methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
        // settings.setAllowUniversalAccessFromFileURLs(true);
        methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
        // settings.setAllowFileAccessFromFileURLs(true);
        methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });

        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.clearHistory();
        webView.clearFormData();
        webView.clearCache(true);

        webView.setWebChromeClient(new MyWebChromeClient());
        // webView.setDownloadListener(downloadListener);
    }

    UploadHandler mUploadHandler;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == Controller.FILE_SELECTED) {
            // Chose a file from the file picker.
            if (mUploadHandler != null) {
                mUploadHandler.onResult(resultCode, intent);
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    class MyWebChromeClient extends WebChromeClient {
        public MyWebChromeClient() {

        }

        private String getTitleFromUrl(String url) {
            String title = url;
            try {
                URL urlObj = new URL(url);
                String host = urlObj.getHost();
                if (host != null && !host.isEmpty()) {
                    return urlObj.getProtocol() + "://" + host;
                }
                if (url.startsWith("file:")) {
                    String fileName = urlObj.getFile();
                    if (fileName != null && !fileName.isEmpty()) {
                        return fileName;
                    }
                }
            } catch (Exception e) {
                // ignore
            }

            return title;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setCancelable(false).create().show();
            return true;
            // return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {

            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            }).setCancelable(false).create().show();
            return true;

            // return super.onJsConfirm(view, url, message, result);
        }

        // Android 2.x
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, "", "filesystem");
        }

        // Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadHandler = new UploadHandler(new Controller());
            mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
        }

        // Android 4.4, 4.4.1, 4.4.2
        // openFileChooser function is not called on Android 4.4, 4.4.1, 4.4.2,
        // you may use your own java script interface or other hybrid framework.          

        // Android 5.0.1
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            String acceptTypes[] = fileChooserParams.getAcceptTypes();

            String acceptType = "";
            for (int i = 0; i < acceptTypes.length; ++ i) {
                if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
                    acceptType += acceptTypes[i] + ";";
            }
            if (acceptType.length() == 0)
                acceptType = "*/*";

            final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;

            ValueCallback<Uri> vc = new ValueCallback<Uri>() {

                @Override
                public void onReceiveValue(Uri value) {

                    Uri[] result;
                    if (value != null)
                        result = new Uri[]{value};
                    else
                        result = null;

                    finalFilePathCallback.onReceiveValue(result);

                }
            };

            openFileChooser(vc, acceptType, "filesystem");


            return true;
       }
    };

    class Controller {
        final static int FILE_SELECTED = 4;

        Activity getActivity() {
            return MainActivity.this;
        }
    }

    // copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.java
    //////////////////////////////////////////////////////////////////////

    /*
     * Copyright (C) 2010 The Android Open Source Project
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    // package com.android.browser;
    //
    // import android.app.Activity;
    // import android.content.ActivityNotFoundException;
    // import android.content.Intent;
    // import android.net.Uri;
    // import android.os.Environment;
    // import android.provider.MediaStore;
    // import android.webkit.ValueCallback;
    // import android.widget.Toast;
    //
    // import java.io.File;
    // import java.util.Vector;
    //
    // /**
    // * Handle the file upload callbacks from WebView here
    // */
    // public class UploadHandler {

    class UploadHandler {
        /*
         * The Object used to inform the WebView of the file to upload.
         */
        private ValueCallback<Uri> mUploadMessage;
        private String mCameraFilePath;
        private boolean mHandled;
        private boolean mCaughtActivityNotFoundException;
        private Controller mController;
        public UploadHandler(Controller controller) {
            mController = controller;
        }
        String getFilePath() {
            return mCameraFilePath;
        }
        boolean handled() {
            return mHandled;
        }
        void onResult(int resultCode, Intent intent) {
            if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
                // Couldn't resolve an activity, we are going to try again so skip
                // this result.
                mCaughtActivityNotFoundException = false;
                return;
            }
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
                    : intent.getData();
            // As we ask the camera to save the result of the user taking
            // a picture, the camera application does not return anything other
            // than RESULT_OK. So we need to check whether the file we expected
            // was written to disk in the in the case that we
            // did not get an intent returned but did get a RESULT_OK. If it was,
            // we assume that this result has came back from the camera.
            if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
                File cameraFile = new File(mCameraFilePath);
                if (cameraFile.exists()) {
                    result = Uri.fromFile(cameraFile);
                    // Broadcast to the media scanner that we have a new photo
                    // so it will be added into the gallery for the user.
                    mController.getActivity().sendBroadcast(
                            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
            }
            mUploadMessage.onReceiveValue(result);
            mHandled = true;
            mCaughtActivityNotFoundException = false;
        }
        void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            final String imageMimeType = "image/*";
            final String videoMimeType = "video/*";
            final String audioMimeType = "audio/*";
            final String mediaSourceKey = "capture";
            final String mediaSourceValueCamera = "camera";
            final String mediaSourceValueFileSystem = "filesystem";
            final String mediaSourceValueCamcorder = "camcorder";
            final String mediaSourceValueMicrophone = "microphone";
            // According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
            // or 'microphone' and the default value should be 'filesystem'.
            String mediaSource = mediaSourceValueFileSystem;
            if (mUploadMessage != null) {
                // Already a file picker operation in progress.
                return;
            }
            mUploadMessage = uploadMsg;
            // Parse the accept type.
            String params[] = acceptType.split(";");
            String mimeType = params[0];
            if (capture.length() > 0) {
                mediaSource = capture;
            }
            if (capture.equals(mediaSourceValueFileSystem)) {
                // To maintain backwards compatibility with the previous implementation
                // of the media capture API, if the value of the 'capture' attribute is
                // "filesystem", we should examine the accept-type for a MIME type that
                // may specify a different capture value.
                for (String p : params) {
                    String[] keyValue = p.split("=");
                    if (keyValue.length == 2) {
                        // Process key=value parameters.
                        if (mediaSourceKey.equals(keyValue[0])) {
                            mediaSource = keyValue[1];
                        }
                    }
                }
            }
            //Ensure it is not still set from a previous upload.
            mCameraFilePath = null;
            if (mimeType.equals(imageMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamera)) {
                    // Specified 'image/*' and requested the camera, so go ahead and launch the
                    // camera directly.
                    startActivity(createCameraIntent());
                    return;
                } else {
                    // Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
                    // In all these cases we show a traditional picker filetered on accept type
                    // so launch an intent for both the Camera and image/* OPENABLE.
                    Intent chooser = createChooserIntent(createCameraIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(videoMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamcorder)) {
                    // Specified 'video/*' and requested the camcorder, so go ahead and launch the
                    // camcorder directly.
                    startActivity(createCamcorderIntent());
                    return;
               } else {
                    // Specified just 'video/*', capture=filesystem or an invalid capture parameter.
                    // In all these cases we show an intent for the traditional file picker, filtered
                    // on accept type so launch an intent for both camcorder and video/* OPENABLE.
                    Intent chooser = createChooserIntent(createCamcorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(audioMimeType)) {
                if (mediaSource.equals(mediaSourceValueMicrophone)) {
                    // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
                    // recorder.
                    startActivity(createSoundRecorderIntent());
                    return;
                } else {
                    // Specified just 'audio/*',  capture=filesystem of an invalid capture parameter.
                    // In all these cases so go ahead and launch an intent for both the sound
                    // recorder and audio/* OPENABLE.
                    Intent chooser = createChooserIntent(createSoundRecorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
                    startActivity(chooser);
                    return;
                }
            }
            // No special handling based on the accept type was necessary, so trigger the default
            // file upload chooser.
            startActivity(createDefaultOpenableIntent());
        }
        private void startActivity(Intent intent) {
            try {
                mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
            } catch (ActivityNotFoundException e) {
                // No installed app was able to handle the intent that
                // we sent, so fallback to the default file upload control.
                try {
                    mCaughtActivityNotFoundException = true;
                    mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
                            Controller.FILE_SELECTED);
                } catch (ActivityNotFoundException e2) {
                    // Nothing can return us a file, so file upload is effectively disabled.
                    Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
                            Toast.LENGTH_LONG).show();
                }
            }
        }
        private Intent createDefaultOpenableIntent() {
            // Create and return a chooser with the default OPENABLE
            // actions including the camera, camcorder and sound
            // recorder where available.
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
                    createSoundRecorderIntent());
            chooser.putExtra(Intent.EXTRA_INTENT, i);
            return chooser;
        }
        private Intent createChooserIntent(Intent... intents) {
            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
            chooser.putExtra(Intent.EXTRA_TITLE,
                    mController.getActivity().getResources()
                            .getString(R.string.choose_upload));
            return chooser;
        }
        private Intent createOpenableIntent(String type) {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(type);
            return i;
        }
        private Intent createCameraIntent() {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File externalDataDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
            File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                    File.separator + "browser-photos");
            cameraDataDir.mkdirs();
            mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                    System.currentTimeMillis() + ".jpg";
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
            return cameraIntent;
        }
        private Intent createCamcorderIntent() {
            return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        }
        private Intent createSoundRecorderIntent() {
            return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        }
    }
}

additional string resoruce of res/values/string.xml :

<string name="uploads_disabled">File uploads are disabled.</string>
<string name="choose_upload">Choose file for upload</string>

If you are using proguard, you may need below option in proguard-project.txt :

-keepclassmembers class * extends android.webkit.WebChromeClient {
   public void openFileChooser(...);
}

UPDATE #1 (2015.09.09)

adds code for Android 5.0.1 compatability.

How can I add new array elements at the beginning of an array in Javascript?

If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>) :

_x000D_
_x000D_
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
_x000D_
_x000D_

How do I list all tables in a schema in Oracle SQL?

select * from user_tables;

(showing all tables)

How do you reindex an array in PHP but with indexes starting from 1?

If you are not trying to reorder the array you can just do:

$array = array_reverse( $array );
$array = array_reverse( $array );

The array_reverse is very fast and it reorders as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.

Finding the layers and layer sizes for each Docker image

It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.

You can refer to the Registry v2 API to fetch the manifest of image.

GET /v2/<name>/manifests/<reference>

Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.

There is a simple script for handling above cases that will be continuously maintained.

How do I split a string into an array of characters?

A string in Javascript is already a character array.

You can simply access any character in the array as you would any other array.

var s = "overpopulation";
alert(s[0]) // alerts o.

UPDATE

As is pointed out in the comments below, the above method for accessing a character in a string is part of ECMAScript 5 which certain browsers may not conform to.

An alternative method you can use is charAt(index).

var s = "overpopulation";
    alert(s.charAt(0)) // alerts o.

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

This will validate against special characters and leading and trailing spaces:

var strString = "Your String";

strString.match(/^[A-Za-z0-9][A-Za-z0-9 ]\*[A-Za-z0-9]\*$/)

R: invalid multibyte string

I realize this is pretty late, but I had a similar problem and I figured I'd post what worked for me. I used the iconv utility (e.g., "iconv file.pcl -f UTF-8 -t ISO-8859-1 -c"). The "-c" option skips characters that can't be translated.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

There's also another way to do this-

select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;

Excel Reference To Current Cell

=ADDRESS(ROW(),COLUMN(),4) will give us the relative address of the current cell. =INDIRECT(ADDRESS(ROW(),COLUMN()-1,4)) will give us the contents of the cell left of the current cell =INDIRECT(ADDRESS(ROW()-1,COLUMN(),4)) will give us the contents of the cell above the current cell (great for calculating running totals)

Using CELL() function returns information about the last cell that was changed. So, if we enter a new row or column the CELL() reference will be affected and will not be the current cell's any longer.

error: RPC failed; curl transfer closed with outstanding read data remaining

you need to turn off the compression:

git config --global core.compression 0

then you need to use shallow clone

git clone --depth=1 <url>

then most important step is to cd into your cloned project

cd <shallow cloned project dir>

now deopen the clone,step by step

git fetch --depth=N, with increasing N

eg.

git fetch --depth=4

then,

git fetch --depth=100

then,

git fetch --depth=500

you can choose how many steps you want by replacing this N,

and finally download all of the remaining revisions using,

git fetch --unshallow 

upvote if it helps you :)

How to make phpstorm display line numbers by default?

Just now found where is it on Windows. Its View -> Active Editor -> Show Line Numbers (changes only for current document) and File -> Settings -> Editor -> Appearance -> Show Line Numbers (for all documents)

For Mac Version go to PhpStorm -> Preferences in menu. In the preference window go to IDE settings -> Editor -> Appearance -> Show Line Numbers (To change setting for all documents)

OR if you want to quickly set show line number PER CURRENT WINDOW even easier - right click on the long white column (where breakpoints are set) then select Show Line Numbers.

enter image description here

Red dot on the screenshot is a place where you have to click

Live-stream video from one android phone to another over WiFi

You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!

Datetime format Issue: String was not recognized as a valid DateTime

try this:

string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",  
   System.Globalization.CultureInfo.InvariantCulture, 
   System.Globalization.DateTimeStyles.None, out dtTime))
 {
    Console.WriteLine(dtTime);
 }

How do you rename a MongoDB database?

The above process is slow,you can use below method but you need to move collection by collection to another db.

use admin
db.runCommand({renameCollection: "[db_old_name].[collection_name]", to: "[db_new_name].[collection_name]"})

How to export data to an excel file using PHPExcel

$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
$objWriter->save('php://output');

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

css selector to match an element without attribute x

:not selector:

input:not([type]), input[type='text'], input[type='password'] {
    /* style here */
}

Support: in Internet Explorer 9 and higher

get size of json object

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

Embedding a media player in a website using HTML

You can use plenty of things.

  • If you're a standards junkie, you can use the HTML5 <audio> tag:

Here is the official W3C specification for the audio tag.

Usage:

<audio controls>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>
 <!-- The next two lines are only executed if the browser doesn't support MP4 files -->
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>
 <!-- The next line will only be executed if the browser doesn't support the <audio> tag-->
 <p>Your user agent does not support the HTML5 Audio element.</p>
</audio>

jsFiddle here.

Note: I'm not sure which are the best ones, as I have never used one (yet).


UPDATE: As mentioned in another answer's comment, you are using XHTML 1.0 Transitional. You might be able to get <audio> to work with some hack.


UPDATE 2: I just remembered another way to do play audio. This will work in XHTML!!! This is fully standards-compliant.

You use this JavaScript:

var aud = document.createElement("iframe");
aud.setAttribute('src', "http://yoursite.com/youraudio.mp4"); // replace with actual file path
aud.setAttribute('width', '1px');
aud.setAttribute('height', '1px');
aud.setAttribute('scrolling', 'no');
aud.style.border = "0px";
document.body.appendChild(aud);

This is my answer to another question.


UPDATE 3: To customise the controls, you can use something like this.

Java 8 LocalDate Jackson format

https://stackoverflow.com/a/53251526/1282532 is the simplest way to serialize/deserialize property. I have two concerns regarding this approach - up to some point violation of DRY principle and high coupling between pojo and mapper.

public class Trade {
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate tradeDate;
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate maturityDate;
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate entryDate;
}

In case you have POJO with multiple LocalDate fields it's better to configure mapper instead of POJO. It can be as simple as https://stackoverflow.com/a/35062824/1282532 if you are using ISO-8601 values ("2019-01-31")

In case you need to handle custom format the code will be like this:

ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
mapper.registerModule(javaTimeModule);

The logic is written just once, it can be reused for multiple POJO

Calculate age based on date of birth

Got this script from net (thanks to coffeecupweb)

<?php
/**
 * Simple PHP age Calculator
 * 
 * Calculate and returns age based on the date provided by the user.
 * @param   date of birth('Format:yyyy-mm-dd').
 * @return  age based on date of birth
 */
function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }else{
        return 0;
    }
}
$dob = '1992-03-18';
echo ageCalculator($dob);
?>

Adding headers when using httpClient.GetAsync

Sometimes, you only need this code.

 httpClient.DefaultRequestHeaders.Add("token", token);

javascript window.location in new tab

with jQuery its even easier and works on Chrome as well

$('#your-button').on('click', function(){
       $('<a href="https://www.some-page.com" target="blank"></a>')[0].click();    
})

zsh compinit: insecure directories

Following worked on M1

ProductName:    macOS
ProductVersion: 11.1
BuildVersion:   20C69

% compaudit
/opt/homebrew/share

Changed group permission from 775 to 755

% sudo chmod 755 /opt/homebrew/share

drwxr-xr-x   33 xenea  admin   1056 Feb  2 01:28 share

HTML input time in 24 format

In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.

DataGrid get selected rows' column values

I did something similar but I use binding to get the selected item :

<DataGrid Grid.Row="1" AutoGenerateColumns="False" Name="dataGrid"
          IsReadOnly="True" SelectionMode="Single"
          ItemsSource="{Binding ObservableContactList}" 
          SelectedItem="{Binding SelectedContact}">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
    <DataGridTextColumn Binding="{Binding Path=FamilyName}" Header="FamilyName"/>
    <DataGridTextColumn Binding="{Binding Path=Age}" Header="Age"/>
    <DataGridTextColumn Binding="{Binding Path=Relation}" Header="Relation"/>
    <DataGridTextColumn Binding="{Binding Path=Phone.Display}" Header="Phone"/>
    <DataGridTextColumn Binding="{Binding Path=Address.Display}" Header="Addr"/>
    <DataGridTextColumn Binding="{Binding Path=Mail}" Header="E-mail"/>
  </DataGrid.Columns>
</DataGrid>

So I can access my SelectedContact.Name in my ViewModel.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

In c++ what does a tilde "~" before a function name signify?

It's a destructor. The function is guaranteed to be called when the object goes out of scope.

best way to preserve numpy arrays on disk

I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.

benchmark for numpy array storage

Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.

If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).

More details and the code are available at the github repo.

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

Usage

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

Fastest way to Remove Duplicate Value from a list<> by lambda

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.

How to use setArguments() and getArguments() methods in Fragments?

Instantiating the Fragment the correct way!

getArguments() setArguments() methods seem very useful when it comes to instantiating a Fragment using a static method.
ie Myfragment.createInstance(String msg)

How to do it?

Fragment code

public MyFragment extends Fragment {

    private String displayMsg;
    private TextView text;

    public static MyFragment createInstance(String displayMsg)
    {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.setString("KEY",displayMsg);
        fragment.setArguments(args);           //set
        return fragment;
    }

    @Override
    public void onCreate(Bundle bundle)
    {
        displayMsg = getArguments().getString("KEY"):    // get 
    }

    @Override
    public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
        View view = inflater.inflate(R.id.placeholder,parent,false);
        text = (TextView)view.findViewById(R.id.myTextView);
        text.setText(displayMsg)    // show msg
        returm view;
   }

}

Let's say you want to pass a String while creating an Instance. This is how you will do it.

MyFragment.createInstance("This String will be shown in textView");

Read More

1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

Block Comments in a Shell Script

In bash:

#!/bin/bash
echo before comment
: <<'END'
bla bla
blurfl
END
echo after comment

The ' and ' around the END delimiter are important, otherwise things inside the block like for example $(command) will be parsed and executed.

For an explanation, see this and this question.

How to create a unique index on a NULL column?

Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html

Can an abstract class have a constructor?

Yes surely you can add one, as already mentioned for initialization of Abstract class variables. BUT if you dont explicitly declare one, it anyways has an implicit constructor for "Constructor Chaining" to work.

How to make a Python script run like a service or daemon in Linux

how about using $nohup command on linux?

I use it for running my commands on my Bluehost server.

Please advice if I am wrong.

NSURLErrorDomain error codes description

I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain taken from NSURLError.h

/*!
    @enum NSURL-related Error Codes
    @abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
    NSURLErrorUnknown =             -1,
    NSURLErrorCancelled =           -999,
    NSURLErrorBadURL =              -1000,
    NSURLErrorTimedOut =            -1001,
    NSURLErrorUnsupportedURL =          -1002,
    NSURLErrorCannotFindHost =          -1003,
    NSURLErrorCannotConnectToHost =         -1004,
    NSURLErrorNetworkConnectionLost =       -1005,
    NSURLErrorDNSLookupFailed =         -1006,
    NSURLErrorHTTPTooManyRedirects =        -1007,
    NSURLErrorResourceUnavailable =         -1008,
    NSURLErrorNotConnectedToInternet =      -1009,
    NSURLErrorRedirectToNonExistentLocation =   -1010,
    NSURLErrorBadServerResponse =       -1011,
    NSURLErrorUserCancelledAuthentication =     -1012,
    NSURLErrorUserAuthenticationRequired =  -1013,
    NSURLErrorZeroByteResource =        -1014,
    NSURLErrorCannotDecodeRawData =             -1015,
    NSURLErrorCannotDecodeContentData =         -1016,
    NSURLErrorCannotParseResponse =             -1017,
    NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
    NSURLErrorFileDoesNotExist =        -1100,
    NSURLErrorFileIsDirectory =         -1101,
    NSURLErrorNoPermissionsToReadFile =     -1102,
    NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

    // SSL errors
    NSURLErrorSecureConnectionFailed =      -1200,
    NSURLErrorServerCertificateHasBadDate =     -1201,
    NSURLErrorServerCertificateUntrusted =  -1202,
    NSURLErrorServerCertificateHasUnknownRoot = -1203,
    NSURLErrorServerCertificateNotYetValid =    -1204,
    NSURLErrorClientCertificateRejected =   -1205,
    NSURLErrorClientCertificateRequired =   -1206,
    NSURLErrorCannotLoadFromNetwork =       -2000,

    // Download and file I/O errors
    NSURLErrorCannotCreateFile =        -3000,
    NSURLErrorCannotOpenFile =          -3001,
    NSURLErrorCannotCloseFile =         -3002,
    NSURLErrorCannotWriteToFile =       -3003,
    NSURLErrorCannotRemoveFile =        -3004,
    NSURLErrorCannotMoveFile =          -3005,
    NSURLErrorDownloadDecodingFailedMidStream = -3006,
    NSURLErrorDownloadDecodingFailedToComplete =-3007,

    NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
    NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
    NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
    NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

    NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
    NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
    NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};

SecurityError: The operation is insecure - window.history.pushState()

I solved it by switching tohttp protocol from the file protocol.

  • you can use "live-server" extension in VS code,
  • or, on node, use live-server [dirPath]

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

How to backup MySQL database in PHP?

While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.

I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.

The basic usage of mysqldump is

mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like

mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like

<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.

It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.

You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

Detect application heap size in Android

The official API is:

This was introduced in 2.0 where larger memory devices appeared. You can assume that devices running prior versions of the OS are using the original memory class (16).

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Found out that there's no bug there. Just add:

<base href="/" />

to your <head />.

Javascript Error Null is not an Object

I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.

This is what I would do

<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;

function setup() {
  myButton = document.getElementById("myButton");
  myTextfield = document.getElementById("myTextfield");
  myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);
    return false;
  }
}

function greetUser(userName) {
  var greeting = "Hello " + userName + "!";
  document.getElementsByTagName("h2")[0].innerHTML = greeting;
}

</script>
<body onload="setup()">
  <h2>Hello World!</h2>
  <p id="myParagraph">This is an example website</p>

  <form>
    <input type="text" id="myTextfield" placeholder="Type your name" />
    <input type="button" id="myButton" value="Go" />
  </form>
  </body>
</html>

have fun!

JavaScript - Get minutes between two dates

var startTime = new Date('2012/10/09 12:00'); 
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);

Private properties in JavaScript ES6 classes

It is possible to have private methods in classes using WeakMap.

According to MDN web docs:

The WeakMap object is a collection of key/value pairs in which the keys are objects only and the values can be arbitrary values.

The object references in the keys are held weakly, meaning that they are a target of garbage collection (GC) if there is no other reference to the object anymore.

And this is an example of creating Queue data structure with a private member _items which holds an array.

const _items = new WeakMap();

class Queue {    
    constructor() {
        _items.set(this, []);
    }

    enqueue( item) {
        _items.get(this).push(item);
    }    

    get count() {
        return _items.get(this).length;        
    }

    peek() {
        const anArray = _items.get(this);
        if( anArray.length == 0)
            throw new Error('There are no items in array!');

        if( anArray.length > 0)
            return anArray[0];
    }

    dequeue() {        
        const anArray = _items.get(this);
        if( anArray.length == 0)
            throw new Error('There are no items in array!');

        if( anArray.length > 0)
            return anArray.splice(0, 1)[0];
    }    
}

An example of using:

const c = new Queue();
c.enqueue("one");
c.enqueue("two");
c.enqueue("three");
c.enqueue("four");
c.enqueue("five");
console.log(c);

Private member _items is hided and cannot be seen in properties or methods of an Queue object:

enter image description here

However, private member _items in the Queue object can be reached using this way:

const anArray = _items.get(this);

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

No module named pkg_resources

I had this problem today as well. I only got the problem inside the virtual env.

The solution for me was deactivating the virtual env, deleting and then uninstalling virtualenv with pip and reinstalling it. After that I created a new virtual env for my project, then pip worked fine both inside the virtual environment as in the normal environment.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

What is the best collation to use for MySQL with PHP?

The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.

utf8_general_ci is somewhat faster than utf8_unicode_ci, but less accurate (for sorting). The specific language utf8 encoding (such as utf8_swedish_ci) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use utf8_unicode_ci (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.

You can read more on specific unicode character sets on the MySQL manual - http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

To get total number of columns in a table in sql

The below query will display all the tables and corresponding column count in a database schema

SELECT Table_Name, count(*) as [No.of Columns]
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'dbo' -- schema name
group by table_name

Add default value of datetime field in SQL Server to a timestamp

For modifying an existing column in an existing table:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

React js onClick can't pass value to method

I have below 3 suggestion to this on JSX onClick Events -

  1. Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.

  2. You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.

    So finally code will look like this:
    <ul onClick={this.onItemClick}>
        {this.props.items.map(item =>
               <li key={item.id} data-itemid={item.id}>
                   ...
               </li>
          )}
    </ul>
    

    // And you can access item.id in onItemClick method as shown below:

    onItemClick = (event) => {
       console.log(e.target.getAttribute("item.id"));
    }
    
  3. I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.

    import React from "react";
    import ListItem from "./ListItem";
    export default class List extends React.Component {
    
        /**
        * This List react component is generic component which take props as list of items and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = (item) => {
            if (this.props.onItemClick) {
                this.props.onItemClick(item);
            }
        }
    
        /**
        * render method will take list of items as a props and include ListItem component
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <div>
                  {this.props.items.map(item =>
                      <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                  )}
                </div>
            );
        }
    
    }
    
    
    import React from "react";
    
    export default class ListItem extends React.Component {
        /**
        * This List react component is generic component which take props as item and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = () => {
            if (this.props.item && this.props.onItemClick) {
                this.props.onItemClick(this.props.item);
            }
        }
        /**
        * render method will take item as a props and print in li
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
            );
        }
    }
    

What is Java EE?

J(2)EE, strictly speaking, is a set of APIs (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.

In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!

J2EE was a marketing construct.

When creating a service with sc.exe how to pass in context parameters?

Parameters for created services have some peculiar formating issues, in particular if the command includes spaces or quotes:

If you want to enter command line parameters for the service, you have to enclose the whole command line in quotes. (And always leave a space after binPath= and before the first quote, as mrswadge pointed out)

So, to create a service for the command PATH\COMMAND.EXE --param1=xyz you would use the following binPath parameter:

binPath= "PATH\COMMAND.EXE --param1=xyz"
        ^^                             ^
        ||                             |
  space    quote                     quote

If the path to the executable contains spaces, you have to enclose the path in quotes.

So for a command that has both parameters and a path with spaces, you need nested quotes. You have to escape the inner quotes with backslashes \". The same holds if the parameters themselves contain quotes, you will need to escape those too.

Despite using backslashes as escape characters, you do not have to escape the regular backslashes contained in the path. This is contrary to how you normally use backslashes as escape characters.

So for a command like
"PATH WITH SPACES \COMMAND.EXE" --param-with-quotes="a b c" --param2:

binPath= "\"PATH WITH SPACES \COMMAND.EXE\" --param-with-quotes=\"a b c\" --param2"
         ^ ^                 ^           ^                      ^       ^         ^
         | |                 |           |                      |       |         | 
 opening     escaped      regular     escaped                    escaped       closing
   quote     quote       backslash    closing                    quotes          quote
     for     for            in         quote                      for              for
   whole     path          path       for path                  parameter        whole
 command                                                                       command

Here is a concrete example from the SVNserve documentation, which shows all special cases:

sc create svnserve 
   binpath= "\"C:\Program Files\CollabNet Subversion Server\svnserve.exe\" --service -r \"C:\my repositories\"  "
   displayname= "Subversion Server" depend= Tcpip start= auto 

(linebreaks are added for readability, do not include them)

This would add a new service with the command line "C:\Program Files\CollabNet Subversion Server\svnserve.exe" --service -r "C:\my repositories".

So in summary

  • space after each sc parameter: binpath=_, displayname=_ and depend=_
  • each sc parameter that contains spaces must be enclosed in quotes
  • all additional quotes inside the binpath are escaped with backslashes: \"
  • all backslashes inside the binpath are not escaped

Convert JSON String to JSON Object c#

there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes

Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented . In this manner you will use these classes which is more powerful and simply to use.

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

<script src="/script/login.js"></script>

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

Error: Unable to run mksdcard SDK tool

if you do this: sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6. You may get this error:

E: Unable to locate package lib32bz2-1.0

E: Couldn't find any package by glob 'lib32bz2-1.0'

E: Couldn't find any package by regex 'lib32bz2-1.0'

So i suggest just doing this:

sudo apt-get install lib32stdc++6

And also, the AOSP should look for how while installing Android-Studio, that is installed too.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

Alternate background colors for list items

You can achieve this by adding alternating style classes to each list item

<ul>
    <li class="odd"><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li><a href="link">Link 2</a></li>
</ul>

And then styling it like

li { backgorund:white; }
li.odd { background:silver; }

You can further automate this process with javascript (jQuery example below)

$(document).ready(function() {
  $('table tbody tr:odd').addClass('odd');
});

How do I debug jquery AJAX calls?

here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:

    $('#ChangePermission').click(function () {
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
            'user': document.GetElementById("user").value,
            'perm': document.GetElementById("perm").value
        },
        success: function (data) {
            console.log(data);  
        },
        error: function (data) {
            console.log(data);
        }
    });
});

on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.

<?php

error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

if (isset($_POST["user"]) && isset($_POST["perm"])) {
    $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
    $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
    $STH->execute();
} catch (PDOException $e) {
    $result .= $e->getMessage;
}
echo json_encode($result);
?>

Lambda expression to convert array/List of String to array/List of Integers

In addition - control when string array doesn't have elements:

Arrays.stream(from).filter(t -> (t != null)&&!("".equals(t))).map(func).toArray(generator) 

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

What version of tomcat are you using ? What appears to me is that the tomcat version is not supporting the servlet & jsp versions you're using. You can change to something like below or look into your version of tomcat on what it supports and change the versions accordingly.

 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

Compiling a C++ program with gcc

By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:

gcc -x c++

More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language).

This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

If after install you need to run redis on all time, just type in terminal:

redis-server &

Running redis using upstart on Ubuntu

I've been trying to understand how to setup systems from the ground up on Ubuntu. I just installed redis onto the box and here's how I did it and some things to look out for.

To install:

sudo apt-get install redis-server

That will create a redis user and install the init.d script for it. Since upstart is now the replacement for using init.d, I figure I should convert it to run using upstart.

To disable the default init.d script for redis:

sudo update-rc.d redis-server disable

Then create /etc/init/redis-server.conf with the following script:

description "redis server"

start on runlevel [23]
stop on shutdown

exec sudo -u redis /usr/bin/redis-server /etc/redis/redis.conf

respawn

What this is the script for upstart to know what command to run to start the process. The last line also tells upstart to keep trying to respawn if it dies.

One thing I had to change in /etc/redis/redis.conf is daemonize yes to daemonize no. What happens if you don't change it then redis-server will fork and daemonize itself, and the parent process goes away. When this happens, upstart thinks that the process has died/stopped and you won't have control over the process from within upstart.

Now you can use the following commands to control your redis-server:

sudo start redis-server
sudo restart redis-server
sudo stop redis-server

Hope this was helpful!

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

What is the difference between Views and Materialized Views in Oracle?

Materialized views are the logical view of data-driven by the select query but the result of the query will get stored in the table or disk, also the definition of the query will also store in the database.

The performance of Materialized view it is better than normal View because the data of materialized view will be stored in table and table may be indexed so faster for joining also joining is done at the time of materialized views refresh time so no need to every time fire join statement as in case of view.

Other difference includes in case of View we always get latest data but in case of Materialized view we need to refresh the view for getting latest data. In case of Materialized view we need an extra trigger or some automatic method so that we can keep MV refreshed, this is not required for views in the database.

What is the best comment in source code you have ever encountered?

On the linux 1.0 kernel scheduler (sched.c):

Dijkstra probably hates me.

/*
 *  'schedule()' is the scheduler function. It's a very simple and nice
 * scheduler: it's not perfect, but certainly works for most things.
 * The one thing you might take a look at is the signal-handler code here.
 *
 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
 * information in task[0] is never used.
 *
 * The "confuse_gcc" goto is used only to get better assembly code..
 * Dijkstra probably hates me.
 */
asmlinkage void schedule(void)

(...)

Neither BindingResult nor plain target object for bean name available as request attr

Make sure that your Spring form mentions the modelAttribute="<Model Name".

Example:

@Controller
@RequestMapping("/greeting.html")
public class GreetingController {

 @ModelAttribute("greeting")
 public Greeting getGreetingObject() {
  return new Greeting();
 }

 /**
  * GET
  * 
  * 
  */
 @RequestMapping(method = RequestMethod.GET)
 public String handleRequest() {
  return "greeting";
 }

 /**
  * POST
  * 
  * 
  */
 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView processSubmit(@ModelAttribute("greeting") Greeting greeting, BindingResult result){
  ModelAndView mv = new ModelAndView();
  mv.addObject("greeting", greeting);  
  return mv;
 }
}

In your JSP :

<form:form  modelAttribute="greeting" method="POST" action="greeting.html">

How add spaces between Slick carousel item

Add

centerPadding: '0'

Slider settings will look like:

$('.phase-slider-one').slick({
     centerMode: true,
     centerPadding: '0',
     responsive: [{breakpoint: 1024,},{breakpoint: 600,},{breakpoint: 480,}]
});

Thank you

Android: How can I print a variable on eclipse console?

If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.

The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)