Programs & Examples On #Event listener

An abstract object that is triggered when a particular event occurs in the application or system.

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

The following code within a ViewGroup subclass would prevent it's parent containers from receiving touch events:

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    // Normal event dispatch to this container's children, ignore the return value
    super.dispatchTouchEvent(ev);

    // Always consume the event so it is not dispatched further up the chain
    return true;
  }

I used this with a custom overlay to prevent background views from responding to touch events.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Laravel - Model Class not found

If after changing the namespace and the config/auth.php it still fails, you could try the following:

  1. In the file vendor/composer/autoload_classmap.php change the line App\\User' => $baseDir . '/app/User.php',, to App\\Models\\User' => $baseDir . '/app/Models/User.php',

  2. At the beginning of the file app/Services/Registrar.php change "use App\User" to "App\Models\User"

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

What is the difference between Cygwin and MinGW?

Don't overlook AT&T's U/Win software, which is designed to help you compile Unix applications on windows (last version - 2012-08-06; uses Eclipse Public License, Version 1.0).

Like Cygwin they have to run against a library; in their case POSIX.DLL. The AT&T guys are terrific engineers (same group that brought you ksh and dot) and their stuff is worth checking out.

Comparing chars in Java

You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

How to resolve "Server Error in '/' Application" error?

I had this error when the .NET version was wrong - make sure the site is configured to the one you need.

See aspnet_regiis.exe for details.

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

How to validate a date?

My function returns true if is a valid date otherwise returns false :D

_x000D_
_x000D_
function isDate  (day, month, year){_x000D_
 if(day == 0 ){_x000D_
  return false;_x000D_
 }_x000D_
 switch(month){_x000D_
  case 1: case 3: case 5: case 7: case 8: case 10: case 12:_x000D_
   if(day > 31)_x000D_
    return false;_x000D_
   return true;_x000D_
  case 2:_x000D_
   if (year % 4 == 0)_x000D_
    if(day > 29){_x000D_
     return false;_x000D_
    }_x000D_
    else{_x000D_
     return true;_x000D_
    }_x000D_
   if(day > 28){_x000D_
    return false;_x000D_
   }_x000D_
   return true;_x000D_
  case 4: case 6: case 9: case 11:_x000D_
   if(day > 30){_x000D_
    return false;_x000D_
   }_x000D_
   return true;_x000D_
  default:_x000D_
   return false;_x000D_
 }_x000D_
}_x000D_
_x000D_
console.log(isDate(30, 5, 2017));_x000D_
console.log(isDate(29, 2, 2016));_x000D_
console.log(isDate(29, 2, 2015));
_x000D_
_x000D_
_x000D_

How to make clang compile to llvm IR

If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.

Instead, you want to compile with link-time-optimization

clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o

and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm

clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program

This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing

clang program.bc -o program

although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.

Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option

-B/home/jeremy/fakebin

to any linking steps above.

How to implement debounce in Vue2?

If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.

For custom components you should use :value along with @change.native

<b-input :value="data" @change.native="data = $event.target.value" ></b-input>

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

My first program is somewhat similar to one already mentioned here, but my is one line shorter and much more polite:

10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Thanks"

PHP function use variable from outside

Alternatively, you can bring variables in from the outside scope by using closures with the use keyword.

$myVar = "foo";
$myFunction = function($arg1, $arg2) use ($myVar)
{
 return $arg1 . $myVar . $arg2;
};

Print array without brackets and commas

Just initialize a String object with your array

String s=new String(array);

What size should apple-touch-icon.png be for iPad and iPhone?

Use these sizes 57x57, 72x72, 114x114, 144x144 then do this in the head of your document:

<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone4.png" />

   

This will look good on all apple devices. ;)

foreach with index

I like being able to use foreach, so I made an extension method and a structure:

public struct EnumeratedInstance<T>
{
    public long cnt;
    public T item;
}

public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
{
    long counter = 0;
    foreach (var item in collection)
    {
        yield return new EnumeratedInstance<T>
        {
            cnt = counter,
            item = item
        };
        counter++;
    }
}

and an example use:

foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
{
    Console.WriteLine(ii.item + ii.cnt);
}

One nice thing is that if you are used to the Python syntax, you can still use it:

foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))

Why aren't python nested functions called closures?

I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

JS:

function make () {
  var cl = 1;
  function gett () {
    console.log(cl);
  }
  function sett (val) {
    cl = val;
  }
  return [gett, sett]
}

and executing:

a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3

Python:

def make (): 
  cl = 1
  def gett ():
    print(cl);
  def sett (val):
    cl = val
  return gett, sett

and executing:

g, s = make()
g() #1
s(2); g() #1
s(3); g() #1

Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)

How can I get the iOS 7 default blue color programmatically?

Use self.view.tintColor from a view controller, or self.tintColor from a UIView subclass.

How to automate browsing using python?

You can also take a look at mechanize. Its meant to handle "stateful programmatic web browsing" (as per their site).

List Git aliases

As other answers mentioned, git config -l lists all your configuration details from your config file. Here's a partial example of that output for my configuration:

...
alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E
core.repositoryformatversion=0
core.filemode=false
core.bare=false
...

So we can grep out the alias lines, using git config -l | grep alias:

alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

We can make this prettier by just cutting out the alias. part of each line, leaving us with this command:

git config -l | grep alias | cut -c 7-

Which prints:

force=push -f
wd=diff --color-words
shove=push -f
gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

Lastly, don't forget to add this as an alias:

git config --global alias.la "!git config -l | grep alias | cut -c 7-"

Enjoy!

Difference between acceptance test and functional test?

I like the answer of Patrick Cuff. What I like to add is the distinction between a test level and a test type which was for me an eye opener.

test levels

Test level is easy to explain using V-model, an example: enter image description here Each test level has its corresponding development level. It has a typical time characteristic, they're executed at certain phase in the development life cycle.

  1. component/unit testing => verifying detailed design
  2. component/unit integration testing => verifying global design
  3. system testing => verifying system requirements
  4. system integration testing => verifying system requirements
  5. acceptance testing => validating user requirements

test types

A test type is a characteristics, it focuses on a specific test objective. Test types emphasize your quality aspects, also known as technical or non-functional aspects. Test types can be executed at any test level. I like to use as test types the quality characteristics mentioned in ISO/IEC 25010:2011.

  1. functional testing
  2. reliability testing
  3. performance testing
  4. operability testing
  5. security testing
  6. compatibility testing
  7. maintainability testing
  8. transferability testing

To make it complete. There's also something called regression testing. This an extra classification next to test level and test type. A regression test is a test you want to repeat because it touches something critical in your product. It's in fact a subset of tests you defined for each test level. If a there's a small bug fix in your product, one doesn't always have the time to repeat all tests. Regression testing is an answer to that.

Execute JavaScript using Selenium WebDriver in C#

How about a slightly simplified version of @Morten Christiansen's nice extension method idea:

