Programs & Examples On #Launch

The definition of a launch is an event at which something, such as an application/program is started.

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

How to open the command prompt and insert commands using Java?

You just need to append your command after start in the string that you are passing.

String command = "cmd.exe /c start "+"*your command*";

Process child = Runtime.getRuntime().exec(command);

How to remove specific value from array using jQuery

There is a simple solution with splice. According to W3School splice syntax is following;

array.splice(index, howmany, item1, ....., itemX)

index Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array

howmany Required. The number of items to be removed. If set to 0, no items will be removed

item1, ..., itemX Optional. The new item(s) to be added to the array

Keep that in mind, the following js will pop one or more matched item from the given array if found, otherwise wouldn't remove the last item of the array.

var x = [1,2,3,4,5,4,4,6,7];
var item = 4;
var startItemIndex = $.inArray(item, x);
var itemsFound = x.filter(function(elem){
                            return elem == item;
                          }).length;

Or

var itemsFound = $.grep(x, function (elem) {
                              return elem == item;
                           }).length;

So the final should look like the following

x.splice( startItemIndex , itemsFound );

Hope this helps.

Counting number of words in a file

import java.io.BufferedReader;
import java.io.FileReader;

public class CountWords {

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

       System.out.println ("Counting Words");       
       FileReader fr = new FileReader ("c:\\Customer1.txt");        
       BufferedReader br = new BufferedReader (fr);     
       String line = br.readLin ();
       int count = 0;
       while (line != null) {
          String []parts = line.split(" ");
          for( String w : parts)
          {
            count++;        
          }
          line = br.readLine();
       }         
       System.out.println(count);
    }
}

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

On Mac: I had installed android-sdk using brew as well as Android Studio. Somehow, having 2 installations was causing this problem. When I uninstalled my brew installation of the sdk using brew cask uninstall android-sdk and added the following vars to my env. It worked.

export ANDROID_HOME=/Users/<Username>/Library/Android/sdk
export ANDROID_SDK_ROOT=$ANDROID_HOME

Getting hold of the outer class object from the inner class object

OuterClass.this references the outer class.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

You need to use an Angular form directive on the select. You can do that with ngModel. For example

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class App {
  cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
  selectedCity = this.cities[1];

  onChange(city) {
    alert(city.name);
  }
}

The (ngModelChange) event listener emits events when the selected value changes. This is where you can hookup your callback.

Note you will need to make sure you have imported the FormsModule into the application.

Here is a Plunker

The requested URL /about was not found on this server

It worked for me like this:

Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:

/index.php/%year%/%monthnum%/%day%/%postname%/

and click the Save button.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

I believe there are two main reasons for trying to seperate templated code into a header and a cpp:

One is for mere elegance. We all like to write code that is wasy to read, manage and is reusable later.

Other is reduction of compilation times.

I am currently (as always) coding simulation software in conjuction with OpenCL and we like to keep code so it can be run using float (cl_float) or double (cl_double) types as needed depending on HW capability. Right now this is done using a #define REAL at the beginning of the code, but this is not very elegant. Changing desired precision requires recompiling the application. Since there are no real run-time types, we have to live with this for the time being. Luckily OpenCL kernels are compiled runtime, and a simple sizeof(REAL) allows us to alter the kernel code runtime accordingly.

The much bigger problem is that even though the application is modular, when developing auxiliary classes (such as those that pre-calculate simulation constants) also have to be templated. These classes all appear at least once on the top of the class dependency tree, as the final template class Simulation will have an instance of one of these factory classes, meaning that practically every time I make a minor change to the factory class, the entire software has to be rebuilt. This is very annoying, but I cannot seem to find a better solution.

How to track untracked content?

  1. I removed the .git directories from those new directories (this can create submodule drama. Google it if interested.)
  2. I then ran git rm -rf --cached /the/new/directories
  3. Then I re-added the directories with a git add . from above

Reference URL https://danielmiessler.com/blog/git-modified-untracked/#gs.W0C7X6U

How to validate IP address in Python?

import socket

def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return address.count('.') == 3
    except socket.error:  # not a valid address
        return False

    return True

def is_valid_ipv6_address(address):
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:  # not a valid address
        return False
    return True

How do I echo and send console output to a file in a bat script?

If you don't need the output in real time (i.e. as the program is writing it) you could add

type windows-dir.txt

after that line.

Convert a python UTC datetime to a local datetime using only python standard library?

Here is another way to change timezone in datetime format (I know I wasted my energy on this but I didn't see this page so I don't know how) without min. and sec. cause I don't need it for my project:

def change_time_zone(year, month, day, hour):
      hour = hour + 7 #<-- difference
      if hour >= 24:
        difference = hour - 24
        hour = difference
        day += 1
        long_months = [1, 3, 5, 7, 8, 10, 12]
        short_months = [4, 6, 9, 11]
        if month in short_months:
          if day >= 30:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month in long_months:
          if day >= 31:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month == 2:
          if not year%4==0:
            if day >= 29:
              day = 1
              month += 1
              if month > 12:
                year += 1
          else:
            if day >= 28:
              day = 1
              month += 1
              if month > 12:
                year += 1
      return datetime(int(year), int(month), int(day), int(hour), 00)

How to include file in a bash shell script

Syntax is source <file-name>

ex. source config.sh

script - config.sh

USERNAME="satish"
EMAIL="[email protected]"

calling script -

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

You can learn to include a bash script in another bash script here.

How to resize a VirtualBox vmdk file

Simply you have to follow the following steps:

  1. Power off your machine.
  2. Right click on virtual machine name > Settings > Storage
  3. Click on Controller : SATA > Add Hard Disk.
  4. Choose the new hard disk drive type size and hit create.
  5. Discard the machine state.
  6. Insert Ubuntu Live CD.
  7. Boot from ubuntu live cd.
  8. Open "gparted" (It's installed, not need to installation).
  9. Check if the system see your new created hard disk.
  10. Open Terminal.
  11. Type the following code.
  12. sudo dd if=/dev/sda of=/dev/sdb (The first is the old partition path, the second is the new partition path).
  13. Wait until its finish copying data (This step may take some time according to your host specs).
  14. After finish copying, return to gparted and select refresh devices.
  15. Select the new partition /dev/sdb it must be typical to the old one after doing dd command.
  16. It'll show the expanded space as unlocated data.
  17. Delete Swap partition/Extended partition.
  18. Right click on root partition /dev/sdb > Resize
  19. Allocate the whole space without swap allocation.
  20. Create new extended partition > Choose extended > Create
  21. Create new linux-swap partition > choose linux-swap > Create
  22. Now turn off your running machine.
  23. Right click on machine > settings > Storage.
  24. Eject ubuntu live cd.
  25. Right click on the old hard disk > remove attachment.
  26. Now you can start your vm from the newly created hard disk.
  27. Check the storage by enter df -kh command.
  28. It must show you the new size.

Congratulation, enjoy your free space.
This video will help you: https://youtu.be/ikSIDI535L0

How to detect lowercase letters in Python?

You should use raw_input to take a string input. then use islower method of str object.

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

Just do -

dir(s)

and you will find islower and other attributes of str

How do I delete all the duplicate records in a MySQL table without temp tables

An alternative way would be to create a new temporary table with same structure.

CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0

Then create the primary key in the table.

ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)

Finally copy all records from the original table while ignoring the duplicate records.

INSERT IGNORE INTO temp_table AS SELECT * FROM original_table

Now you can delete the original table and rename the new table.

DROP TABLE original_table
RENAME TABLE temp_table TO original_table

How to get a subset of a javascript object's properties

Destructuring assignment with dynamic properties

This solution not only applies to your specific example but is more generally applicable:

_x000D_
_x000D_
const subset2 = (x, y) => ({[x]:a, [y]:b}) => ({[x]:a, [y]:b});_x000D_
_x000D_
const subset3 = (x, y, z) => ({[x]:a, [y]:b, [z]:c}) => ({[x]:a, [y]:b, [z]:c});_x000D_
_x000D_
// const subset4...etc._x000D_
_x000D_
_x000D_
const o = {a:1, b:2, c:3, d:4, e:5};_x000D_
_x000D_
_x000D_
const pickBD = subset2("b", "d");_x000D_
const pickACE = subset3("a", "c", "e");_x000D_
_x000D_
_x000D_
console.log(_x000D_
  pickBD(o), // {b:2, d:4}_x000D_
  pickACE(o) // {a:1, c:3, e:5}_x000D_
);
_x000D_
_x000D_
_x000D_

You can easily define subset4 etc. to take more properties into account.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

The simplest way to comma-delimit a list?

String delimiter = ",";
StringBuilder sb = new StringBuilder();
for (Item i : list) {
    sb.append(delimiter).append(i);
}
sb.toString().replaceFirst(delimiter, "");

PHPExcel auto size column width

you also need to identify the columns to set dimensions:

foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
$phpExcelObject
        ->getActiveSheet()
        ->getColumnDimension($col)
        ->setAutoSize(true);
}

How do I execute a *.dll file

To Run a .dll file..First find out what are functions it is exporting..Dll files will excecute the functions specified in the Export Category..To know what function it is Exporting refer "filealyzer" Application..It will show you the export function under "PE EXPORT" Category..Notedown the function name-- Then open the command prompt,Type Rundll32 dllname,functionname (dllname--name of your dll) (Functionname-- name of the function you found under the PE Export) Note:Makesure that your command prompt location is your dll file location

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

Case-insensitive search

You can make everything lowercase:

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= (string.toLowerCase()).search((searchstring.toLowerCase()));
alert(result);

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Spring sets the default content-type to octet-stream when the response is missing that field. All you need to do is to add a message converter to fix this.

How to get < span > value?

You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.

See example bellow

_x000D_
_x000D_
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
    <span>1</span>_x000D_
    <span>2</span>_x000D_
    <span>3</span>_x000D_
    <span>4</span>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Looping through JSON with node.js

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

Where can I find the assembly System.Web.Extensions dll?

Your project is mostly likely targetting .NET Framework 4 Client Profile. Check the application tab in your project properties.

This question has a good answer on the different versions: Target framework, what does ".NET Framework ... Client Profile" mean?

How do I get a background location update every n minutes in my iOS application?

To someone else having nightmare figure out this one. I have a simple solution.

  1. look this example from raywenderlich.com-> have sample code, this works perfectly, but unfortunately no timer during background location. this will run indefinitely.
  2. Add timer by using :

    -(void)applicationDidEnterBackground {
    [self.locationManager stopUpdatingLocation];
    
    UIApplication*    app = [UIApplication sharedApplication];
    
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
     self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate
                                                  target:self.locationManager
                                                selector:@selector(startUpdatingLocation)
                                                userInfo:nil
                                                 repeats:YES];
    
    }
    
  3. Just don't forget to add "App registers for location updates" in info.plist.

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

How to bind RadioButtons to an enum?

I would use the RadioButtons in a ListBox, and then bind to the SelectedValue.

This is an older thread about this topic, but the base idea should be the same: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

How to define custom exception class in Java, the easiest way?

If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).

How do I set default terminal to terminator?

Copy-paste the following into your current terminal:

gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"

This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.

AngularJS - Create a directive that uses ng-model

You only need ng-model when you need to access the model's $viewValue or $modelValue. See NgModelController. And in that case, you would use require: '^ngModel'.

For the rest, see Roys answer.

How to call a parent class function from derived class function?

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
public:
    void foo();
};

class right {
public:
    void foo();
};

class bottom : public left, public right {
public:
    void foo()
    {
        //base::foo();// ambiguous
        left::foo();
        right::foo();

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls b.foo() from 'left'
        b.right::foo();  // call b.foo() from 'right'
    }
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
};

Sort an array in Java

Java 8 provides the option of using streams which can be used to sort int[] array as:

int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2

As mentioned in doc for parallelSort :

The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.

So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort simply calls sequential sort algorithm.

Just in case we want to reverse sort the integer array we can make use of comparator as:

int[] reverseSorted = IntStream.of(array).boxed()
                        .sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();

Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

i had the same problem and was already using the code in the selected answer. this link was the answer for me; maybe for others also.

How to disable navigation on WinForm with arrows in C#?

What’s the best way to check if a file exists in C++? (cross platform)

Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.

It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.

Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html

replace NULL with Blank value or Zero in sql server

Different ways to replace NULL in sql server

Replacing NULL value using:

1. ISNULL() function

2. COALESCE() function

3. CASE Statement

SELECT Name as EmployeeName, ISNULL(Bonus,0) as EmployeeBonus from tblEmployee

SELECT Name as EmployeeName, COALESCE(Bonus, 0) as EmployeeBonus 
FROM tblEmployee

SELECT Name as EmployeeName, CASE WHEN Bonus IS NULL THEN 0 
ELSE Bonus  END as EmployeeBonus 
FROM  tblEmployee

Run git pull over all subdirectories

My humble construction that

  • shows the current path (using python, convenient and just works, see How to get full path of a file?)
  • looks directly for .git subfolder: low chance to emit a git command in a non-git subfolder
  • gets rid of some warnings of find

as follow:

find . \
    -maxdepth 2 -type d \
    -name ".git" \
    -execdir python -c 'import os; print(os.path.abspath("."))' \; \
    -execdir git pull \;

Of course, you may add other git commands with additional -execdir options to find, displaying the branch for instance:

find . \
    -maxdepth 2 -type d \
    -name ".git" \
    -execdir python -c 'import os; print(os.path.abspath("."))' \; \
    -execdir git branch \;
    -execdir git pull \;

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

Actually, you can achieve this pretty easy. Simply specify the line height as a number:

<p style="line-height:1.5">
    <span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
    <span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>

The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.

For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.

Stopping an Android app from console

Edit: Long after I wrote this post and it was accepted as the answer, the am force-stop command was implemented by the Android team, as mentioned in this answer.

Alternatively: Rather than just stopping the app, since you mention wanting a "clean slate" for each test run, you can use adb shell pm clear com.my.app.package, which will stop the app process and clear out all the stored data for that app.


If you're on Linux:
adb shell ps | grep com.myapp | awk '{print $2}' | xargs adb shell kill

That will only work for devices/emulators where you have root immediately upon running a shell. That can probably be refined slightly to call su beforehand.

Otherwise, you can do (manually, or I suppose scripted):
pc $ adb -d shell
android $ su
android # ps
android # kill <process id from ps output>

Insert current date in datetime format mySQL

set the type of column named dateposted as DATETIME and run the following query:

INSERT INTO table (`dateposted`) VALUES (CURRENT_TIMESTAMP)

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Here's an approach that combines atomic directory locking with a check for stale lock via PID and restart if stale. Also, this does not rely on any bashisms.

#!/bin/dash

SCRIPTNAME=$(basename $0)
LOCKDIR="/var/lock/${SCRIPTNAME}"
PIDFILE="${LOCKDIR}/pid"

if ! mkdir $LOCKDIR 2>/dev/null
then
    # lock failed, but check for stale one by checking if the PID is really existing
    PID=$(cat $PIDFILE)
    if ! kill -0 $PID 2>/dev/null
    then
       echo "Removing stale lock of nonexistent PID ${PID}" >&2
       rm -rf $LOCKDIR
       echo "Restarting myself (${SCRIPTNAME})" >&2
       exec "$0" "$@"
    fi
    echo "$SCRIPTNAME is already running, bailing out" >&2
    exit 1
else
    # lock successfully acquired, save PID
    echo $$ > $PIDFILE
fi

trap "rm -rf ${LOCKDIR}" QUIT INT TERM EXIT


echo hello

sleep 30s

echo bye

can not find module "@angular/material"

Follow these steps to begin using Angular Material.

Step 1: Install Angular Material

npm install --save @angular/material

Step 2: Animations

Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the @angular/animations module and include the BrowserAnimationsModule in your app.

npm install --save @angular/animations

Then

import {BrowserAnimationsModule} from '@angular/platform browser/animations';

@NgModule({
...
  imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }

Step 3: Import the component modules

Import the NgModule for each component you want to use:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
 })
 export class PizzaPartyAppModule { }