public static object Execute(this IWebDriver driver, string script)
{
    return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = (string)driver.Execute("return document.title");

or maybe the generic version:

public static T Execute<T>(this IWebDriver driver, string script)
{
    return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = driver.Execute<string>("return document.title");

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

How do I replace whitespaces with underscore?

Using the re module:

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace as others have suggested.

Can't start hostednetwork

I encountered this problem on my laptop. I found the solution for this problem.

  1. Test this command in the command prompt "netsh wlan show driver".
  2. See Hosted network supported.
  3. If it is no,

Then do this

  1. Go to device manager.
  2. Click on view and press on "show hidden devices".
  3. Go down to the list of devices and expand the node "Network Devices" .
  4. Find an adapter with the name "Microsoft Hosted Network Virtual Adapter" and then right click on it.
  5. Select Enable
  6. This will enable the AdHoc created connection, it should appear in the network connections in Network and Sharing Center, if the AdHoc network connection is not appear then open elevated command prompt and apply this command "netsh wlan stop hostednetwork" without quotations.
  7. After this, the connection should appear. Then try starting your connection. It should work fine.

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

How to group time by hour or by 10 minutes

The original answer the author gave works pretty well. Just to extend this idea, you can do something like

group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.

How to enable explicit_defaults_for_timestamp?

On Windows -- open my.ini file, present at "C:\ProgramData\MySQL\MySQL Server 5.6", find "[mysqld]" (without quotes) in next line add explicit_defaults_for_timestamp and then save the changes.

Java, Simplified check if int array contains int

You can convert your primitive int array into an arraylist of Integers using below Java 8 code,

List<Integer> arrayElementsList = Arrays.stream(yourArray).boxed().collect(Collectors.toList());

And then use contains() method to check if the list contains a particular element,

boolean containsElement = arrayElementsList.contains(key);

ClassCastException, casting Integer to Double

Well the code you've shown doesn't actually include adding any Integers to the ArrayList - but if you do know that you've got integers, you can use:

sum = (double) ((Integer) marks.get(i)).intValue();

That will convert it to an int, which can then be converted to double. You can't just cast directly between the boxed classes.

Note that if you can possibly use generics for your ArrayList, your code will be clearer.

What is a Python egg?

Note: Egg packaging has been superseded by Wheel packaging.

Same concept as a .jar file in Java, it is a .zip file with some metadata files renamed .egg, for distributing code as bundles.

Specifically: The Internal Structure of Python Eggs

A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.

The .egg format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.

Paging UICollectionView by cells, not screen

This is my solution, in Swift 4.2, I wish it could help you.

class SomeViewController: UIViewController {

  private lazy var flowLayout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: /* width */, height: /* height */)
    layout.minimumLineSpacing = // margin
    layout.minimumInteritemSpacing = 0.0
    layout.sectionInset = UIEdgeInsets(top: 0.0, left: /* margin */, bottom: 0.0, right: /* margin */)
    layout.scrollDirection = .horizontal
    return layout
  }()

  private lazy var collectionView: UICollectionView = {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.dataSource = self
    collectionView.delegate = self
    // collectionView.register(SomeCell.self)
    return collectionView
  }()

  private var currentIndex: Int = 0
}

// MARK: - UIScrollViewDelegate

extension SomeViewController {
  func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    guard scrollView == collectionView else { return }

    let pageWidth = flowLayout.itemSize.width + flowLayout.minimumLineSpacing
    currentIndex = Int(scrollView.contentOffset.x / pageWidth)
  }

  func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    guard scrollView == collectionView else { return }

    let pageWidth = flowLayout.itemSize.width + flowLayout.minimumLineSpacing
    var targetIndex = Int(roundf(Float(targetContentOffset.pointee.x / pageWidth)))
    if targetIndex > currentIndex {
      targetIndex = currentIndex + 1
    } else if targetIndex < currentIndex {
      targetIndex = currentIndex - 1
    }
    let count = collectionView.numberOfItems(inSection: 0)
    targetIndex = max(min(targetIndex, count - 1), 0)
    print("targetIndex: \(targetIndex)")

    targetContentOffset.pointee = scrollView.contentOffset
    var offsetX: CGFloat = 0.0
    if targetIndex < count - 1 {
      offsetX = pageWidth * CGFloat(targetIndex)
    } else {
      offsetX = scrollView.contentSize.width - scrollView.width
    }
    collectionView.setContentOffset(CGPoint(x: offsetX, y: 0.0), animated: true)
  }
}

Styling of Select2 dropdown select boxes

Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....

.select2-dropdown.select2-dropdown--below{
    width: 148px !important;
}

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

How to Update/Drop a Hive Partition?

in addition, you can drop multiple partitions from one statement (Dropping multiple partitions in Impala/Hive).

Extract from above link:

hive> alter table t drop if exists partition (p=1),partition (p=2),partition(p=3);
Dropped the partition p=1
Dropped the partition p=2
Dropped the partition p=3
OK

EDIT 1:

Also, you can drop bulk using a condition sign (>,<,<>), for example:

Alter table t 
drop partition (PART_COL>1);

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

A good example of this casting is using *= or /=

byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57

or

byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40

or

char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'

or

char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

How do I search an SQL Server database for a string?

I was given access to a database, but not the table where my query was being stored in.

Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.

I found that it can also search a database for a string.

Click Search, then Find text on Server

Search tool open. Make sure the DB is selected

It will search each table and give you how many times it found the string per table!

How to move Jenkins from one PC to another

Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.

Step1: Prepare PC1 for migration

  • Manage Jenkins -> ThinbackUp -> Setting
  • Select correct options and directory for backup
  • If you need a job history and artifacts need to be added then please select 'Back build results' option as well.

enter image description here

  • Go back click on Backup Now.

enter image description here

Note: This Thinbackup will also take Plugin Backup which is optional.

  • Check the ThinbackUp folder must have a folder with current date and timestamp. (wait for couple of minutes it might take some time.)
  • You are ready with your back, .zip it and copy to PARTICULAR (which will be 'Backup directory') directory in PC2.
  • Unzip ThinbackUp zipped folder.
  • Stop Jenkins Service in PC1.

Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.

  • Create Jenkins Service using command sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
  • Modify JENKINS_HOME/jenkins.xml if needed in PC2.
  • Run windows service <Jenkins_PC2Servicename> in PC2
  • Manage Jenkins -> ThinbackUp -> Setting
  • Make sure that you PERTICULAR path from step1 as Backup Directory in ThinBackup settings.
  • ThinbackUp -> Restore will give you a Dropdown list, choose a right backup (identify with date and timestamp).

enter image description here

  • Wait for some minutes and you have latest backup configurations including jobs history and plugins in PC2.
  • In case if there are additional changes needed in JENKINS_HOME/Jenkins.xml (coming from PC1 ThinbackUp which is not needed) then this modification need to do manually.

NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.

Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.

jQuery UI Dialog - missing close icon

I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

Xcode 7.2 no matching provisioning profiles found

With Xcode 7.2.1, if you are certain that your provisioning profile is correct (it has the correct App ID and certificate, and the corresponding certificate exists in your Keychain Access) then set the Code Signing Identity and set the Provisioning Profile to Automatic.

How to make a round button?

<corners android:bottomRightRadius="180dip"
    android:bottomLeftRadius="180dip"
    android:topRightRadius="180dip"
    android:topLeftRadius="180dip"/>

<solid android:color="#6E6E6E"/> <!-- this one is ths color of the Rounded Button -->

and add this to the button code

    android:layout_width="50dp"
    android:layout_height="50dp"

Creating .pem file for APNS?

I never remember the openssl command needed to create a .pem file, so I made this bash script to simplify the process:

#!/bin/bash
if [ $# -eq 2 ]
then
    echo "Signing $1..."

    if ! openssl pkcs12 -in $1 -out $2 -nodes -clcerts; then
        echo "Error signing certificate."
    else
        echo "Certificate created successfully: $2"
    fi
else
    if [ $# -gt 2 ]
    then
        echo "Too many arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    else
        echo "Missing arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    fi
fi

Name it, for example, signpem.sh and save it on your user's folder (/Users/<username>?). After creating the file, do a chmod +x signpem.sh to make it executable and then you can run:

~/signpem myCertificate.p12 myCertificate.pem

And myCertificate.pem will be created.

How best to determine if an argument is not sent to the JavaScript function

If you are using jQuery, one option that is nice (especially for complicated situations) is to use jQuery's extend method.

function foo(options) {

    default_options = {
        timeout : 1000,
        callback : function(){},
        some_number : 50,
        some_text : "hello world"
    };

    options = $.extend({}, default_options, options);
}

If you call the function then like this:

foo({timeout : 500});

The options variable would then be:

{
    timeout : 500,
    callback : function(){},
    some_number : 50,
    some_text : "hello world"
};

Passing an array as parameter in JavaScript

Just remove the .value, like this:

function(arrayP){    
   for(var i = 0; i < arrayP.length; i++){
      alert(arrayP[i]);    //no .value here
   }
}

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

Tests not running in Test Explorer

If your projects aren't all AnyCpu then you may also want to check that the following 2 settings match:

  1. [Right click test project] -> properties -> Build -> Platform target - e.g. x64

  2. [Main Menu] -> Test -> Test Settings -> Default Processor Architecture -> X64

I found that when these didn't match my test project would silently fail to run.

How to print the values of slices

You can try the %v, %+v or %#v verbs of go fmt:

fmt.Printf("%v", projects)

If your array (or here slice) contains struct (like Project), you will see their details.
For more precision, you can use %#v to print the object using Go-syntax, as for a literal:

%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value

For basic types, fmt.Println(projects) is enough.


Note: for a slice of pointers, that is []*Project (instead of []Project), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address).
See this play.golang example.

What is a "cache-friendly" code?

As @Marc Claesen mentioned that one of the ways to write cache friendly code is to exploit the structure in which our data is stored. In addition to that another way to write cache friendly code is: change the way our data is stored; then write new code to access the data stored in this new structure.

This makes sense in the case of how database systems linearize the tuples of a table and store them. There are two basic ways to store the tuples of a table i.e. row store and column store. In row store as the name suggests the tuples are stored row wise. Lets suppose a table named Product being stored has 3 attributes i.e. int32_t key, char name[56] and int32_t price, so the total size of a tuple is 64 bytes.

We can simulate a very basic row store query execution in main memory by creating an array of Product structs with size N, where N is the number of rows in table. Such memory layout is also called array of structs. So the struct for Product can be like:

struct Product
{
   int32_t key;
   char name[56];
   int32_t price'
}

/* create an array of structs */
Product* table = new Product[N];
/* now load this array of structs, from a file etc. */

Similarly we can simulate a very basic column store query execution in main memory by creating an 3 arrays of size N, one array for each attribute of the Product table. Such memory layout is also called struct of arrays. So the 3 arrays for each attribute of Product can be like:

/* create separate arrays for each attribute */
int32_t* key = new int32_t[N];
char* name = new char[56*N];
int32_t* price = new int32_t[N];
/* now load these arrays, from a file etc. */

Now after loading both the array of structs (Row Layout) and the 3 separate arrays (Column Layout), we have row store and column store on our table Product present in our memory.

Now we move on to the cache friendly code part. Suppose that the workload on our table is such that we have an aggregation query on the price attribute. Such as

SELECT SUM(price)
FROM PRODUCT

For the row store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + table[i].price;

For the column store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + price[i];

The code for the column store would be faster than the code for the row layout in this query as it requires only a subset of attributes and in column layout we are doing just that i.e. only accessing the price column.

Suppose that the cache line size is 64 bytes.

In the case of row layout when a cache line is read, the price value of only 1(cacheline_size/product_struct_size = 64/64 = 1) tuple is read, because our struct size of 64 bytes and it fills our whole cache line, so for every tuple a cache miss occurs in case of a row layout.

In the case of column layout when a cache line is read, the price value of 16(cacheline_size/price_int_size = 64/4 = 16) tuples is read, because 16 contiguous price values stored in memory are brought into the cache, so for every sixteenth tuple a cache miss ocurs in case of column layout.

So the column layout will be faster in the case of given query, and is faster in such aggregation queries on a subset of columns of the table. You can try out such experiment for yourself using the data from TPC-H benchmark, and compare the run times for both the layouts. The wikipedia article on column oriented database systems is also good.

So in database systems, if the query workload is known beforehand, we can store our data in layouts which will suit the queries in workload and access data from these layouts. In the case of above example we created a column layout and changed our code to compute sum so that it became cache friendly.

How to detect page zoom level in all modern browsers?

I have a solution for this as of Jan 2016. Tested working in Chrome, Firefox and MS Edge browsers.

The principle is as follows. Collect 2 MouseEvent points that are far apart. Each mouse event comes with screen and document coordinates. Measure the distance between the 2 points in both coordinate systems. Although there are variable fixed offsets between the coordinate systems due to the browser furniture, the distance between the points should be identical if the page is not zoomed. The reason for specifying "far apart" (I put this as 12 pixels) is so that small zoom changes (e.g. 90% or 110%) are detectable.

Reference: https://developer.mozilla.org/en/docs/Web/Events/mousemove

Steps:

  1. Add a mouse move listener

    window.addEventListener("mousemove", function(event) {
        // handle event
    });
    
  2. Capture 4 measurements from mouse events:

    event.clientX, event.clientY, event.screenX, event.screenY
    
  3. Measure the distance d_c between the 2 points in the client system

  4. Measure the distance d_s between the 2 points in the screen system

  5. If d_c != d_s then zoom is applied. The difference between the two tells you the amount of zoom.

N.B. Only do the distance calculations rarely, e.g. when you can sample a new mouse event that's far from the previous one.

Limitations: Assumes user will move the mouse at least a little, and zoom is unknowable until this time.

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

Git log out user from command line

On a Mac, credentials are stored in Keychain Access. Look for Github and remove that credential. More info: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/

How to restart adb from root to user mode?

This is a very common issue.

One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.

Just go to Window Task Manager to kill adb process and restart Eclipse.

Will work perfect :)

Importing CSV File to Google Maps

GPS Visualizer has an interface by which you can cut and paste a CSV file and convert it to kml:

http://www.gpsvisualizer.com/map_input?form=googleearth

Then use Google Earth. If you don't have Google Earth and want to display it online I found another nifty service that will plot kml files online:

http://display-kml.appspot.com/

How to pass an array within a query string?

You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

How to get child element by index in Jquery?

var node = document.getElementsByClassName("second")[0].firstElementChild

Disclaimer: Browser compliance on getElementsByClassName and firstElementChild are shaky. DOM-shims fix those problems though.

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

Unable to install boto3

I had a similar problem, but the accepted answer did not resolve it - I was not using a virtual environment. This is what I had to do:

sudo python -m pip install boto3

I do not know why this behaved differently from sudo pip install boto3.

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

Import Error: No module named numpy

I'm not sure exactly why I was getting the error, but pip3 uninstall numpy then pip3 install numpy resolved the issue for me.

Bin size in Matplotlib (Histogram)

This answer support the @ macrocosme suggestion.

I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.

Describe statistics. enter image description here

# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');

plt.colorbar();

enter image description here

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

Import numpy on pycharm

Another option is to open the terminal at the pycharm & install it with pip

sudo pip install numpy

Determine the process pid listening on a certain port

The -p flag of netstat gives you PID of the process:

netstat -l -p

Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat. As we worked out during the discussion with @Cyclone, the line that does the job is:

sockstat -4 -l | grep :80 | awk '{print $3}' | head -1

Open a new tab on button click in AngularJS

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = 'www.google.com';
}

ImportError: No module named PyQt4.QtCore

You don't have g++ installed, simple way to have all the needed build tools is to install the package build-essential:

sudo apt-get install build-essential

, or just the g++ package:

sudo apt-get install g++

Connection to SQL Server Works Sometimes

I had the same issue that automatically resolve after last Microsoft windows update, does anyone experience the same?

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

How do I choose the URL for my Spring Boot webapp?

In your src/main/resources put an application.properties or application.yml and put a server.contextPath in there.

server.contextPath=/your/context/here

When starting your application the application will be available at http://localhost:8080/your/context/here.

For a comprehensive list of properties to set see Appendix A. of the Spring Boot reference guide.

Instead of putting it in the application.properties you can also pass it as a system property when starting your application

java -jar yourapp.jar -Dserver.contextPath=/your/path/here

Fastest JavaScript summation

Improvements


Your looping structure could be made faster:


   var count = 0;
   for(var i=0, n=array.length; i < n; i++) 
   { 
      count += array[i]; 
   }

This retrieves array.length once, rather than with each iteration. The optimization is made by caching the value.


If you really want to speed it up:


   var count=0;
   for (var i=array.length; i--;) {
     count+=array[i];
   }

This is equivalent to a while reverse loop. It caches the value and is compared to 0, thus faster iteration.

For a more complete comparison list, see my JSFiddle.
Note: array.reduce is horrible there, but in Firebug Console it is fastest.


Compare Structures

I started a JSPerf for array summations. It was quickly constructed and not guaranteed to be complete or accurate, but that's what edit is for :)

Return multiple values in JavaScript?

Other than returning an array or an object as others have recommended, you can also use a collector function (similar to the one found in The Little Schemer):

function a(collector){
  collector(12,13);
}

var x,y;
a(function(a,b){
  x=a;
  y=b;
});

I made a jsperf test to see which one of the three methods is faster. Array is fastest and collector is slowest.

http://jsperf.com/returning-multiple-values-2

How do I call a dynamically-named method in Javascript?

As Triptych points out, you can call any global scope function by finding it in the host object's contents.