be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {MdCardModule} from '@angular/material';
@NgModule({
    declarations: [
        AppComponent,
        HeaderComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        MdCardModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Include a theme

Including a theme is required to apply all of the core and theme styles to your application.

To get started with a prebuilt theme, include the following in your app's index.html:

<link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">

How to write a simple Html.DropDownListFor()?

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

"Unable to find remote helper for 'https'" during git clone

For those using git with Jenkins under a windows system, you need to configure the location of git.exe under: Manage Jenkins => Global Tool Configuration => Git => Path to Git executable and fill-in the path to git.exe, for example; C:\Program Files\Git\bin\git.exe

What is causing the error `string.split is not a function`?

In clausule if, use (). For example:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...

Add border-bottom to table row <tr>

Display the row as a block.

tr {
    display: block;
    border-bottom: 1px solid #000;
}

and to display alternate colors simply:

tr.oddrow {
    display: block;
    border-bottom: 1px solid #F00;
}

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Execute bash script from URL

You can also do this:

wget -O - https://raw.github.com/luismartingil/commands/master/101_remote2local_wireshark.sh | bash

How do I set log4j level on the command line?

With Log4j2, this can be achieved using the following utility method added to your code.

private static void setLogLevel() {
  if (Boolean.getBoolean("log4j.debug")) {
    Configurator.setLevel(System.getProperty("log4j.logger"), Level.DEBUG);
  }
}

You need these imports

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;

Now invoke the setLogLevel method in your main() or whereever appropriate and pass command line params -Dlog4j.logger=com.mypackage.Thingie and -Dlog4j.debug=true.

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

on the BlueStacks emulator worked for me the following solution

Go to ”Settings” -> “Applications” -> “Manage Applications” and select “All

Go to “Google Play Services Framework” and select “Clear Data” & “Clear Cache” to remove all the data.

Go to “Google Play Store” and Select “Clear Data” & “Clear Cache” to remove all the data regarding Google Play Store.

Go to “Settings” -> “Accounts” -> “Google” -> Select “Your Account

Go to “Menu” and Select “Remove Account”.

Now “Restart” your mobile device.

Go to “Menu” and “Add Your Account”.

and try to perform update or download.

Get the string representation of a DOM node

You can simply use outerHTML property over the element. It will return what you desire.

Let's create a function named get_string(element)

_x000D_
_x000D_
var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

function get_string(element) {
 console.log(element.outerHTML);
}

get_string(el); // your desired output
_x000D_
_x000D_
_x000D_ enter image description here

How to add include path in Qt Creator?

If you are using qmake, the standard Qt build system, just add a line to the .pro file as documented in the qmake Variable Reference:

INCLUDEPATH += <your path>

If you are using your own build system, you create a project by selecting "Import of Makefile-based project". This will create some files in your project directory including a file named <your project name>.includes. In that file, simply list the paths you want to include, one per line. Really all this does is tell Qt Creator where to look for files to index for auto completion. Your own build system will have to handle the include paths in its own way.

As explained in the Qt Creator Manual, <your path> must be an absolute path, but you can avoid OS-, host- or user-specific entries in your .pro file by using $$PWD which refers to the folder that contains your .pro file, e.g.

INCLUDEPATH += $$PWD/code/include

Comparing two dataframes and getting the differences

Hope this would be useful to you. ^o^

df1 = pd.DataFrame({'date': ['0207', '0207'], 'col1': [1, 2]})
df2 = pd.DataFrame({'date': ['0207', '0207', '0208', '0208'], 'col1': [1, 2, 3, 4]})
print(f"df1(Before):\n{df1}\ndf2:\n{df2}")
"""
df1(Before):
   date  col1
0  0207     1
1  0207     2

df2:
   date  col1
0  0207     1
1  0207     2
2  0208     3
3  0208     4
"""

old_set = set(df1.index.values)
new_set = set(df2.index.values)
new_data_index = new_set - old_set
new_data_list = []
for idx in new_data_index:
    new_data_list.append(df2.loc[idx])

if len(new_data_list) > 0:
    df1 = df1.append(new_data_list)
print(f"df1(After):\n{df1}")
"""
df1(After):
   date  col1
0  0207     1
1  0207     2
2  0208     3
3  0208     4
"""

How do I fix 'ImportError: cannot import name IncompleteRead'?

On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in the documentation

wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

That's an OK solution for a development environment.

How can I delete using INNER JOIN with SQL Server?

Another way is using CTE:

;WITH cte
     AS (SELECT *
         FROM   workrecord2 w
         WHERE  EXISTS (SELECT 1
                        FROM   employee e
                        WHERE  employeerun = employeeno
                               AND company = '1'
                               AND date = '2013-05-06'))
DELETE FROM cte

Note: We cannot use JOIN inside CTE when you want to delete.

Grid of responsive squares

I use this solution for responsive boxes of different rations:

HTML:

<div class="box ratio1_1">
  <div class="box-content">
            ... CONTENT HERE ...
  </div>
</div>

CSS:

.box-content {
  width: 100%; height: 100%;
  top: 0;right: 0;bottom: 0;left: 0;
  position: absolute;
}
.box {
  position: relative;
  width: 100%;
}
.box::before {
    content: "";
    display: block;
    padding-top: 100%; /*square for no ratio*/
}
.ratio1_1::before { padding-top: 100%; }
.ratio1_2::before { padding-top: 200%; }
.ratio2_1::before { padding-top: 50%; }
.ratio4_3::before { padding-top: 75%; }
.ratio16_9::before { padding-top: 56.25%; }

See demo on JSfiddle.net

How to print all key and values from HashMap in Android?

Java 8

map.entrySet().forEach(System.out::println);

Sort objects in ArrayList by date?

With introduction of Java 1.8, streams are very useful in solving this kind of problems:

Comparator <DateTime> myComparator = (arg1, arg2) 
                -> {
                    if(arg1.lt(arg2)) 
                       return -1;
                    else if (arg1.lteq(arg2))
                       return 0;
                    else
                       return 1;
                   };

ArrayList<DateTime> sortedList = myList
                   .stream()
                   .sorted(myComparator)
                   .collect(Collectors.toCollection(ArrayList::new));

$(this).val() not working to get text from span using jquery

.val() is for input elements, use .html() instead

How can I add some small utility functions to my AngularJS application?

The easiest way to add utility functions is to leave them at the global level:

function myUtilityFunction(x) { return "do something with "+x; }

Then, the simplest way to add a utility function (to a controller) is to assign it to $scope, like this:

$scope.doSomething = myUtilityFunction;

Then you can call it like this:

{{ doSomething(x) }}

or like this:

ng-click="doSomething(x)"

EDIT:

The original question is if the best way to add a utility function is through a service. I say no, if the function is simple enough (like the isNotString() example provided by the OP).

The benefit of writing a service is to replace it with another (via injection) for the purpose of testing. Taken to an extreme, do you need to inject every single utility function into your controller?

The documentation says to simply define behavior in the controller (like $scope.double): http://docs.angularjs.org/guide/controller

DLL Load Library - Error Code 126

This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.

What does Java option -Xmx stand for?

Max heap Usage for the application is is 1024 MB

UTF-8: General? Bin? Unicode?

In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.

Here is the difference:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

Quoted from: http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

For more detailed explanation, please read the following post from MySQL forums: http://forums.mysql.com/read.php?103,187048,188748

As for utf8_bin: Both utf8_general_ci and utf8_unicode_ci perform case-insensitive comparison. In constrast, utf8_bin is case-sensitive (among other differences), because it compares the binary values of the characters.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

Wait some seconds without blocking UI execution

i really disadvise you against using Thread.Sleep(2000), because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.

I recommend to use a C# Timer instead of Thread.Sleep(). Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); method.

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

How to capture the android device screen content?

For newer Android platforms, one can execute a system utility screencap in /system/bin to get the screenshot without root permission. You can try /system/bin/screencap -h to see how to use it under adb or any shell.

By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.

IE8 css selector

OK so, it isn't css hack, but out of frustration for not being able to find ways to target ie8 from css, and due to policy of not having ie specific css files, I had to do following, which I assume someone else might find useful:

if (jQuery.browser.version==8.0) {
   $(results).css({
         'left':'23px',
         'top':'-253px'
      });
}

How can I format bytes a cell in Excel as KB, MB, GB etc?

I use CDH hadoop and when I export excel report, I have two problems;

1) convert Linux date to excel date,
For that, add an empty column next to date column lets say the top row is B4, paste below formula and drag the BLACK "+" all the way to your last day at the end of the column. Then hide the original column

=(((B4/1000/60)/60)/24)+DATE(1970|1|1)+(-5/24)

2) Convert disk size from byte to TB, GB, and MB
the best formula for that is this

[>999999999999]# ##0.000,,,," TB";[>999999999]# ##0.000,,," GB";# ##0.000,," MB"

it will give you values with 3 decimals just format cells --> Custom and paste the above code there

VARCHAR to DECIMAL

You are missing the fact that 6.999,50 is not a valid decimal. You can't have a comma and a decimal point in a decimal value surely? What number is it supposed to be?

Assuming your locale specifies . as grouping and , as decimal separator: To remove the grouping digits:

SELECT CONVERT(decimal(11,2), REPLACE('6.999,50', '.', ''))

will yield 6999,50 as a decimal

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

Copy files without overwrite

I just want to clarify something from my own testing.

@Hydrargyrum wrote:

  • /XN excludes existing files newer than the copy in the source directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the source directory. Robocopy normally overwrites those.

This is actually backwards. XN does "eXclude Newer" files but it excludes files that are newer than the copy in the destination directory. XO does "eXclude Older", but it excludes files that are older than the copy in the destination directory.

Of course do your own testing as always.

How do I clear a C++ array?

Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize

std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });

You can do ints too e.g.

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

or just

std::generate(v.begin(), v.end(), [] (){ return 0; });

but I imagine std::fill is faster for the simplest case

How do I find all files containing specific text on Linux?

Do the following:

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
  • -e is the pattern used during the search

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching:

  • This will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
  • This will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
  • For directories it's possible to exclude one or more directories using the --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

This works very well for me, to achieve almost the same purpose like yours.

For more options check man grep.

What is the difference between os.path.basename() and os.path.dirname()?

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/2/library/os.path.html#os.path.basename

Check if a process is running or not on Windows with Python

Long Codes Are Not Necessary To Find Out Whether The App Is Running Or Not This is for those who use TK in PYTHON and For Those Who Are Beginner In Python

For Tk

from tkinter import *
import os

root = Tk()

def killer(appname):
    a = os.system(f'taskkill /PID '+appname+'.exe /F')
    if a==1 or a==0:
        l1.config(text=appname+' Has Been Killed Successfully')
    else:
        l1.config(text=appname+" Is Not Running")

Button(text="Kill VLC MEIDA PLAYER",command=lambda:(killer('VLC'))).pack()
Button(text="Kill CMD",command=lambda:(killer('CMD'))).pack()
Button(text="Kill Notepad",command=lambda:(killer('NOTEPAD'))).pack()

l1 = Label(text="")
l1.pack()

root.mainloop()

For Python Console

a = os.system('taskkill /PID cmd.exe /F') 
# Here Insted Of Cmd You Can Give Your Program Name
if a==0 or a==1:
    print('Cmd Is Running And Is Killed')
else:
    print('CMD is Not Running')
inn = input('Press Any Key To Continue')
# Insted Of Cmd.exe You Can Give Your Program Name Such As VLC.exe

Thank You

How to replace DOM element in place using Javascript?

by using replaceChild():

<html>
<head>
</head>
<body>
  <div>
    <a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
  </div>
<script type="text/JavaScript">
  var myAnchor = document.getElementById("myAnchor");
  var mySpan = document.createElement("span");
  mySpan.innerHTML = "replaced anchor!";
  myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>

How can I execute a PHP function in a form action?

I'm not sure I understand what you are trying to achieve as we don't have what username() is supposed to return but you might want to try something like that. I would also recommend you don't echo whole page and rather use something like that, it's much easier to read and maintain:

<?php
require_once ( 'username.php' );
if (isset($_POST)) {
  $textfield = $_POST['textfield']; // this will get you what was in the
                                    // textfield if the form was submitted
}
?>

<form name="form1" method="post" action="<?php echo($_SERVER['PHP_SELF']) ?">
  <p>Your username is: <?php echo(username()) ?></p>
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>

This will post the results in the same page. So first time you display the page, only the empty form is shown, if you press on submit, the textfield field will be in the $textfield variable and you can display it again as you want.

I don't know if the username() function was supposed to return you the URL of where you should send the results but that's what you'd want in the action attribute of your form. I've put the result down in a sample paragraph so you see how you can display the result. See the "Your username is..." part.


// Edit:

If you want to send the value without leaving the page, you want to use AJAX. Do a search on jQuery on StackOverflow or on Google.

You would probably want to have your function return the username instead of echo it though. But if you absolutely want to echo it from the function, just call it like that <?php username() ?> in your HTML form.

I think you will need to understand the flow of the client-server process of your pages before going further. Let's say that the sample code above is called form.php.

  1. Your form.php is called.
  2. The form.php generates the HTML and is sent to the client's browser.
  3. The client only sees the resulting HTML form.
  4. When the user presses the button, you have two choices: a) let the browser do its usual thing so send the values in the form fields to the page specified in action (in this case, the URL is defined by PHP_SELF which is the current page.php). Or b) use javascript to push this data to a page without refreshing the page, this is commonly called AJAX.
  5. A page, in your case, it could be changed to username.php, will then verify against the database if the username exists and then you want to regenerate HTML that contains the values you need, back to step 1.

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

Log to the base 2 in python

http://en.wikipedia.org/wiki/Binary_logarithm

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res

PHP-FPM and Nginx: 502 Bad Gateway

For anyone else struggling to get to the bottom of this, I tried adjusting timeouts as suggested as I didn't want to stop using Unix sockets...after lots of troubleshooting and not much to go on I found that this issue was being caused by the APC extension that I'd enabled in php-fpm a few months back. Disabling this extension resolved the intermittent 502 errors, easiest way to do this was by commenting out the following line :

;extension = apc.so

This did the trick for me!

Finish an activity from another activity

  1. Make your activity A in manifest file: launchMode = "singleInstance"

  2. When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.

  3. When the user clicks modify, call the new Intent or simply finish activity B.

FIRST WAY

In your first activity, declare one Activity object like this,

public static Activity fa;
onCreate()
{
    fa = this;
}

now use that object in another Activity to finish first-activity like this,

onCreate()
{
    FirstActivity.fa.finish();
}

SECOND WAY

While calling your activity FirstActivity which you want to finish as soon as you move on, You can add flag while calling FirstActivity

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

But using this flag the activity will get finished evenif you want it not to. and sometime onBack if you want to show the FirstActivity you will have to call it using intent.

When to use Interface and Model in TypeScript / Angular

As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

rawQuery(query, selectionArgs)

Maybe this can help you

Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0) 
{               
    c.moveToFirst();
    do {
        id[i] = c.getInt(c.getColumnIndex("field_name"));
        i++;
    } while (c.moveToNext());
    c.close();
}

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.

scale fit mobile web content using viewport meta tag

Adding style="width:100%;max-width:640px" to the image tag will scale it up to the viewport width, i.e. for larger windows it will look fixed width.

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

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

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

PostgreSQL DISTINCT ON with different ORDER BY

It can also be solved using the following query along with other answers.

WITH purchase_data AS (
        SELECT address_id, purchased_at, product_id,
                row_number() OVER (PARTITION BY address_id ORDER BY purchased_at DESC) AS row_number
        FROM purchases
        WHERE product_id = 1)
SELECT address_id, purchased_at, product_id
FROM purchase_data where row_number = 1

How to increase the Java stack size?

The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