A cleaner method, which pollutes the global namespace much less, is to explicitly put the functions into an array directly like so:

var dyn_functions = [];
dyn_functions['populate_Colours'] = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions['populate_Shapes'](1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions.populate_Shapes(1, 2);

This array could also be a property of some object other than the global host object too meaning that you can effectively create your own namespace as many JS libraries such as jQuery do. This is useful for reducing conflicts if/when you include multiple separate utility libraries in the same page, and (other parts of your design permitting) can make it easier to reuse the code in other pages.

You could also use an object like so, which you might find cleaner:

var dyn_functions = {};
dyn_functions.populate_Colours = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions.populate_Shapes(1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions['populate_Shapes'](1, 2);

Note that with either an array or an object, you can use either method of setting or accessing the functions, and can of course store other objects in there too. You can further reduce the syntax of either method for content that isn't that dynamic by using JS literal notation like so:

var dyn_functions = {
           populate_Colours:function (arg1, arg2) { 
                // function body
           };
         , populate_Shapes:function (arg1, arg2) { 
                // function body
           };
};

Edit: of course for larger blocks of functionality you can expand the above to the very common "module pattern" which is a popular way to encapsulate code features in an organised manner.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

Check the current number of connections to MongoDb

Also some more details on the connections with: db.currentOp(true)

Taken from: https://jira.mongodb.org/browse/SERVER-5085

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The is keyword is a test for object identity while == is a value comparison.

If you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

HRESULT: 0x800A03EC on Worksheet.range

I had the same error code when executing the following statement:

sheet.QueryTables.Add("TEXT" & Path.GetFullPath(fileName), "1:1", Type.Missing)

The reason was the missing semicolon (;) after "TEXT".

Here is the correct one:

sheet.QueryTables.Add("TEXT;" & Path.GetFullPath(fileName), "1:1", Type.Missing)

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

No connection could be made because the target machine actively refused it?

Normally, connection scripts do not mention the port to use. For example:

$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database');

So, to connect with a manager that doesn't use port 3306, you have to specify the port number on the connection request:

$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database', '3307');

To check the connections on the MySQL or MariaDB database manager, use the script: wamp(64)\www\testmysql.php by putting 'http://localhost/testmysql.php' in the browser address bar having first modified the script according to your parameters.

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

How to find char in string and get all the indexes?

This is because str.index(ch) will return the index where ch occurs the first time. Try:

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

This will return a list of all indexes you need.

P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing [] to ().

Check if a number is odd or even in python

Use the modulo operator:

if wordLength % 2 == 0:
    print "wordLength is even"
else:
    print "wordLength is odd"

For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1], which create the list from word by taking every character from the end to the start:

def is_palindrome(word):
    return word == word[::-1]

How to convert JSON to a Ruby hash

What about the following snippet?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

Change event on select with knockout binding, how can I know if it is a real change?

Here is a solution that may help with this strange behaviour. I couldn't find a better solution than place a button to manually trigger the change event.

EDIT: Maybe a custom binding like this could help:

ko.bindingHandlers.changeSelectValue = {

   init: function(element,valueAccessor){

        $(element).change(function(){

            var value = $(element).val();

            if($(element).is(":focus")){

                  //Do whatever you want with the new value
            }

        });

    }
  };

And in your select data-bind attribute add:

changeSelectValue: yourSelectValue

List of strings to one string

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

Running this in the commandline will fix the problem also. SETX VisualStudioVersion "12.0"

Can we call the function written in one JavaScript in another JS file?

For those who want to do this in Node.js (running scripts on the server-side) another option is to use require and module.exports. Here is a short example on how to create a module and export it for use elsewhere:

file1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

React won't load local images

By doing a simple import you can access the image in React

import logo from "../images/logo.png";
<img src={logo}/>

Everything solved! Just a simple fix =)

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

Problems after upgrading to Xcode 10: Build input file cannot be found

The above solution eventually works for me; however, I need to do some more extra steps to finally make it to compile successfully. (These extra steps were required even on Xcode 9.)

  1. Xcode: File -> Workspace Settings -> Build System: Legacy Build System
  2. Xcode: Product -> Clean
  3. Rotate to compile thru different emulator types, such as "iPhone 8", "iPhone 8 Plus", etc. (They might fail or might not.)
  4. Eventually compile on "Generic iOS Device"

How can I add reflection to a C++ application?

If you declare a pointer to a function like this:

int (*func)(int a, int b);

You can assign a place in memory to that function like this (requires libdl and dlopen)

#include <dlfcn.h>

int main(void)
{
    void *handle;
    char *func_name = "bla_bla_bla";
    handle = dlopen("foo.so", RTLD_LAZY);
    *(void **)(&func) = dlsym(handle, func_name);
    return func(1,2);
}

To load a local symbol using indirection, you can use dlopen on the calling binary (argv[0]).

The only requirement for this (other than dlopen(), libdl, and dlfcn.h) is knowing the arguments and type of the function.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

What exactly are DLL files, and how do they work?

DLL files contain an Export Table which is a list of symbols which can be looked up by the calling program. The symbols are typically functions with the C calling convention (__stcall). The export table also contains the address of the function.

With this information, the calling program can then call the functions within the DLL even though it did not have access to the DLL at compile time.

Introducing Dynamic Link Libraries has some more information.

Coding Conventions - Naming Enums

As already stated, enum instances should be uppercase according to the docs on the Oracle website (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).

However, while looking through a JavaEE7 tutorial on the Oracle website (http://www.oracle.com/technetwork/java/javaee/downloads/index.html), I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java), I found the following enum definition:

private enum PropertyKeys {
    alt, coords, shape, targetImage;
}

According to the conventions, it should have looked like:

public enum PropertyKeys {
    ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");

    private final String val;

    private PropertyKeys(String val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return val;
    }
}

So it seems even the guys at Oracle sometimes trade convention with convenience.

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

How to Generate Unique ID in Java (Integer)?

Unique at any time:

int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

How to safely call an async method in C# without await

On technologies with message loops (not sure if ASP is one of them), you can block the loop and process messages until the task is over, and use ContinueWith to unblock the code:

public void WaitForTask(Task task)
{
    DispatcherFrame frame = new DispatcherFrame();
    task.ContinueWith(t => frame.Continue = false));
    Dispatcher.PushFrame(frame);
}

This approach is similar to blocking on ShowDialog and still keeping the UI responsive.

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

Looping through the content of a file in Bash

Here is my real life example how to loop lines of another program output, check for substrings, drop double quotes from variable, use that variable outside of the loop. I guess quite many is asking these questions sooner or later.

##Parse FPS from first video stream, drop quotes from fps variable
## streams.stream.0.codec_type="video"
## streams.stream.0.r_frame_rate="24000/1001"
## streams.stream.0.avg_frame_rate="24000/1001"
FPS=unknown
while read -r line; do
  if [[ $FPS == "unknown" ]] && [[ $line == *".codec_type=\"video\""* ]]; then
    echo ParseFPS $line
    FPS=parse
  fi
  if [[ $FPS == "parse" ]] && [[ $line == *".r_frame_rate="* ]]; then
    echo ParseFPS $line
    FPS=${line##*=}
    FPS="${FPS%\"}"
    FPS="${FPS#\"}"
  fi
done <<< "$(ffprobe -v quiet -print_format flat -show_format -show_streams -i "$input")"
if [ "$FPS" == "unknown" ] || [ "$FPS" == "parse" ]; then 
  echo ParseFPS Unknown frame rate
fi
echo Found $FPS

Declare variable outside of the loop, set value and use it outside of loop requires done <<< "$(...)" syntax. Application need to be run within a context of current console. Quotes around the command keeps newlines of output stream.

Loop match for substrings then reads name=value pair, splits right-side part of last = character, drops first quote, drops last quote, we have a clean value to be used elsewhere.

Creating stored procedure and SQLite?

If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.

I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.

Hopefully this answer will help someone in the future.

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

Setting background images in JFrame

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

Best way to define private methods for a class in Objective-C

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.

Get WooCommerce product categories from WordPress

Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );
    if($sub_cats) {
        foreach($sub_cats as $sub_category) {
            echo  $sub_category->name ;
        }

    }

with:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                }
            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                }
            }