public class TT {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "TT", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("true recursion level was " + level);
                    System.err.println("reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();
        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

Bash: Syntax error: redirection unexpected

Does your script reference /bin/bash or /bin/sh in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh then your script will be using a different shell than you expect. Dash does not have the <<< redirection operator.

Truncate string in Laravel blade templates

This works on Laravel 5:

{!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}

Run react-native on android emulator

Had a similar problem. I updated my Genymotion and my android SDK's/libraries/dependencies and all seemed to work. To update my SDK's I used android sdk manager {ANDROID_SDK_FOLDER}/tools/android sdk

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

change background image in body

Just set an onload function on the body:

<body onload="init()">

Then do something like this in javascript:

function init() {
  var someimage = 'changableBackgroudImage';
  document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}

You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.

How do you find out the type of an object (in Swift)?

If you get an "always true/fails" warning you may need to cast to Any before using is

(foo as Any) is SomeClass

How to avoid Python/Pandas creating an index in a saved csv?

There are two ways to handle the situation where we do not want the index to be stored in csv file.

  1. As others have stated you can use index=False while saving your
    dataframe to csv file.

    df.to_csv('file_name.csv',index=False)

  2. Or you can save your dataframe as it is with an index, and while reading you just drop the column unnamed 0 containing your previous index.Simple!

    df.to_csv(' file_name.csv ')
    df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)

Unable to make the session state request to the session state server

If you need to change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection to 1, remember to restart the ASP.net state service after you change the parameter.

How can I add a line to a file in a shell script?

This adds custom text at the beginning of your file:

echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

let's consider the final output rendered to the user of what we want to achieve: a padded textarea with both a border and a padding, which characteristics are that being clicked they pass the focus to our textarea, and the advantage of an automatic 100% width typical of block elements.

The best approach in my opinion is to use low level solutions as far as possible, to reach the maximum browsers support. In this case the only HTML could work fine, avoiding the use of Javascript (which anyhow we all love).

The LABEL tag comes in our help because has such behaviour and is allowed to contain the input elements it must address to. Its default style is the one of inline elements, so, giving to the label a block display style we can avail ourselves of the automatic 100% width including padding and borders, while the inner textarea has no border, no padding and a 100% width.

Taking a look at the W3C specifics other advantages we may notice are:

  • no "for" attribute is needed: when a LABEL tag contains the target input, it automatically focuses the child input when clicked;
  • if an external label for the textarea has already been designed, no conflicts occur, since a given input may have one or more labels.

See W3C specifics for more detailed information.

Simple example:

_x000D_
_x000D_
.container { _x000D_
  width: 400px; _x000D_
  border: 3px _x000D_
  solid #f7c; _x000D_
  }_x000D_
.textareaContainer {_x000D_
 display: block;_x000D_
 border: 3px solid #38c;_x000D_
 padding: 10px;_x000D_
  }_x000D_
textarea { _x000D_
  width: 100%; _x000D_
  margin: 0; _x000D_
  padding: 0; _x000D_
  border-width: 0; _x000D_
  }
_x000D_
<body>_x000D_
<div class="container">_x000D_
 I am the container_x000D_
 <label class="textareaContainer">_x000D_
  <textarea name="text">I am the padded textarea with a styled border...</textarea>_x000D_
 </label>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

The padding and border of the .textareaContainer elements are the ones we want to give to the textarea. Try editing them to style it as you want. I gave large and visible padding and borders to the .textareaContainer element to let you see their behaviour when clicked.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

How to use radio buttons in ReactJS?

Make the radio component as dumb component and pass props to from parent.

import React from "react";

const Radiocomponent = ({ value, setGender }) => ( 
  <div onChange={setGender.bind(this)}>
    <input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
    <input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
  </div>
);

export default Radiocomponent;

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

How to call base.base.method()?

The answer (which I know is not what you're looking for) is:

class SpecialDerived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.

EDIT:

Your edit works, but I think I would use something like this:

class Derived : Base
{
    protected bool _useBaseSay = false;

    public override void Say()
    {
        if(this._useBaseSay)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Of course, in a real implementation, you might do something more like this for extensibility and maintainability:

class Derived : Base
{
    protected enum Mode
    {
        Standard,
        BaseFunctionality,
        Verbose
        //etc
    }

    protected Mode Mode
    {
        get; set;
    }

    public override void Say()
    {
        if(this.Mode == Mode.BaseFunctionality)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Then, derived classes can control their parents' state appropriately.

How to reload/refresh an element(image) in jQuery

It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());

Can I check if Bootstrap Modal Shown / Hidden?

Use hasClass('in'). It will return true if modal is in OPEN state.

E.g:

if($('.modal').hasClass('in')){
   //Do something here
}

Twitter bootstrap collapse: change display of toggle button

You do like this. the function return the old text.

$('button').click(function(){ 
        $(this).text(function(i,old){
            return old=='Read More' ?  'Read Less' : 'Read More';
        });
    });

How can I generate a tsconfig.json file?

For those who have TypeScript installed as a local package (and possibly as a dev dependency) via:

$ npm install typescript --save-dev

...and who have added tsc script to package.json:

"scripts": {
   ...
   "tsc": "tsc"
},

You can call tsc --init via npm:

$ npm run tsc -- --init 

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

I had the same issue for another secure page when using wget or file_get_contents. A lot of research (including some of the responses on this question) resulted in a simple solution - installing Curl and PHP-Curl - If I've understood correctly, Curl has the Root CA for Comodo which resolved the issue

Install Curl and PHP-Curl addon, then restart Apache

sudo apt-get install curl
sudo apt-get install php-curl
sudo /etc/init.d/apache2 reload

All now working.

Redirect with CodeIgniter

If you want to redirect previous location or last request then you have to include user_agent library:

$this->load->library('user_agent');

and then use at last in a function that you are using:

redirect($this->agent->referrer());

its working for me.

Is there a way to make text unselectable on an HTML page?

The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.

<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>

Length of string in bash

Here is couple of ways to calculate length of variable :

echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'

and to set the result in another variable just assign above command with back quote into another variable as following:

otherVar=`echo -n $VAR | wc -m`   
echo $otherVar

http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html

Using jQuery how to get click coordinates on the target element

In percentage :

$('.your-class').click(function (e){
    var $this = $(this); // or use $(e.target) in some cases;
    var offset = $this.offset();
    var width = $this.width();
    var height = $this.height();
    var posX = offset.left;
    var posY = offset.top;
    var x = e.pageX-posX;
        x = parseInt(x/width*100,10);
        x = x<0?0:x;
        x = x>100?100:x;
    var y = e.pageY-posY;
        y = parseInt(y/height*100,10);
        y = y<0?0:y;
        y = y>100?100:y;
    console.log(x+'% '+y+'%');
});

ImportError: cannot import name NUMPY_MKL

From your log its clear that numpy package is missing. As mention in the PyPI package:

The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array manipulation.

So, try installing numpy package for python as you did with scipy.

Seaborn Barplot - Displaying Values

Works with single ax or with matrix of ax (subplots)

from matplotlib import pyplot as plt
import numpy as np

def show_values_on_bars(axs):
    def _show_on_single_plot(ax):        
        for p in ax.patches:
            _x = p.get_x() + p.get_width() / 2
            _y = p.get_y() + p.get_height()
            value = '{:.2f}'.format(p.get_height())
            ax.text(_x, _y, value, ha="center") 

    if isinstance(axs, np.ndarray):
        for idx, ax in np.ndenumerate(axs):
            _show_on_single_plot(ax)
    else:
        _show_on_single_plot(axs)

fig, ax = plt.subplots(1, 2)
show_values_on_bars(ax)

WPF Datagrid Get Selected Cell Value

I was in such situation .. and found This:

int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);

And make sure to treat custom columns' templates

How can I escape double quotes in XML attributes values?

A double quote character (") can be escaped as &quot;, but here's the rest of the story...

Double quote character must be escaped in this context:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need not be escaped in most contexts:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

In Python, how do you convert seconds since epoch to a `datetime` object?

Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

The endpoint reference (EPR) for the Operation not found is

It seems don't find wsdl file..
I've solved adding wsdlLocation parameter at javax.jws.WebService annotation

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Get loop counter/index using for…of syntax in JavaScript

Answer Given by rushUp Is correct but this will be more convenient

for (let [index, val] of array.entries() || []) {
   // your code goes here    
}

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

How to set and reference a variable in a Jenkinsfile

We got around this by adding functions to the environment step, i.e.:

environment {
    ENVIRONMENT_NAME = defineEnvironment() 
}
...
def defineEnvironment() {
    def branchName = "${env.BRANCH_NAME}"
    if (branchName == "master") {
        return 'staging'
    }
    else {
        return 'test'
    }
}

How to retrieve the LoaderException property?

Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:

($exception).LoaderExceptions

Python "extend" for a dictionary

You can also use python's collections.Chainmap which was introduced in python 3.3.

from collections import Chainmap
c = Chainmap(a, b)
c['a'] # returns 1

This has a few possible advantages, depending on your use-case. They are explained in more detail here, but I'll give a brief overview:

  • A chainmap only uses views of the dictionaries, so no data is actually copied. This results in faster chaining (but slower lookup)
  • No keys are actually overwritten so, if necessary, you know whether the data comes from a or b.

This mainly makes it useful for things like configuration dictionaries.

How to check if string contains Latin characters only?

I'm surprised that the answers here got so many upvotes when none of them really answer the question. Here's how to make sure that ONLY LATIN characters are in a given string.

const hasOnlyLetters = !!value.match(/^[a-z]*$/i);

The !! takes transforms something that's not boolean into a boolean value. (It's exactly the same as applying a ! twice, and in fact you can use as many ! as you'd like to toggle the truthiness multiple times.)

As for the RegEx, here's the breakdown.

  • /.../i The delimiter is a / and the i means to assess the statement in a case-insensitive fashion.
  • ^...$ The ^ means to look at the very beginning of a string. The $ means to look at the end of the string, and when used together, it means to consider the entire string. You can add more to the RegEx outside of these boundaries for things like appending/prepending a required suffix or prefix.
  • [a-z]*This part says to look for all lowercase letters. (The case-insensitive modifier means that we don't need to look at uppercase letters, too.) The * at the end says that we should match whats in the brackets any number of times. That way "abc" will match instead of just "a" or "b", and so forth.

Namespace not recognized (even though it is there)

Crazy. I know.

Tried all options here. Restarting, cleaning, manually checking in generated DLLs (this is invaluable to understanding if it's actually yourself that messed up).

I got it to work by setting the Verbosity of MSBuild to "Detailed" in Options.

Check a collection size with JSTL

use ${fn:length(companies) > 0} to check the size. This returns a boolean

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

jquery draggable: how to limit the draggable area?

Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV

buildDraggable = function() {
    $( "#handle" ).draggable({
    containment: '#thumbnail',
    drag: function(event) {
        var top = $(this).position().top;
        var left = $(this).position().left;

        ICZoom.panImage(top, left);
    },
});

How to resolve symbolic links in a shell script

To work around the Mac incompatibility, I came up with

echo `php -r "echo realpath('foo');"`

Not great but cross OS

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

Global Angular CLI version greater than local version

To answer one of the questions, it is necessary to have both a global and local install for the tools to work.

If you try to run ng serve on an application without the local install of the CLI (global install only), you will get the following error.

You have to be inside an Angular CLI project in order to use the serve command.

It will also print this message:

Please take the following steps to avoid issues:
"npm install --save-dev @angular/cli@latest"

Run that npm command to update the CLI locally, and avoid the warning that you are getting.

Other question: It looks like they do not have to be in sync, but it's probably best that they are in order to avoid any unusual behavior with the tool, or any inconsistencies with the code the tool generates.

Why do we need both the global install, and a local install?

The global install is needed to start a new application. The ng new <app-name> command is run using the global installation of the CLI. In fact, if you try to run ng new while inside the folder structure of an existing CLI application, you get this lovely error:

You cannot use the new command inside an Angular CLI project.

Other commands that can be run from the global install are ng help, ng get/set with the --global option, ng version, ng doc, and ng completion.

The local install of the CLI is used after an application has been built. This way, when new versions of the CLI are available, you can update your global install, and not affect the local install. This is good for the stability of a project. Most ng commands only make sense with the local version, like lint, build and serve, etc.

According to the CLI GitHub readme, to update the CLI you must update the global and local package. However, I have used the CLI where the global and local version vary without any trouble so far. If I ever run across an error related to having the global and local CLI versions out of sync, I will post that here.

How can I see what I am about to push with git?

After git commit -m "{your commit message}", you will get a commit hash before the push. So you can see what you are about to push with git by running the following command:

git diff origin/{your_branch_name} commit hash

e.g: git diff origin/master c0e06d2

Declare an empty two-dimensional array in Javascript?

ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))       

_x000D_
_x000D_
let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
);
_x000D_
_x000D_
_x000D_

Can't run Curl command inside my Docker Container

If you are using an Alpine based image, you have to

RUN
... \
apk add --no-cache curl \
curl ...
...

How to increase font size in a plot in R?

I came across this when I wanted to make the axis labels smaller, but leave everything else the same size. The command that worked for me, was to put:

par(cex.axis=0.5)

Before the plot command. Just remember to put:

par(cex.axis=1.0)

After the plot to make sure that the fonts go back to the default size.

Create PDF from a list of images

Ready-to-use solution that converts all PNG in the current folder to a PDF, inspired by @ilovecomputer's answer:

import glob, PIL.Image
L = [PIL.Image.open(f) for f in glob.glob('*.png')]
L[0].save('out.pdf', "PDF" ,resolution=100.0, save_all=True, append_images=L[1:])

Nothing else than PIL is needed :)

C# : changing listbox row color?

First use this Namespace:

using System.Drawing;

Add this anywhere on your form:

listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;

Here is the Event Handler:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
     e.DrawBackground();

     Graphics g = e.Graphics;
     g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
     ListBox lb = (ListBox)sender;
     g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));

     e.DrawFocusRectangle();
}

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

If you have @oneToOne mapping set to FetchType.LAZY and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.

Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.

Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects

How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

How do I pass a value from a child back to the parent form?

Use public property of child form

frmOptions {
     public string Result; }

frmMain {
     frmOptions.ShowDialog(); string r = frmOptions.Result; }

Use events

frmMain {
     frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);
     frmOptions.ShowDialog(); }

Use public property of main form

frmOptions {
     public frmMain MainForm; MainForm.Result = "result"; }

frmMain {
     public string Result;
     frmOptions.MainForm = this;
     frmOptions.ShowDialog();
     string r = this.Result; }

Use object Control.Tag; This is common for all controls public property which can contains a System.Object. You can hold there string or MyClass or MainForm - anything!

frmOptions {
     this.Tag = "result": }
frmMain {
     frmOptions.ShowDialog();
     string r = frmOptions.Tag as string; }

How to write a cron that will run a script every day at midnight?

from the man page

linux$ man -S 5 crontab

   cron(8) examines cron entries once every minute.

   The time and date fields are:

          field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sun, or use names)
   ...
   # run five minutes after midnight, every day
   5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
   ...

It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.

   # Run once after reboot.
   @reboot         /usr/local/sbin/run_only_once_after_reboot.sh

You can also use this trick to run your cron job multiple times per minute.

   # Run every minute at 0, 20, and 40 second intervals
   * * * * *       sleep 00; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 20; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 40; /usr/local/sbin/run_3times_per_minute.sh

To add a cron job, you can do one of three things:

  1. add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).

    • edit a user's crontab as root with crontab -e -u <username>
    • or edit the current user's crontab with just crontab -e
    • You can set the editor with the EDITOR environment variable
      • env EDITOR=nano crontab -e -u <username>
      • or set the value of EDITOR for your entire shell session
        1. export EDITOR=vim
        2. crontab -e
    • Make scripts executable with chmod a+x <file>


  1. create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly directories

    • anacron /etc/cron.*ly directories:
      • /etc/cron.daily
      • /etc/cron.hourly
      • /etc/cron.monthly
      • /etc/cron.weekly
    • as in:
      • /etc/cron.daily/script_runs_daily.sh
      • chmod a+x /etc/cron.daily/script_runs_daily.sh -- make it executable
    • See also the anacron man page: man anacron
    • Make scripts executable with chmod a+x <file>
    • When do these cron.*ly script run?
      • For RHEL/CentOS 5.x, they are configured in /etc/crontab or /etc/anacrontab to run at a set time
      • RHEL/CentOS 6.x+ and Fedora 17+ Linux systems only define this in /etc/anacrontab, and define cron.hourly in /etc/cron.d/0hourly


  1. Or, One can create system crontables in /etc/cron.d.

    • The previously described crontab syntax (with additionally providing a user to execute each job as) is put into a file, and the file is dropped into the /etc/cron.d directory.
    • These are easy to manage in system packaging (e.g. RPM packages), so may usually be application specific.
    • The syntax difference is that a user must be specified for the cron job after the time/date fields and before the command to execute.
    • The files added to /etc/cron.d do not need to be executable.
    • Here is an example job that is executed as the user someuser, and the use of /bin/bash as the shell is forced.


   File: /etc/cron.d/myapp-cron
   # use /bin/bash to run commands, no matter what /etc/passwd says
   SHELL=/bin/bash
   # Execute a nightly (11:00pm) cron job to scrub application records
   00 23 * * * someuser /opt/myapp/bin/scrubrecords.php