Update R using RStudio

There's a new package called installr that can update your R version within R on the Windows platform. The package was built under version 3.2.3

From R Studio, click on Tools and select Install Packages... then type the name "installr" and click install. Alternatively, you may type install.packages("installr") in the Console.

Once R studio is done installing the package, load it by typing require(installr) in the Console.

To start the updating process for your R installation, type updateR(). This function will check for newer versions of R and if available, it will guide you through the decisions you need to make. If your R installation is up-to-date, it will return FALSE.

If you choose to download and install a newer version. There's an option for copying/moving all of your packages from the current R installation to the newer R installation which is very handy.

Quit and restart R Studio once the update process is over. R Studio will load the newer R version.

Follow this link if you wish to learn more on how to use the installr package.

How to determine the current iPhone/device model?

For both device as well as simulators, Create a new swift file with name UIDevice.swift

Add the below code

import UIKit


public extension UIDevice {

var modelName: String {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        let DEVICE_IS_SIMULATOR = true
    #else
        let DEVICE_IS_SIMULATOR = false
    #endif

    var machineString : String = ""

    if DEVICE_IS_SIMULATOR == true
    {

        if let dir = NSProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
            machineString = dir
        }
    }
    else {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        machineString = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 where value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
    }
    switch machineString {
    case "iPod5,1":                                 return "iPod Touch 5"
    case "iPod7,1":                                 return "iPod Touch 6"
    case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
    case "iPhone4,1":                               return "iPhone 4s"
    case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
    case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
    case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
    case "iPhone7,2":                               return "iPhone 6"
    case "iPhone7,1":                               return "iPhone 6 Plus"
    case "iPhone8,1":                               return "iPhone 6s"
    case "iPhone8,2":                               return "iPhone 6s Plus"
    case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
    case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
    case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
    case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
    case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
    case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
    case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
    case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
    case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
    case "iPad6,7", "iPad6,8":                      return "iPad Pro"
    case "AppleTV5,3":                              return "Apple TV"
    default:                                        return machineString
    }
}
}

Then in your viewcontroller,

 let deviceType = UIDevice.currentDevice().modelName

    if deviceType.lowercaseString.rangeOfString("iphone 4") != nil {
       print("iPhone 4 or iphone 4s")
    }
    else if deviceType.lowercaseString.rangeOfString("iphone 5") != nil {
        print("iPhone 5 or iphone 5s or iphone 5c")
    }
   else if deviceType.lowercaseString.rangeOfString("iphone 6") != nil {
        print("iPhone 6 Series")
    }

Absolute positioning ignoring padding of parent

Well, this may not be the most elegant solution (semantically), but in some cases it'll work without any drawbacks: Instead of padding, use a transparent border on the parent element. The absolute positioned child elements will honor the border and it'll be rendered exactly the same (except you're using the border of the parent element for styling).

How can I change the default width of a Twitter Bootstrap modal box?

Preserve the responsive design, set the width to what you desire.

.modal-content {
  margin-left: auto;
  margin-right: auto;
  max-width: 360px;
}

Keep it simple.

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

PowerShell: Format-Table without headers

I know it's 2 years late, but these answers helped me to formulate a filter function to output objects and trim the resulting strings. Since I have to format everything into a string in my final solution I went about things a little differently. Long-hand, my problem is very similar, and looks a bit like this

$verbosepreference="Continue"
write-verbose (ls | ft | out-string) # this generated too many blank lines

Here is my example:

ls | Out-Verbose # out-verbose formats the (pipelined) object(s) and then trims blanks

My Out-Verbose function looks like this:

filter Out-Verbose{
Param([parameter(valuefrompipeline=$true)][PSObject[]]$InputObject,
      [scriptblock]$script={write-verbose "$_"})
  Begin {
    $val=@()
  }
  Process {
    $val += $inputobject
  }
  End {
    $val | ft -autosize -wrap|out-string |%{$_.split("`r`n")} |?{$_.length} |%{$script.Invoke()}
  }
}

Note1: This solution will not scale to like millions of objects(it does not handle the pipeline serially)

Note2: You can still add a -noheaddings option. If you are wondering why I used a scriptblock here, that's to allow overloading like to send to disk-file or other output streams.

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

Is this how you define a function in jQuery?

No, you can just write the function as:

$(document).ready(function() {
    MyBlah("hello");
});

function MyBlah(blah) {
    alert(blah);
}

This calls the function MyBlah on content ready.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I tried almost all the possible suggestions mention here but for me problem got solved after changing "Access for less secure apps" to ENABLE in my Google account security settings tab. Hope this might useful for others !

How to find a user's home directory on linux or unix?

The userdir prefix (e.g., '/home' or '/export/home') could be a configuration item. Then the app can append the arbitrary user name to that path.

Caveat: This doesn't intelligently interact with the OS, so you'd be out of luck if it were a Windows system with userdirs on different drives, or on Unix with a home dir layout like /home/f/foo, /home/b/bar.

Django optional url parameters

You can use nested routes

Django <1.8

urlpatterns = patterns(''
    url(r'^project_config/', include(patterns('',
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include(patterns('',
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ))),
    ))),
)

Django >=1.8

urlpatterns = [
    url(r'^project_config/', include([
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include([
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ])),
    ])),
]

This is a lot more DRY (Say you wanted to rename the product kwarg to product_id, you only have to change line 4, and it will affect the below URLs.

Edited for Django 1.8 and above

error: unknown type name ‘bool’

Somewhere in your code there is a line #include <string>. This by itself tells you that the program is written in C++. So using g++ is better than gcc.

For the missing library: you should look around in the file system if you can find a file called libl.so. Use the locate command, try /usr/lib, /usr/local/lib, /opt/flex/lib, or use the brute-force find / | grep /libl.

Once you have found the file, you have to add the directory to the compiler command line, for example:

g++ -o scan lex.yy.c -L/opt/flex/lib -ll

How can I add comments in MySQL?

From here you can use

#  For single line comments
-- Also for single line, must be followed by space/control character
/*
    C-style multiline comment
*/

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How to quickly drop a user with existing privileges

I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.

I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.

1) Drop the database

dropdb msf

2) drop the user

dropuser msf

Now I got the user successfully dropped.

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

A transport-level error has occurred when receiving results from the server

For those not using IIS, I had this issue when debugging with Visual Studio 2010. I ended all of the debugger processes: WebDev.WebServer40.EXE which solved the issue.

CSS Display an Image Resized and Cropped

What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.

It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

I strongly prefer HomeBrew over MacPorts for installing software from source.

HomeBrew sequesters everything in /usr/local/Cellar so it doesn't spew files all over the place. (Yes, MacPorts keeps everything in /opt/local, but it requires sudo access, and I don't trust MacPorts with root.)

Installing MySQL is as simple as:

brew install mysql
mysql_install_db

To start mysql, in Terminal type:

mysqld&

There's a way to start it upon boot, but I like to start it manually.

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

As @hanmari mentioned in his comment. when inserting into a postgres tables, the on conflict (..) do nothing is the best code to use for not inserting duplicate data.:

query = "INSERT INTO db_table_name(column_name)
         VALUES(%s) ON CONFLICT (column_name) DO NOTHING;"

The ON CONFLICT line of code will allow the insert statement to still insert rows of data. The query and values code is an example of inserted date from a Excel into a postgres db table. I have constraints added to a postgres table I use to make sure the ID field is unique. Instead of running a delete on rows of data that is the same, I add a line of sql code that renumbers the ID column starting at 1. Example:

q = 'ALTER id_column serial RESTART WITH 1'

If my data has an ID field, I do not use this as the primary ID/serial ID, I create a ID column and I set it to serial. I hope this information is helpful to everyone. *I have no college degree in software development/coding. Everything I know in coding, I study on my own.

Showing which files have changed between two revisions

One more option, using meld in this case:

git difftool -d master otherbranch

This allows not only to see the differences between files, but also provides a easy way to point and click into a specific file.

How to gettext() of an element in Selenium Webdriver

You need to print the result of the getText(). You're currently printing the object TxtBoxContent.

getText() will only get the inner text of an element. To get the value, you need to use getAttribute().

WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]
    

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