Text overwrite in visual studio 2010

Ran into this issue with Parallels and VS 2013. Command + Insert also fixed it in my setup, in addition to the accepted answer. On my Windows USB keyboard Command == WindowsKey.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:

(You should back up your project before doing this)

1) I deleted all the appcompat layout folders (ex: /res/layout-v11).

2) Solved the problems that arose from that, usually an error in menu.xml

3) Back to main project and add appcompat library, clean, and everything works!

What is the difference between XML and XSD?

XSD:
XSD (XML Schema Definition) specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Xml:
XML was designed to describe data.It is independent from software as well as hardware.
It enhances the following things.
-Data sharing.
-Platform independent.
-Increasing the availability of Data.

Differences:

  1. XSD is based and written on XML.

  2. XSD defines elements and structures that can appear in the document, while XML does not.

  3. XSD ensures that the data is properly interpreted, while XML does not.

  4. An XSD document is validated as XML, but the opposite may not always be true.

  5. XSD is better at catching errors than XML.

An XSD defines elements that can be used in the documents, relating to the actual data with which it is to be encoded.
for eg:
A date that is expressed as 1/12/2010 can either mean January 12 or December 1st. Declaring a date data type in an XSD document, ensures that it follows the format dictated by XSD.

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How to remove an element from the flow?

position: fixed; will also "pop" an element out of the flow, as you say. :)

position: absolute must be accompanied by a position. e.g. top: 1rem; left: 1rem

position: fixed however, will place the element where it would normally appear according to the document flow, but prevent it from moving after that. It also effectively set's the height to 0px (with regards to the dom) so that the next element shifts up over it.

This can be pretty cool, because you can set position: fixed; z-index: 1 (or whatever z-index you need) so that it "pops" over the next element.

This is especially useful for fixed position headers that stay at the top when you scroll, for example.

Custom thread pool in Java 8 parallel stream

The original solution (setting the ForkJoinPool common parallelism property) no longer works. Looking at the links in the original answer, an update which breaks this has been back ported to Java 8. As mentioned in the linked threads, this solution was not guaranteed to work forever. Based on that, the solution is the forkjoinpool.submit with .get solution discussed in the accepted answer. I think the backport fixes the unreliability of this solution also.

ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
        .forEach((int theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
    list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
        .forEach((theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();

Android: show soft keyboard automatically when focus is on an EditText

<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

or

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

Add a linebreak in an HTML text area

In a text area, as in the form input, then just a normal line break will work:

<textarea>
This is a text area
line breaks are automatic
</textarea>

If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.

However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:

<p>
  This is some text
</p>
<p>
  This is some more
</p>

Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.

What is the technology behind wechat, whatsapp and other messenger apps?

To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.

Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.

How to convert Map keys to array?

Map.keys() returns a MapIterator object which can be converted to Array using Array.from:

let keys = Array.from( myMap.keys() );
// ["a", "b"]

EDIT: you can also convert iterable object to array using spread syntax

let keys =[ ...myMap.keys() ];
// ["a", "b"]

Bulk create model objects in django

for a single line implementation, you can use a lambda expression in a map

map(lambda x:MyModel.objects.get_or_create(name=x), items)

Here, lambda matches each item in items list to x and create a Database record if necessary.

Lambda Documentation

Things possible in IntelliJ that aren't possible in Eclipse?

A few other things:

  • propagate parameters/exceptions when changing method signature, very handy for updating methods deep inside the call stack
  • SQL code validation in the strings passed as arguments to jdbc calls (and the whole newly bundled language injection stuff)
  • implemented in/overwritten in icons for interfaces & classes (and their methods) and the smart implementation navigation (Ctrl+Alt+Click or Ctrl+Alt+B)
  • linking between the EJB 2.1 interfaces and bean classes (including refactoring support); old one, but still immensely valuable when working on older projects

How does a Breadth-First Search work when looking for Shortest Path?

Based on acheron55 answer I posted a possible implementation here.
Here is a brief summery of it:

All you have to do, is to keep track of the path through which the target has been reached. A simple way to do it, is to push into the Queue the whole path used to reach a node, rather than the node itself.
The benefit of doing so is that when the target has been reached the queue holds the path used to reach it.
This is also applicable to cyclic graphs, where a node can have more than one parent.

How to hide keyboard in swift on pressing return key?

The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Good way to encapsulate Integer.parseInt()

This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.

Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)

Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:

public class IntBoxSimple {
    // IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
    // A full blown IntBox class implementation can be found in my Github project
    // Copyright (c) 2016, Peter Sulzer, Fürth
    // Program is published under the GNU General Public License (GPL) Version 1 or newer

    protected int _n; // this "boxes" the int value

    // BEGIN The following statements are only executed at the
    // first instantiation of an IntBox (i. e. only once) or
    // already compiled into the code at compile time:
    public static final int MAX_INT_LEN =
            String.valueOf(Integer.MAX_VALUE).length();
    public static final int MIN_INT_LEN =
            String.valueOf(Integer.MIN_VALUE).length();
    public static final int MAX_INT_LASTDEC =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
    public static final int MAX_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
    public static final int MIN_INT_LASTDEC =
            -Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
    public static final int MIN_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
    // END The following statements...

    // ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
    public static String ltrimZeroes(String s) {
        if (s.charAt(0) == '-')
            return ltrimZeroesNegative(s);
        else
            return ltrimZeroesPositive(s);
    }
    protected static String ltrimZeroesNegative(String s) {
        int i=1;
        for ( ; s.charAt(i) == '0'; i++);
        return ("-"+s.substring(i));
    }
    protected static String ltrimZeroesPositive(String s) {
        int i=0;
        for ( ; s.charAt(i) == '0'; i++);
        return (s.substring(i));
    }

    public static boolean tryParse(String s,IntBoxSimple intBox) {
        if (intBox == null)
            // intBoxSimple=new IntBoxSimple(); // This doesn't work, as
            // intBoxSimple itself is passed by value and cannot changed
            // for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
            return false; // so we simply return false
        s=s.trim(); // leading and trailing whitespace is allowed for String s
        int len=s.length();
        int rslt=0, d, dfirst=0, i, j;
        char c=s.charAt(0);
        if (c == '-') {
            if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
                s = ltrimZeroesNegative(s);
                len = s.length();
            }
            if (len >= MIN_INT_LEN) {
                c = s.charAt(1);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            }
            if (len < MIN_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            } else {
                if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
                    return false;
                rslt -= dfirst * j;
            }
        } else {
            if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
                s = ltrimZeroesPositive(s);
                len=s.length();
            }
            if (len >= MAX_INT_LEN) {
                c = s.charAt(0);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (len < MAX_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
                return false;
            rslt += dfirst*j;
        }
        intBox._n=rslt;
        return true;
    }

    // Get the value stored in an IntBoxSimple:
    public int get_n() {
        return _n;
    }
    public int v() { // alternative shorter version, v for "value"
        return _n;
    }
    // Make objects of IntBoxSimple (needed as constructors are not public):
    public static IntBoxSimple makeIntBoxSimple() {
        return new IntBoxSimple();
    }
    public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
        return new IntBoxSimple(integerNumber);
    }

    // constructors are not public(!=:
    protected IntBoxSimple() {} {
        _n=0; // default value an IntBoxSimple holds
    }
    protected IntBoxSimple(int integerNumber) {
        _n=integerNumber;
    }
}

Test/example program for class IntBoxSimple:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
    public static void main (String args[]) {
        IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
        String in = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.printf(
                    "Enter an integer number in the range %d to %d:%n",
                        Integer.MIN_VALUE, Integer.MAX_VALUE);
            try { in = br.readLine(); } catch (IOException ex) {}
        } while(! IntBoxSimple.tryParse(in, ibs));
        System.out.printf("The number you have entered was: %d%n", ibs.v());
    }
}

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.

I added lines in PATH as above, didn't do anything.

My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.

Run php function on button click

<a href="home.php?click=1" class="btn">Click me</a>
<?php 
  if($_GET['click']){
    doSomething();
  }
?>

But is better to use JS and with ajax to call function!

npm install hangs

Check your .npmrc file for a registry entry (which identifies a server acting as a package cache.)

For me, npm install would hang partway through, and it was because of a old / non-responsive server listed in my .npmrc file. Remove the line or comment it out:

>cat ~/.npmrc
#registry=http://oldserver:4873

(And/or check with your IT / project lead as to why it's not working ;)

Where can I find php.ini?

Use the following commands to find the php.ini file path in linux.

[root@AnyDirectory ~]# locate php.ini
/etc/php.ini
/etc/php.ini.rpmnew
/usr/share/doc/php-common-5.4.45/php.ini-development
/usr/share/doc/php-common-5.4.45/php.ini-production


or try this another way

[root@AnyDirectory ~]# php --ini
its shows the path result

How to Select Top 100 rows in Oracle?

Try this:

   SELECT *
FROM (SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn=1
  ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;

Or TOP:

SELECT TOP 2 * FROM Customers; //But not supported in Oracle

NOTE: I suppose that your internal query is fine. Please share your output of this.

Print all key/value pairs in a Java ConcurrentHashMap

The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:

map.forEach((k,v)-> System.out.println(k+", "+v));

or

map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));

how to iterate through dictionary in a dictionary in django template?

Lets say your data is -

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

How to clear jQuery validation error messages?

For those using Bootstrap 3 code below will clean whole form: messages, icons and colors...

$('.form-group').each(function () { $(this).removeClass('has-success'); });
$('.form-group').each(function () { $(this).removeClass('has-error'); });
$('.form-group').each(function () { $(this).removeClass('has-feedback'); });
$('.help-block').each(function () { $(this).remove(); });
$('.form-control-feedback').each(function () { $(this).remove(); });

how to configuring a xampp web server for different root directory

In case, if anyone prefers a simpler solution, especially on Linux (e.g. Ubuntu), a very easy way out is to create a symbolic link to the intended folder in the htdocs folder. For example, if I want to be able to serve files from a folder called "/home/some/projects/testserver/" and my htdocs is located in "/opt/lampp/htdocs/". Just create a symbolic link like so:

ln -s /home/some/projects/testserver /opt/lampp/htdocs/testserver

The command for symbolic link works like so: ln -s target source where,

target - The existing file/directory you would like to link TO.
source - The file/folder to be created, copying the contents of the target. The LINK itself.

For more help see ln --help Source: Create Symbolic Links in Ubuntu

And that's done. just visit http://localhost/testserver/ In fact, you don't even need to restart your server.

adding noise to a signal in python

Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,

import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

import numpy as np
import pandas as pd

def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
    rnd_state = np.random.RandomState(random_state)
    time = np.linspace(0, 200, num=2000)
    pure = 20*np.sin(time/(2*np.pi))

    # concatenate on the second axis; this will allow us to mix different data 
    # distribution
    data = np.c_[pure]
    mu = np.mean(data)
    sd = np.std(data)
    logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
    data_df = pd.DataFrame(data, columns=['Value'])
    data_df['Index'] = data_df.index.values

    # Adding gaussian jitter
    jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
    data_df['with_jitter'] = data_df['Value'] + jitter

    index_further_away = None
    if add_anomalies:
        # As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd 
        # covers 95.4% of the dataset.
        # Since, anomalies are considered to be rare and typically within the 
        # 5-10% of the data; this filtering
        # technique might work 
        #for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
        indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu + 
         2*sd))[0]
        logger.info(f"Number of points further away : 
        {len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
        # Generate a point uniformly and embed it into the dataset
        random = rnd_state.uniform(0, 5, 1)
        data_df.loc[indexes_furhter_away, 'with_jitter'] +=  
        random*data_df.loc[indexes_furhter_away, 'with_jitter']
    return data_df, indexes_furhter_away

How to find out what is locking my tables?

exec sp_lock

This query should give you existing locks.

exec sp_who SPID -- will give you some info

Having spids, you could check activity monitor(processes tab) to find out what processes are locking the tables ("details" for more info and "kill process" to kill it).

load scripts asynchronously

I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.

How to set JAVA_HOME path on Ubuntu?

add JAVA_HOME to the file:

/etc/environment

for it to be available to the entire system (you would need to restart Ubuntu though)

The backend version is not supported to design database diagrams or tables

I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.

How to use onSaveInstanceState() and onRestoreInstanceState()?

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

static final String STATE_USER = "user";
private String mUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mUser = savedInstanceState.getString(STATE_USER);
    } else {
        // Probably initialize members with default values for a new instance
        mUser = "NewUser";
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString(STATE_USER, mUser);
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

How to check if a div is visible state or not?

if (!$('#singlechatpanel-1').css('display') == 'none') {
   alert('visible');
}else{
   alert('hidden');
}

Create a button with rounded border

FlatButton(
          onPressed: null,
          child: Text('Button', style: TextStyle(
              color: Colors.blue
            )
          ),
          textColor: MyColor.white,
          shape: RoundedRectangleBorder(side: BorderSide(
            color: Colors.blue,
            width: 1,
            style: BorderStyle.solid
          ), borderRadius: BorderRadius.circular(50)),
        )

How to change Named Range Scope

Check out these two subs that reverse each other and flip the scope (worksheet to workbook or reverse) of all named ranges that refer to a range on the active sheet.

 Option Explicit
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorkbook
' Author    : JS20'07'11
' Date      : 11/18/2013
' Purpose   : Rescopes the parent of worksheet scoped named ranges to the active workbook
' for each named range with a scope equal to the active sheet in the active workbook.
'---------------------------------------------------------------------------------------

Public Sub RescopeNamedRangesToWorkbook()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objName In ws.Names
'Check name is visble.
    If objName.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objName.RefersTo
            sObjName = objName.Name
'Check name is scoped to the worksheet.
            If objName.Parent.Name <> sWbName Then
'Delete the current name scoped to worksheet replacing with workbook scoped name.
                sObjName = Mid(sObjName, InStr(1, sObjName, "!") + 1, Len(sObjName))
                objName.Delete
                wb.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objName
End Sub
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorksheet
' Author    : JS20'07'11
' Date      : 11/18/2013
' Purpose   : Rescopes each workbook scoped named range to the specific worksheet to
' which the range refers for each named range that refers to the active worksheet.
'---------------------------------------------------------------------------------------

Public Sub RescopeNamedRangesToWorksheet()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objName In wb.Names
'Check name is visble.
    If objName.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objName.RefersTo
            sObjName = objName.Name
'Check name is scoped to the workbook.
            If objName.Parent.Name = sWbName Then
'Delete the current name scoped to workbook replacing with worksheet scoped name.
                objName.Delete
                ws.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objName
End Sub

Retrieving the COM class factory for component failed

I can understand your pain. In my case the error got resolved by performing below steps:

  1. Start > Run > dcomcnfg.
  2. Open the folder DCOM Config and Select Component Services > Computers > My Computer > DCOM Config.
  3. Select “Microsoft Office Word 97 – 2003 document”/”Microsoft Excel Application” and go to its properties.
  4. In "Security" tab set “Launch and Activation Permissions” need to be Customize (Authorized user).
  5. Now go to IIS and select application pool of the Web and go to its Advanced Settings and select “NETWORK SERVICE” as identity user.

Hope this helps.

Execute specified function every X seconds

The most beginner-friendly solution is:

Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

private void wait_Tick(object sender, EventArgs e)
{
    refreshText(); // Add the method you want to call here.
}

No need to worry about pasting it into the wrong code block or something like that.

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

Python send POST with header

Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

How to view UTF-8 Characters in VIM or Gvim

On Windows gvim just select "Lucida Console" font.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

for me encoding with utf16 worked

file = open('filename.csv', encoding="utf16")

NuGet behind a proxy

I could be wrong but I thought it used IE's proxy settings.

If it sees that you need to login it opens a dialog and asks you to do so (login that is).

Please see the description of this here -> http://docs.nuget.org/docs/release-notes/nuget-1.5

Colorizing text in the console with C++

I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.