The FULLY WORKING SOLUTION for both Android or React-native users facing this issue just add this android:usesCleartextTraffic="true" in AndroidManifest.xml file like this:

android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
    android:name="org.apache.http.legacy"
    android:required="false" />

in between <application>.. </application> tag like this:

<application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning">
        <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"/>
 </application>

What does it mean when an HTTP request returns status code 0?

wininet.dll returns both standard and non-standard status codes that are listed below.

401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed

12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception

For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?

XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

How to enter command with password for git pull?

This is not exactly what you asked for, but for http(s):

  • you can put the password in .netrc file (_netrc on windows). From there it would be picked up automatically. It would go to your home folder with 600 permissions.
  • you could also just clone the repo with https://user:pass@domain/repo but that's not really recommended as it would show your user/pass in a lot of places...
  • a new option is to use the credential helper. Note that credentials would be stored in clear text in your local config using standard credential helper. credential-helper with wincred can be also used on windows.

Usage examples for credential helper

  • git config credential.helper store - stores the credentials indefinitely.
  • git config credential.helper 'cache --timeout=3600'- stores for 60 minutes

For ssh-based access, you'd use ssh agent that will provide the ssh key when needed. This would require generating keys on your computer, storing the public key on the remote server and adding the private key to relevant keystore.

ImportError: No module named sqlalchemy

I just experienced the same problem. Apparently, there is a new distribution method, the extension code is no longer stored under flaskext.

Source: Flask CHANGELOG This worked for me:

from flask_sqlalchemy import SQLAlchemy

How do I limit the number of returned items?

Like this, using .limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
  // `posts` will be of length 20
});

UILabel text margin

Xcode 6.1.1 Swift solution using a extension.

The file name could be something like "UILabel+AddInsetMargin.swift":

import UIKit

extension UILabel
{
    public override func drawRect(rect: CGRect)
    {
        self.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)))
    }
}

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

How to position text over an image in css

Why not set sample.png as background image of text or h2 css class? This will give effect as you have written over an image.

Type List vs type ArrayList in Java

I think the people who use (2) don't know the Liskov substitution principle or the Dependency inversion principle. Or they really have to use ArrayList.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Dim rg As Range
Set rg = Range("A1:E10")
Dim i As Integer
For i = 1 To rg.Rows.Count

    For j = 1 To rg.Columns.Count
    rg.Cells(i, j).Value = rg.Cells(i, j).Address(False, False)

    Next
Next

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you are using Jersey 2.x use following dependency:

<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.XX</version>
</dependency>  

Where XX could be any particular version you look for. Jersey Containers.

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

How do I get a file's directory using the File object?

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

Using PHP variables inside HTML tags?

You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:

echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";

echo '<a href="http://www.whatever.com/' . $param . '">Click Here</a>';

Notice that I escaped the double quotes inside my first example using a backslash.

SQL: Return "true" if list of records exists?

Your c# will have to do just a bit of work (counting the number of IDs passed in), but try this:

select (select count(*) from players where productid in (1, 10, 100, 1000)) = 4

Edit:

4 can definitely be parameterized, as can the list of integers.

If you're not generating the SQL from string input by the user, you don't need to worry about attacks. If you are, you just have to make sure you only get integers. For example, if you were taking in the string "1, 2, 3, 4", you'd do something like

String.Join(",", input.Split(",").Select(s => Int32.Parse(s).ToString()))

That will throw if you get the wrong thing. Then just set that as a parameter.

Also, be sure be sure to special case if items.Count == 0, since your DB will choke if you send it where ParameterID in ().

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I set my width element, with javascript. After I set the de vh.

html

<div id="gifimage"><img src="back_phone_back.png" style="width: 100%"></div>

css

#gifimage {
    position: absolute;
    height: 70vh;
}

javascript

imageHeight = document.getElementById('gifimage').clientHeight;

// if (isMobile)       
document.getElementById('gifimage').setAttribute("style","height:" + imageHeight + "px");

This works for me. I don't use jquery ect. because I want it to load as soon as posible.

What is process.env.PORT in Node.js?

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

What version of MongoDB is installed on Ubuntu

inside shell:

mongod --version

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

This is another way and is good to use with some text editors that are unable to correctly highlight every intricate code you create:

read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"

Converting XML to JSON using Python?

I'd suggest not going for a direct conversion. Convert XML to an object, then from the object to JSON.

In my opinion, this gives a cleaner definition of how the XML and JSON correspond.

It takes time to get right and you may even write tools to help you with generating some of it, but it would look roughly like this:

class Channel:
  def __init__(self)
    self.items = []
    self.title = ""

  def from_xml( self, xml_node ):
    self.title = xml_node.xpath("title/text()")[0]
    for x in xml_node.xpath("item"):
      item = Item()
      item.from_xml( x )
      self.items.append( item )

  def to_json( self ):
    retval = {}
    retval['title'] = title
    retval['items'] = []
    for x in items:
      retval.append( x.to_json() )
    return retval

class Item:
  def __init__(self):
    ...

  def from_xml( self, xml_node ):
    ...

  def to_json( self ):
    ...

Setting up and using Meld as your git difftool and mergetool

How do I set up and use Meld as my git difftool?

git difftool displays the diff using a GUI diff program (i.e. Meld) instead of displaying the diff output in your terminal.

Although you can set the GUI program on the command line using -t <tool> / --tool=<tool> it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
[diff]
    tool = meld
[difftool]
    prompt = false
[difftool "meld"]
    cmd = meld "$LOCAL" "$REMOTE"

[Note: These settings will not alter the behaviour of git diff which will continue to function as usual.]

You use git difftool in exactly the same way as you use git diff. e.g.

git difftool <COMMIT_HASH> file_name
git difftool <BRANCH_NAME> file_name
git difftool <COMMIT_HASH_1> <COMMIT_HASH_2> file_name

If properly configured a Meld window will open displaying the diff using a GUI interface.

The order of the Meld GUI window panes can be controlled by the order of $LOCAL and $REMOTE in cmd, that is to say which file is shown in the left pane and which in the right pane. If you want them the other way around simply swap them around like this:

    cmd = meld "$REMOTE" "$LOCAL"

Finally the prompt = false line simply stops git from prompting you as to whether you want to launch Meld or not, by default git will issue a prompt.


How do I set up and use Meld as my git mergetool?

git mergetool allows you to use a GUI merge program (i.e. Meld) to resolve the merge conflicts that have occurred during a merge.

Like difftool you can set the GUI program on the command line using -t <tool> / --tool=<tool> but, as before, it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
[merge]
    tool = meld
[mergetool "meld"]
    # Choose one of these 2 lines (not both!) explained below.
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"

You do NOT use git mergetool to perform an actual merge. Before using git mergetool you perform a merge in the usual way with git. e.g.

git checkout master
git merge branch_name

If there is a merge conflict git will display something like this:

$ git merge branch_name
Auto-merging file_name
CONFLICT (content): Merge conflict in file_name
Automatic merge failed; fix conflicts and then commit the result.

At this point file_name will contain the partially merged file with the merge conflict information (that's the file with all the >>>>>>> and <<<<<<< entries in it).

Mergetool can now be used to resolve the merge conflicts. You start it very easily with:

git mergetool

If properly configured a Meld window will open displaying 3 files. Each file will be contained in a separate pane of its GUI interface.

In the example .gitconfig entry above, 2 lines are suggested as the [mergetool "meld"] cmd line. In fact there are all kinds of ways for advanced users to configure the cmd line, but that is beyond the scope of this answer.

This answer has 2 alternative cmd lines which, between them, will cater for most users, and will be a good starting point for advanced users who wish to take the tool to the next level of complexity.

Firstly here is what the parameters mean:

  • $LOCAL is the file in the current branch (e.g. master).
  • $REMOTE is the file in the branch being merged (e.g. branch_name).
  • $MERGED is the partially merged file with the merge conflict information in it.
  • $BASE is the shared commit ancestor of $LOCAL and $REMOTE, this is to say the file as it was when the branch containing $REMOTE was originally created.

I suggest you use either:

[mergetool "meld"]
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"

or:

[mergetool "meld"]
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"
    # See 'Note On Output File' which explains --output "$MERGED".

The choice is whether to use $MERGED or $BASE in between $LOCAL and $REMOTE.

Either way Meld will display 3 panes with $LOCAL and $REMOTE in the left and right panes and either $MERGED or $BASE in the middle pane.

In BOTH cases the middle pane is the file that you should edit to resolve the merge conflicts. The difference is just in which starting edit position you'd prefer; $MERGED for the file which contains the partially merged file with the merge conflict information or $BASE for the shared commit ancestor of $LOCAL and $REMOTE. [Since both cmd lines can be useful I keep them both in my .gitconfig file. Most of the time I use the $MERGED line and the $BASE line is commented out, but the commenting out can be swapped over if I want to use the $BASE line instead.]

Note On Output File: Do not worry that --output "$MERGED" is used in cmd regardless of whether $MERGED or $BASE was used earlier in the cmd line. The --output option simply tells Meld what filename git wants the conflict resolution file to be saved in. Meld will save your conflict edits in that file regardless of whether you use $MERGED or $BASE as your starting edit point.

After editing the middle pane to resolve the merge conflicts, just save the file and close the Meld window. Git will do the update automatically and the file in the current branch (e.g. master) will now contain whatever you ended up with in the middle pane.

git will have made a backup of the partially merged file with the merge conflict information in it by appending .orig to the original filename. e.g. file_name.orig. After checking that you are happy with the merge and running any tests you may wish to do, the .orig file can be deleted.

At this point you can now do a commit to commit the changes.

If, while you are editing the merge conflicts in Meld, you wish to abandon the use of Meld, then quit Meld without saving the merge resolution file in the middle pane. git will respond with the message file_name seems unchanged and then ask Was the merge successful? [y/n], if you answer n then the merge conflict resolution will be aborted and the file will remain unchanged. Note that if you have saved the file in Meld at any point then you will not receive the warning and prompt from git. [Of course you can just delete the file and replace it with the backup .orig file that git made for you.]

If you have more than 1 file with merge conflicts then git will open a new Meld window for each, one after another until they are all done. They won't all be opened at the same time, but when you finish editing the conflicts in one, and close Meld, git will then open the next one, and so on until all the merge conflicts have been resolved.

It would be sensible to create a dummy project to test the use of git mergetool before using it on a live project. Be sure to use a filename containing a space in your test, in case your OS requires you to escape the quotes in the cmd line, see below.


Escaping quote characters

Some operating systems may need to have the quotes in cmd escaped. Less experienced users should remember that config command lines should be tested with filenames that include spaces, and if the cmd lines don't work with the filenames that include spaces then try escaping the quotes. e.g.

cmd = meld \"$LOCAL\" \"$REMOTE\"

In some cases more complex quote escaping may be needed. The 1st of the Windows path links below contains an example of triple-escaping each quote. It's a bore but sometimes necessary. e.g.

cmd = meld \\\"$LOCAL\\\" \\\"$REMOTE\\\"

Windows paths

Windows users will probably need extra configuration added to the Meld cmd lines. They may need to use the full path to meldc, which is designed to be called on Windows from the command line, or they may need or want to use a wrapper. They should read the StackOverflow pages linked below which are about setting the correct Meld cmd line for Windows. Since I am a Linux user I am unable to test the various Windows cmd lines and have no further information on the subject other than to recommend using my examples with the addition of a full path to Meld or meldc, or adding the Meld program folder to your path.

Ignoring trailing whitespace with Meld

Meld has a number of preferences that can be configured in the GUI.

In the preferences Text Filters tab there are several useful filters to ignore things like comments when performing a diff. Although there are filters to ignore All whitespace and Leading whitespace, there is no ignore Trailing whitespace filter (this has been suggested as an addition in the Meld mailing list but is not available in my version).

Ignoring trailing whitespace is often very useful, especially when collaborating, and can be manually added easily with a simple regular expression in the Meld preferences Text Filters tab.

# Use either of these regexes depending on how comprehensive you want it to be.
[ \t]*$
[ \t\r\f\v]*$

I hope this helps everyone.

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>
</div>

Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

CSS: How can I set image size relative to parent height?

Change your code:

a.image_container img {
    width: 100%;
}

To this:

a.image_container img {
    width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
    height: 100%;
}

http://jsfiddle.net/f9krj/5/

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

Access a URL and read Data with R

base

read.csv without the url function just works fine. Probably I am missing something if Dirk Eddelbuettel included it in his answer:

ad <- read.csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

  X    TV radio newspaper sales
1 1 230.1  37.8      69.2  22.1
2 2  44.5  39.3      45.1  10.4
3 3  17.2  45.9      69.3   9.3
4 4 151.5  41.3      58.5  18.5
5 5 180.8  10.8      58.4  12.9
6 6   8.7  48.9      75.0   7.2

Another options using two popular packages:

data.table

library(data.table)
ad <- fread("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

V1    TV radio newspaper sales
1:  1 230.1  37.8      69.2  22.1
2:  2  44.5  39.3      45.1  10.4
3:  3  17.2  45.9      69.3   9.3
4:  4 151.5  41.3      58.5  18.5
5:  5 180.8  10.8      58.4  12.9
6:  6   8.7  48.9      75.0   7.2

readr

library(readr)
ad <- read_csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

# A tibble: 6 x 5
     X1    TV radio newspaper sales
  <int> <dbl> <dbl>     <dbl> <dbl>
1     1 230.1  37.8      69.2  22.1
2     2  44.5  39.3      45.1  10.4
3     3  17.2  45.9      69.3   9.3
4     4 151.5  41.3      58.5  18.5
5     5 180.8  10.8      58.4  12.9
6     6   8.7  48.9      75.0   7.2

For homebrew mysql installs, where's my.cnf?

I believe the answer is no. Installing one in ~/.my.cnf or /usr/local/etc seems to be the preferred solution.

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

printf with std::string?

Please don't use printf("%s", your_string.c_str());

Use cout << your_string; instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf entirely -- it's a leftover from C that's rarely needed or useful in C++.

As to why you should use cout instead of printf, the reasons are numerous. Here's a sampling of a few of the most obvious:

  1. As the question shows, printf isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.
  2. printf isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.
  3. It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout has that covered as well. For example:

    std::locale loc("");
    std::cout.imbue(loc);
    
    std::cout << 123456.78;
    

    The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78. For somebody with it configured for India, it would print out as 1,23,456.78 (and of course there are many others). With printf I get exactly one result: 123456.78. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf, because printf itself simply will not do the job correctly.

  4. Although they're quite compact, printf format strings can be quite unreadable. Even among C programmers who use printf virtually every day, I'd guess at least 99% would need to look things up to be sure what the # in %#x means, and how that differs from what the # in %#f means (and yes, they mean entirely different things).

How to get Current Directory?

I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.

To get the executable path use GetModuleFileName:

TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );

Here's a C++ function that gets the directory without the file name:

#include <windows.h>
#include <string>
#include <iostream>

wstring ExePath() {
    TCHAR buffer[MAX_PATH] = { 0 };
    GetModuleFileName( NULL, buffer, MAX_PATH );
    std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
    return std::wstring(buffer).substr(0, pos);
}

int main() {
    std::cout << "my directory is " << ExePath() << "\n";
}

How do I get the name of the rows from the index of a data frame?

df.index

  • outputs the row names as pandas Index object.

list(df.index)

  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

Error: Local workspace file ('angular.json') could not be found

I just had the same problem.

It's related to release v6.0.0-rc.2, https://github.com/angular/angular-cli/releases:

New configuration format. The new file can be found at angular.json (but .angular.json is also accepted). Running ng update on a CLI 1.7 project will move you to the new configuration.

I needed to execute:

ng update @angular/cli --migrate-only --from=1.7.4

This removed .angular-cli.json and created angular.json.

If this leads to your project using 1.7.4, install v6 locally:

npm install --save-dev @angular/[email protected]

And try once again to update your project with:

ng update @angular/cli --migrate-only --from=1.7.4

How to manually reload Google Map with JavaScript

You can refresh with this:

map.panBy(0, 0);

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How to sort an array based on the length of each element?

I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

printing a two dimensional array in python

I used numpy to generate the array, but list of lists array should work similarly.

import numpy as np
def printArray(args):
    print "\t".join(args)

n = 10

Array = np.zeros(shape=(n,n)).astype('int')

for row in Array:
    printArray([str(x) for x in row])

If you want to only print certain indices:

import numpy as np
def printArray(args):
    print "\t".join(args)

n = 10

Array = np.zeros(shape=(n,n)).astype('int')

i_indices = [1,2,3]
j_indices = [2,3,4]

for i in i_indices:printArray([str(Array[i][j]) for j in j_indices])

How do I check if file exists in Makefile so I can delete it?

test ! -f README.md || echo 'Support OpenSource!' >> README.md

"If README.md does not exist, do nothing (and exit successfully). Otherwise, append text to the end."

If you use && instead of || then you generate an error when the file doesn't exist:

Makefile:42: recipe for target 'dostuff' failed
make: *** [dostuff] Error 1

How do I timestamp every ping result?

I could not redirect the Perl based solution to a file for some reason so I kept searching and found a bash only way to do this:

ping www.google.fr | while read pong; do echo "$(date): $pong"; done

Wed Jun 26 13:09:23 CEST 2013: PING www.google.fr (173.194.40.56) 56(84) bytes of data.
Wed Jun 26 13:09:23 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=1 ttl=57 time=7.26 ms
Wed Jun 26 13:09:24 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=2 ttl=57 time=8.14 ms

The credit goes to https://askubuntu.com/a/137246

Update style of a component onScroll in React.js

My bet here is using Function components with new hooks to solve it, but instead of using useEffect like in previous answers, I think the correct option would be useLayoutEffect for an important reason:

The signature is identical to useEffect, but it fires synchronously after all DOM mutations.

This can be found in React documentation. If we use useEffect instead and we reload the page already scrolled, scrolled will be false and our class will not be applied, causing an unwanted behavior.

An example:

import React, { useState, useLayoutEffect } from "react"

const Mycomponent = (props) => {
  const [scrolled, setScrolled] = useState(false)

  useLayoutEffect(() => {
    const handleScroll = e => {
      setScrolled(window.scrollY > 0)
    }

    window.addEventListener("scroll", handleScroll)

    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [])

  ...

  return (
    <div className={scrolled ? "myComponent--scrolled" : ""}>
       ...
    </div>
  )
}

A possible solution to the problem could be https://codepen.io/dcalderon/pen/mdJzOYq

const Item = (props) => { 
  const [scrollY, setScrollY] = React.useState(0)

  React.useLayoutEffect(() => {
    const handleScroll = e => {
      setScrollY(window.scrollY)
    }

    window.addEventListener("scroll", handleScroll)

    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [])

  return (
    <div class="item" style={{'--scrollY': `${Math.min(0, scrollY/3 - 60)}px`}}>
      Item
    </div>
  )
}

Can I use a :before or :after pseudo-element on an input field?

A working solution in pure CSS:

The trick is to suppose there's a dom element after the text-field.

_x000D_
_x000D_
/*_x000D_
 * The trick is here:_x000D_
 * this selector says "take the first dom element after_x000D_
 * the input text (+) and set its before content to the_x000D_
 * value (:before)._x000D_
 */_x000D_
input#myTextField + *:before {_x000D_
  content: "";_x000D_
} 
_x000D_
<input id="myTextField" class="mystyle" type="text" value="someValue" />_x000D_
<!--_x000D_
  There's maybe something after a input-text_x000D_
  Does'nt matter what it is (*), I use it._x000D_
  -->_x000D_
<span></span>
_x000D_
_x000D_
_x000D_

(*) Limited solution, though:

  • you have to hope that there's a following dom element,
  • you have to hope no other input field follows your input field.

But in most cases, we know our code so this solution seems efficient and 100% CSS and 0% jQuery.

Posting array from form

When you post that data, it is stored as an array in $_POST.

You could optionally do something like:

<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">

Then:

$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];

But I fail to see the point.

How to obtain the number of CPUs/cores in Linux from the command line?

Use below query to get core details

[oracle@orahost](TESTDB)$ grep -c ^processor /proc/cpuinfo
8

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I tried the other solutions here, they work but I'm lazy so this is my solution

  1. hover over the element to trigger expanded state
  2. ctrl+shift+c
  3. hover over element again
  4. right click
  5. navigate to the debugger

by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

By default Vagrant uses a generated private key to login, you can try this:

ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1

Loading resources using getClass().getResource()

getResource by example:

package szb.testGetResource;
public class TestGetResource {
    private void testIt() {
        System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
        System.out.println("test2: "+getClass().getResource("test.css"));
    }
    public static void main(String[] args) {
        new TestGetResource().testIt();
    }
}

enter image description here

output:

test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css

What is a "bundle" in an Android application

Just create a bundle,


Bundle simple_bundle=new Bundle();
simple_bundle.putString("item1","value1");
Intent i=new Intent(getApplicationContext(),this_is_the_next_class.class);
i.putExtras(simple_bundle);
startActivity(i);

IN the "this_is_the_next_class.class"

You can retrieve the items like this.

Intent receive_i=getIntent();
Bundle my_bundle_received=receive_i.getExtras();
my_bundle_received.get("item1");
Log.d("Value","--"+my_bundle_received.get("item1").toString);

Replace Div with another Div

This should help you

HTML

<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->

<table>
<tr class="thumb"></tr>
    <td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>   

<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />

<div id="mainmapplace">
    <div id="mainmap">
        All Regions image
    </div>
</div>
<div id="region">
    <div class="replace">northern image</div>
    <div class="replace">southern image</div>
    <div class="replace">Eastern image</div>
</div>

JavaScript

var originalmap;
var flag = false;

$(function (){

    $(".replace").click(function(){
            flag = true;
            originalmap = $('#mainmap');
            $('#mainmap').replaceWith($(this));
        });

    $('.showall').click(
        function(){
            if(flag == true){
                $('#region').append($('#mainmapplace .replace'));                
                $('#mainmapplace').children().remove();
                $('#mainmapplace').append($(originalmap));
                //$('#mapplace').append();
            }
        }
    )

})

CSS

#mainmapplace{
    width: 100px;
    height: 100px;
    background: red;
}

#region div{
    width: 100px;
    height: 100px;
    background: blue;
    margin: 10px 0 0 0;
}

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

keytool error bash: keytool: command not found

find your jre location ::sudo find / -name jre And then :: sudo update-alternatives --install /usr/bin/keytool keytool /opt/jdk/<jdk.verson>/jre/bin/keytool 100

SSH Key - Still asking for password and passphrase

TL;DR
You need to use an ssh agent. So, open terminal & before pushing to git, execute

ssh-add

enter your passphrase when prompted.

Check out the original StackExchange answer here

How can I get the last 7 characters of a PHP string?

Use substr() with a negative number for the 2nd argument.

$newstring = substr($dynamicstring, -7);

From the php docs:

string substr ( string $string , int $start [, int $length ] )

If start is negative, the returned string will start at the start'th character from the end of string.

Get current URL with jQuery?

You can log window.location and see all the options, for just the URL use:

window.location.origin

for the whole path use:

window.location.href

there's also location.__

.host
.hostname
.protocol
.pathname

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

Compiling/Executing a C# Source File in Command Prompt

While it is definitely a good thing knowing how to build at the command line, for most work it might be easier to use an IDE. The C# express edition is free and very good for the money ;-p

Alternatively, things like snippy can be used to run fragments of C# code.

Finally - note that the command line is implementation specific; for MS, it is csc; for mono, it is gmcs and friends.... Likewise, to execute: it is just "exename" for the MS version, but typically "mono exename" for mono.

Finally, many projects are build with build script tools; MSBuild, NAnt, etc.

How to iterate over each string in a list of strings and operate on it's elements

c=0
words = ['challa','reddy','challa']

for idx, word in enumerate(words):
    if idx==0:
        firstword=word
        print(firstword)
    elif idx == len(words)-1:
        lastword=word
        print(lastword)
        if firstword==lastword:
            c=c+1
            print(c)

How to convert int to float in C?

Integer division truncates, so (50/100) results in 0. You can cast to float (better double) or multiply with 100.0 (for double precision, 100.0f for float precision) first,

double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;

or

float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;

Since floating point arithmetic is not associative, the results of 100.0*number/total and (double)number/total * 100 may be slightly different (the same holds for float), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.