Programs & Examples On #Writeablebitmap

Writing html form data to a txt file without the use of a webserver

Something like this?

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">Please type in this box. When you 

click the Download button, the contents of this box will be downloaded to 

your machine at the location you specify. Pretty nifty. </textarea>
  <input type="submit" value="Download">
</form>
</body>
</html>

how to make password textbox value visible when hover an icon

In one line of code as below :

_x000D_
_x000D_
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
       onmouseout="this.type='password'" placeholder="password" />
_x000D_
_x000D_
_x000D_

How to get the list of properties of a class?

Try this:

var model = new MyObject();
foreach (var property in model.GetType().GetProperties())
{
    var descricao = property;
    var type = property.PropertyType.Name;
}

Measuring elapsed time with the Time module

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

Getting the parameters of a running JVM

You can use jps like

jps -lvm

prints something like

4050 com.intellij.idea.Main -Xms128m -Xmx512m -XX:MaxPermSize=250m -ea -Xbootclasspath/a:../lib/boot.jar -Djb.restart.code=88
4667 sun.tools.jps.Jps -lvm -Dapplication.home=/opt/java/jdk1.6.0_22 -Xms8m

How to know when a web page was last updated?

The last changed time comes with the assumption that the web server provides accurate information. Dynamically generated pages will likely return the time the page was viewed. However, static pages are expected to reflect actual file modification time.

This is propagated through the HTTP header Last-Modified. The Javascript trick by AZIRAR is clever and will display this value. Also, in Firefox going to Tools->Page Info will also display in the "Modified" field.

Best way to structure a tkinter application?

OOP should be the approach and frame should be a class variable instead of instance variable.

from Tkinter import *
class App:
  def __init__(self, master):
    frame = Frame(master)
    frame.pack()
    self.button = Button(frame, 
                         text="QUIT", fg="red",
                         command=frame.quit)
    self.button.pack(side=LEFT)
    self.slogan = Button(frame,
                         text="Hello",
                         command=self.write_slogan)
    self.slogan.pack(side=LEFT)
  def write_slogan(self):
    print "Tkinter is easy to use!"

root = Tk()
app = App(root)
root.mainloop()

enter image description here

Reference: http://www.python-course.eu/tkinter_buttons.php

How to compare variables to undefined, if I don’t know whether they exist?

!undefined is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:

if(<object or variable>) {
     //take actions if object is not undefined
} else {
     //take actions if object is undefined
}

How can I monitor the thread count of a process on linux?

JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.

More graphically is JConsole, which displays the thread count for a given process.

Read entire file in Scala?

I've been told that Source.fromFile is problematic. Personally, I have had problems opening large files with Source.fromFile and have had to resort to Java InputStreams.

Another interesting solution is using scalax. Here's an example of some well commented code that opens a log file using ManagedResource to open a file with scalax helpers: http://pastie.org/pastes/420714

What is the difference between PUT, POST and PATCH?

Simplest Explanation:

POST - Create NEW record

PUT - If the record exists, update else, create a new record

PATCH - update

GET - read

DELETE - delete

uppercase first character in a variable with bash

One way with sed:

echo "$(echo "$foo" | sed 's/.*/\u&/')"

Prints:

Bar

Entity Framework Provider type could not be loaded?

Simply reference or browser the EF dll - EntityFramework.SqlServer.dll

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I have encounter this issue too. And I'm running in XP SP3.

The following website http://www.docin.com/p-60410380.html# pointing out the solution. But it's simplified Chinese.

I translated its main idea into English here.

run regedit; open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectX Then you must change the following two items: Item 1: Name: Version, Type:REG_SZ, The value should be a rather little number to make the installation success.

Item 2: Name: SDKVersion. But in your machine, the name can be different, for example, it can be ManagedDirectXVersion. But the type should be REG_SZ. Type:REG_SZ, The value should be a rather little number to make the installation success.

In fact, you can refer to the DirectX.lgo file to find the exact version number.

It works for me.

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

adb command for getting ip address assigned by operator

Try this command, it will help you to get ipaddress

adb shell ifconfig tiwlan0

tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,

 adb shell netcfg

It will output like this

usb0     DOWN  0.0.0.0         0.0.0.0         0×00001002
sit0     DOWN  0.0.0.0         0.0.0.0         0×00000080
ip6tnl0  DOWN  0.0.0.0         0.0.0.0         0×00000080
gannet0  DOWN  0.0.0.0         0.0.0.0         0×00001082
rmnet0   UP    112.79.87.220   255.0.0.0       0x000000c1
rmnet1   DOWN  0.0.0.0         0.0.0.0         0×00000080
rmnet2   DOWN  0.0.0.0         0.0.0.0         0×00000080

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

How can I view an object with an alert()

If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log:

console.log(product);

If you want to view the properties of the object itself, don't alert the object, but its properties:

alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)

As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

#leftdiv,#rightdiv
{
    min-height: 600px;   
}

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

How to get the HTML for a DOM element in javascript

var x = $('#container').get(0).outerHTML;

top nav bar blocking top content of the page

<div class='navbar' data-spy="affix" data-offset-top="0">

If your navbar is on the top of the page originally, set the value to 0. Otherwise, set the value for data-offset-topto the value of the content above your navbar.

Meanwhile, you need to modify the css as such:

.affix{
  width:100%;
  top:0;
  z-index: 10;
}

Your password does not satisfy the current policy requirements

After running the command sudo mysql_secure_installation.

  1. Run sudo mysql to enter into the mysql prompt.
  2. Run this SELECT user,authentication_string,plugin,host FROM mysql.user; to check for user root to have as plugin auth_socket.
  3. Then do run uninstall plugin validate_password; to drop priviledges before running this ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';Be sure to change password to a strong password.

NOTE: check out this link https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04 for more help

Could not resolve all dependencies for configuration ':classpath'

I'm using Gradle plugin 3.0.1 and saw this error. Not sure what caused this but the solution that works for me is to stop the running Gradle daemon by ./gradlew --stop.

Credit card expiration dates - Inclusive or exclusive?

Have a look on one of your own credit cards. It'll have some text like EXPIRES END or VALID THRU above the date. So the card expires at the end of the given month.

Converting List<Integer> to List<String>

Here's a one-liner solution without cheating with a non-JDK library.

List<String> strings = Arrays.asList(list.toString().replaceAll("\\[(.*)\\]", "$1").split(", "));

How to set space between listView Items in Android

For my application, i have done this way

 <ListView
    android:id="@+id/staff_jobassigned_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="10dp">

</ListView>

just set the divider to null and providing height to the divider did for me.

Example :

android:divider="@null"

or

android:divider="@android:color/transparent"

and this is result

enter image description here

How to add external library in IntelliJ IDEA?

This question can also be extended if necessary jar file can be found in global library, how can you configure it into your current project.

Process like these: "project structure"-->"modules"-->"click your current project pane at right"-->"dependencies"-->"click little add(+) button"-->"library"-->"select the library you want".

if you are using maven and you can also configure dependency in your pom.xml, but it your chosen version is not like the global library, you will waste memory on storing another version of the same jar file. so i suggest use the first step.

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

You misspelled permission

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

C# how to use enum with switch

Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:

public double Calculate(int left, int right, Operator op) =>
            op switch 
        {
            Operator.PLUS => left + right,
            Operator.MINUS => left - right,
            Operator.MULTIPLY => left * right,
            Operator.DIVIDE => left / right,
            _    =>  0
        }

Ref. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

How to use glob() to find files recursively?

Simplified version of Johan Dahlin's answer, without fnmatch.

import os

matches = []
for root, dirnames, filenames in os.walk('src'):
  matches += [os.path.join(root, f) for f in filenames if f[-2:] == '.c']

How to add text at the end of each line in Vim?

If you want to add ',' at end of the lines starting with 'key', use:

:%s/key.*$/&,

Creating a recursive method for Palindrome

public static boolean isPalindrome(String in){
   if(in.equals(" ") || in.length() < 2 ) return true;
   if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
      return isPalindrome(in.substring(1,in.length-2));
   else
      return false;
 }

Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.

Multiple commands in an alias for bash

The other answers answer the question adequately, but your example looks like the second command depends on the first one being exiting successfully. You may want to try a short-circuit evaluation in your alias:

alias lock='gnome-screensaver && gnome-screensaver-command --lock'

Now the second command will not even be attempted unless the first one is successful. A better description of short-circuit evaluation is described in this SO question.

How do you make websites with Java?

Read the tutorial on Java Web applications.

Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.

All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).

Here is a Tomcat tutorial.

Async await in linq select

I used this code:

public static async Task<IEnumerable<TResult>> SelectAsync<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> method)
{
      return await Task.WhenAll(source.Select(async s => await method(s)));
}

like this:

var result = await sourceEnumerable.SelectAsync(async s=>await someFunction(s,other params));

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Personally, I found that, since we maintain a ngRoutes collection (long story) i find the most enjoyment from:

GOTO(ri) {
    this.router.navigate(this.ngRoutes[ri]);
}

I actually use it as part of one of our interview questions. This way, I can get a near-instant read at who's been developing forever by watching who twitches when they run into GOTO(1) for Homepage redirection.

How to vertically center <div> inside the parent element with CSS?

have you try this one?

.parentdiv {
 margin: auto;
 position: absolute;
 top: 0; left: 0; bottom: 0; right: 0;
 height: 300px; // at least you have to specify height
}

hope this helps

Move textfield when keyboard appears swift

I love clean Swift code. So here's the tightest code I could come up with to move a text view up/down with the keyboard. It's currently working in an iOS8/9 Swift 2 production app.

UPDATE (March 2016): I just tightened up my previous code as much as possible. Also, there are a bunch of popular answers here that hardcode the keyboard height and animation parameters. There's no need for that, not to mention that the numbers in these answers don't always line up with the actual values I'm seeing on my 6s+ iOS9 (keyboard height of 226, duration of 0.25, and animation curve of 7). In any case, it's almost no extra code to get those values straight from the system. See below.

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}

func animateWithKeyboard(notification: NSNotification) {

    // Based on both Apple's docs and personal experience, 
    // I assume userInfo and its documented keys are available.
    // If you'd like, you can remove the forced unwrapping and add your own default values.

    let userInfo = notification.userInfo!
    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
    let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
    let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
    let moveUp = (notification.name == UIKeyboardWillShowNotification)

    // baseContraint is your Auto Layout constraint that pins the
    // text view to the bottom of the superview.

    baseConstraint.constant = moveUp ? -keyboardHeight : 0

    let options = UIViewAnimationOptions(rawValue: curve << 16)
    UIView.animateWithDuration(duration, delay: 0, options: options,
        animations: {
            self.view.layoutIfNeeded()
        },
        completion: nil
    )

}

NOTE: This code covers the most comment/general case. However, more code may be needed to handle different orientations and/or custom keyboards Here's an in-depth article on working with the iOS keyboard. If you need to handle every scenario, this may help.

How would I stop a while loop after n amount of time?

I have read this but I just want to ask something, wouldn't something like I have written work at all? I have done the testing for 5,10 and 20 seconds. Its time isn't exactly accurate but they are really close to the actual values.

import time

begin_time=0
while begin_time<5:

    begin_time+=1
    time.sleep(1.0)
print("The Work is Done")

How to make child element higher z-index than parent?

Nothing is impossible. Use the force.

.parent {
    position: relative;
}

.child {
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
}

Convert pandas dataframe to NumPy array

Note: The .as_matrix() method used in this answer is deprecated. Pandas 0.23.4 warns:

Method .as_matrix will be removed in a future version. Use .values instead.


Pandas has something built in...

numpy_matrix = df.as_matrix()

gives

array([[nan, 0.2, nan],
       [nan, nan, 0.5],
       [nan, 0.2, 0.5],
       [0.1, 0.2, nan],
       [0.1, 0.2, 0.5],
       [0.1, nan, 0.5],
       [0.1, nan, nan]])

How to increase heap size of an android application?

This can be done by two ways according to your Android OS.

  1. You can use android:largeHeap="true" in application tag of Android manifest to request a larger heap size, but this will not work on any pre Honeycomb devices.
  2. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above See below how to do it.
VMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE);

Before Setting HeapSize make sure that you have entered the appropriate size which will not affect other application or OS functionality. Before settings just check how much size your app takes & then set the size just to fulfill your job. Dont use so much of memory otherwise other apps might affect.

Reference: http://dwij.co.in/increase-heap-size-of-android-application

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Git - Won't add files?

Double check your .gitignore file to make sure that the file is able to be seen by Git. Likewise, there is a file .git/info/exclude that 'excludes' files/directories from the project, just like a .gitignore file would.

Make .gitignore ignore everything except a few files

Gist

# Ignore everything
*

# But not these files...
!script.pl
!template.latex

And probably include:

!.gitignore

Reference

From https://git-scm.com/docs/gitignore:

An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined. Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, "\!important!.txt".

...

Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):

$ cat .gitignore
# exclude everything except directory foo/bar
/*
!/foo
/foo/*
!/foo/bar

How to find top three highest salary in emp table in oracle?

You can try.

   SELECT * FROM 
     (
      SELECT EMPLOYEE, LAST_NAME, SALARY,
      RANK() OVER (ORDER BY SALARY DESC) EMPRANK
      FROM emp
     )
    WHERE emprank <= 3;

This will give correct output even if there are two employees with same maximun salary

How to apply a CSS filter to a background image

As stated in other answers this can be achieved with:

  • A copy of the blurred image as the background.
  • A pseudo element that can be filtered then positioned behind the content.

You can also use backdrop-filter

There is a supported property called backdrop-filter, and it is currently supported in Chrome 76, Edge, Safari, and iOS Safari (see caniuse.com for statistics).

From Mozilla devdocs:

The backdrop-filter property provides for effects like blurring or color shifting the area behind an element, which can then be seen through that element by adjusting the element's transparency/opacity.

See caniuse.com for usage statistics.

You would use it like so. If you do not want content inside to be blurred use the utility class .u-non-blurred

_x000D_
_x000D_
.background-filter::after {
  -webkit-backdrop-filter: blur(5px); /* Use for Safari 9+, Edge 17+ (not a mistake) and iOS Safari 9.2+ */
  backdrop-filter: blur(5px); /* Supported in Chrome 76 */

  content: "";
  display: block;
  position: absolute;
  width: 100%; height: 100%;
  top: 0;
}

.background-filter {
  position: relative;
}

.background {
  background-image: url('https://upload.wikimedia.org/wikipedia/en/6/62/Kermit_the_Frog.jpg');
  width: 200px;
  height: 200px;
}

/* Use for content that should not be blurred */
.u-non-blurred {
  position: relative;
  z-index: 1;
}
_x000D_
<div class="background background-filter"></div>
<div class="background background-filter">
  <h1 class="u-non-blurred">Kermit D. Frog</h1>
</div>
_x000D_
_x000D_
_x000D_

Update (12/06/2019): Chromium will ship with backdrop-filter enabled by default in version 76 which is due out 30/07/2019.

Update (01/06/2019): The Mozzilla Firefox team has announced it will start working on implementing this soon.

Update (21/05/2019): Chromium just announced backdrop-filter is available in chrome canary without enabling "Enable Experimental Web Platform Features" flag. This means backdrop-filter is very close to being implemented on all chrome platforms.

Array of char* should end at '\0' or "\0"?

I would end it with NULL. Why? Because you can't do either of these:

array[index] == '\0'
array[index] == "\0"

The first one is comparing a char * to a char, which is not what you want. You would have to do this:

array[index][0] == '\0'

The second one doesn't even work. You're comparing a char * to a char *, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use == to compare two strings, you have to use the strcmp() function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:

array[index] == NULL

Works just fine and conveys your point.

Get an OutputStream into a String

I would use a ByteArrayOutputStream. And on finish you can call:

new String( baos.toByteArray(), codepage );

or better:

baos.toString( codepage );

For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

The method toString() accepts only a String as a codepage parameter (stand Java 8).

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

How to copy a map?

You have to manually copy each key/value pair to a new map. This is a loop that people have to reprogram any time they want a deep copy of a map.

You can automatically generate the function for this by installing mapper from the maps package using

go get -u github.com/drgrib/maps/cmd/mapper

and running

mapper -types string:aStruct

which will generate the file map_float_astruct.go containing not only a (deep) Copy for your map but also other "missing" map functions ContainsKey, ContainsValue, GetKeys, and GetValues:

func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
    _, ok := m[k]
    return ok
}

func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
    for _, mValue := range m {
        if mValue == v {
            return true
        }
    }

    return false
}

func GetKeysStringAStruct(m map[string]aStruct) []string {
    keys := []string{}

    for k, _ := range m {
        keys = append(keys, k)
    }

    return keys
}

func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
    values := []aStruct{}

    for _, v := range m {
        values = append(values, v)
    }

    return values
}

func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
    copyMap := map[string]aStruct{}

    for k, v := range m {
        copyMap[k] = v
    }

    return copyMap
}

Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map for different type combinations.

Custom Cell Row Height setting in storyboard is not responding

The same problem occurred when working on XCode 9 using Swift 4.

Add AutoLayout for the UI elements inside the Cell and custom cell row height will work accordingly as specified.

If statement for strings in python?

If should be if. Your program should look like this:

answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
    print("this will do the calculation")
else:
    exit()

Note also that the indentation is important, because it marks a block in Python.

Disable same origin policy in Chrome

You can use this chrome plugin called "Allow-Control-Allow-Origin: *" ... It make it a dead simple and work very well. check it here: *

Chrome extenstion

Is there a wikipedia API just for retrieve content summary?

Since 2017 Wikipedia provides a REST API with better caching. In the documentation you can find the following API which perfectly fits your use case. (as it is used by the new Page Previews feature)

https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow returns the following data which can be used to display a summery with a small thumbnail:

{
  "type": "standard",
  "title": "Stack Overflow",
  "displaytitle": "Stack Overflow",
  "extract": "Stack Overflow is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.",
  "extract_html": "<p><b>Stack Overflow</b> is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of <i>Coding Horror</i>, Atwood's popular programming blog.</p>",
  "namespace": {
    "id": 0,
    "text": ""
  },
  "wikibase_item": "Q549037",
  "titles": {
    "canonical": "Stack_Overflow",
    "normalized": "Stack Overflow",
    "display": "Stack Overflow"
  },
  "pageid": 21721040,
  "thumbnail": {
    "source": "https://upload.wikimedia.org/wikipedia/en/thumb/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png/320px-Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 320,
    "height": 149
  },
  "originalimage": {
    "source": "https://upload.wikimedia.org/wikipedia/en/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 462,
    "height": 215
  },
  "lang": "en",
  "dir": "ltr",
  "revision": "902900099",
  "tid": "1a9cdbc0-949b-11e9-bf92-7cc0de1b4f72",
  "timestamp": "2019-06-22T03:09:01Z",
  "description": "website hosting questions and answers on a wide range of topics in computer programming",
  "content_urls": {
    "desktop": {
      "page": "https://en.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.wikipedia.org/wiki/Stack_Overflow?action=history",
      "edit": "https://en.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.wikipedia.org/wiki/Talk:Stack_Overflow"
    },
    "mobile": {
      "page": "https://en.m.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.m.wikipedia.org/wiki/Special:History/Stack_Overflow",
      "edit": "https://en.m.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.m.wikipedia.org/wiki/Talk:Stack_Overflow"
    }
  },
  "api_urls": {
    "summary": "https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow",
    "metadata": "https://en.wikipedia.org/api/rest_v1/page/metadata/Stack_Overflow",
    "references": "https://en.wikipedia.org/api/rest_v1/page/references/Stack_Overflow",
    "media": "https://en.wikipedia.org/api/rest_v1/page/media/Stack_Overflow",
    "edit_html": "https://en.wikipedia.org/api/rest_v1/page/html/Stack_Overflow",
    "talk_page_html": "https://en.wikipedia.org/api/rest_v1/page/html/Talk:Stack_Overflow"
  }
}

By default, it follows redirects (so that /api/rest_v1/page/summary/StackOverflow also works), but this can be disabled with ?redirect=false

If you need to access the API from another domain you can set the CORS header with &origin= (e.g. &origin=*)

Update 2019: The API seems to return more useful information about the page.

Convert string to float?

public class NumberFormatExceptionExample {
private static final String str = "123.234";
public static void main(String[] args){
float i = Float.valueOf(str); //Float.parseFloat(str);
System.out.println("Value parsed :"+i);
}
}

This should resolve the problem.

Can anyone suggest how should we handle this when the string comes in 35,000.00

How can I get onclick event on webview in android?

This works for me

webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                // Do what you want
                                return false;
                            }
                        });

How to set shadows in React Native for android?

I added borderBottomWidth: 0 and it worked fine for me in android.

Set TextView text from html-formatted string resource in XML

Escape your HTML tags ...

<resources>
    <string name="somestring">
        &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt;
        Content
    </string>
</resources>

Detect if HTML5 Video element is playing

Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events

_x000D_
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head>  _x000D_
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> _x000D_
<title>Html5 media events</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head> _x000D_
<body >_x000D_
    <div id="output"></div>_x000D_
    <video id="myVideo" width="320" height="176" controls autoplay>_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">_x000D_
    </video>_x000D_
    <script>_x000D_
        var media = document.getElementById('myVideo');_x000D_
_x000D_
        // Playing event_x000D_
        media.addEventListener("playing", function() {_x000D_
            $("#output").html("Playing event triggered");_x000D_
        });_x000D_
   _x000D_
        // Pause event_x000D_
        media.addEventListener("pause", function() { _x000D_
            $("#output").html("Pause event triggered"); _x000D_
        });_x000D_
_x000D_
        // Seeking event_x000D_
        media.addEventListener("seeking", function() { _x000D_
            $("#output").html("Seeking event triggered"); _x000D_
        });_x000D_
_x000D_
        // Volume changed event_x000D_
        media.addEventListener("volumechange", function(e) { _x000D_
            $("#output").html("Volumechange event triggered"); _x000D_
        });_x000D_
_x000D_
    </script>   _x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_

Get file name from URI string in C#

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(hrefLink.Replace("/", "\\"));
}

THis assumes, of course, that you've parsed out the file name.

EDIT #2:

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}

This should handle spaces and the like in the file name.

How can I close a login form and show the main form without my application closing?

Try this:

public void ShowMain()
    {
        if(auth()) // a method that returns true when the user exists.
        { 
            this.Close();
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
            t.Start();
        }
        else
        {
            MessageBox.Show("Invalid login details.");
        }         
    }
   [STAThread]
   public void Main()
   {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Main());

   }

You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.

One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.

Hope this helps.

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

How to get all keys with their values in redis

I had the same problem, and I felt on your post.

I think the easiest way to solve this issue is by using redis Hashtable.

It allows you to save a Hash, with different fields and values associated with every field.

To get all the fiels and values client.HGETALLL does the trick. It returns an array of

all the fields followed by their values.

More informations here https://redis.io/commands/hgetall

React - clearing an input value after form submit

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

Programmatically read from STDIN or input file in Perl

If there is a reason you can't use the simple solution provided by ennuikiller above, then you will have to use Typeglobs to manipulate file handles. This is way more work. This example copies from the file in $ARGV[0] to that in $ARGV[1]. It defaults to STDIN and STDOUT respectively if files are not specified.

use English;

my $in;
my $out;

if ($#ARGV >= 0){
    unless (open($in,  "<", $ARGV[0])){
      die "could not open $ARGV[0] for reading.";
    }
}
else {
    $in  = *STDIN;
}

if ($#ARGV >= 1){
    unless (open($out, ">", $ARGV[1])){
      die "could not open $ARGV[1] for writing.";
    }
}
else {
    $out  = *STDOUT;
}

while ($_ = <$in>){
    $out->print($_);
}

Simplest way to read json from a URL in java

I have found this to be the easiest way by far.

Use this method:

public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

And use it like this:

String json = getJSON(url);
JSONObject obj;
   try {
         obj = new JSONObject(json);
         JSONArray results_arr = obj.getJSONArray("results");
         final int n = results_arr.length();
            for (int i = 0; i < n; ++i) {
                // get the place id of each object in JSON (Google Search API)
                String place_id = results_arr.getJSONObject(i).getString("place_id");
            }


   }

jQuery hover and class selector

Your code looks fine to me.

Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:

$(function() {
   $('.menuItem').hover( function(){
      $(this).css('background-color', '#F00');
   },
   function(){
      $(this).css('background-color', '#000');
   });
});

How to get current working directory using vba?

Simple Example below:

Sub openPath()
Dim path As String
path = Application.ActivePresentation.path
Shell Environ("windir") & "\explorer.exe """ & path & "", vbNormalFocus
End Sub

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I change my APIs as * cglib --- to ---> cglib-nodep-2.2.jar * cglib-asm --- to ---> cglib-asm.jar (i.e. latest one )

Does Visual Studio Code have box select/multi-line edit?

For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.

Visual Studio Code supports multiple line edit.

Passing array in GET for a REST call

I think it's a better practice to serialize your REST call parameters, usually by JSON-encoding them:

/appointments?users=[id1,id2]

or even:

/appointments?params={users:[id1,id2]}

Then you un-encode them on the server. This is going to give you more flexibility in the long run.

Just make sure to URLEncode the params as well before you send them!

Java properties UTF-8 encoding in Eclipse

You can define UTF-8 .properties files to store your translations and use ResourceBundle, to get values. To avoid problems you can change encoding:

String value = RESOURCE_BUNDLE.getString(key); 
return new String(value.getBytes("ISO-8859-1"), "UTF-8");

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

There may be a problem with Maven path configuration, if you used unix-like Operator System.

step 1: create new file in path ~/.bash_profile

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
CLASSPAHT=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
PATH=$JAVA_HOME/bin:$PATH:
export JAVA_HOME
export CLASSPATH
export PATH

step 2: shell run source ~/.bash_profile OR modify zsh config file(add new line: source ~/.bash_profile)

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Negative margins are valid in css and understanding their (compliant) behaviour is mainly based on the box model and margin collapsing. While certain scenarios are more complex, a lot of common mistakes can be avoided after studying the spec.

For instance, rendering of your sample code is guided by the css spec as described in calculating heights and margins for absolutely positioned non-replaced elements.

If I were to make a graphical representation, I'd probably go with something like this (not to scale):

negative top margin

The margin box lost 8px on the top, however this does not affect the content & padding boxes. Because your element is absolutely positioned, moving the element 8px up does not cause any further disturbance to the layout; with static in-flow content that's not always the case.

Bonus:

Still need convincing that reading specs is the way to go (as opposed to articles like this)? I see you're trying to vertically center the element, so why do you have to set margin-top:-8px; and not margin-top:-50%;?

Well, vertical centering in CSS is harder than it should be. When setting even top or bottom margins in %, the value is calculated as a percentage always relative to the width of the containing block. This is rather a common pitfall and the quirk is rarely described outside of w3 docos

Send XML data to webservice using php curl

If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you

vba: get unique values from array

There's no built-in functionality to remove duplicates from arrays. Raj's answer seems elegant, but I prefer to use dictionaries.

Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
'Set d = New Scripting.Dictionary

Dim i As Long
For i = LBound(myArray) To UBound(myArray)
    d(myArray(i)) = 1
Next i

Dim v As Variant
For Each v In d.Keys()
    'd.Keys() is a Variant array of the unique values in myArray.
    'v will iterate through each of them.
Next v

EDIT: I changed the loop to use LBound and UBound as per Tomalak's suggested answer. EDIT: d.Keys() is a Variant array, not a Collection.

Write single CSV file using spark-csv

repartition/coalesce to 1 partition before you save (you'd still get a folder but it would have one part file in it)

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

iOS: Compare two dates

After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

You can change it to difference between hours also.

Enjoy!


Edit 1

If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date]; && NSTimeInterval distance

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];

How do I Merge two Arrays in VBA?

Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.

Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim arrToReturn() As Variant, myCollection As New Collection
 For Each x In arr1: myCollection.Add x: Next
 For Each y In arr2: myCollection.Add y: Next

 ReDim arrToReturn(1 To myCollection.Count)
 For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
 joinArrays = arrToReturn
End Function

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Extract only right most n letters from a string

Without resorting to the bit converter and bit shifting (need to be sure of encoding) this is fastest method I use as an extension method 'Right'.

string myString = "123456789123456789";

if (myString > 6)
{

        char[] cString = myString.ToCharArray();
        Array.Reverse(myString);
        Array.Resize(ref myString, 6);
        Array.Reverse(myString);
        string val = new string(myString);
}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I fixed it just by editing the gradle-wrapper.properties file.

You must go to the project folder, then /android/grandle/wrapper/gradle-wrapper.properties. In DistributionUrl, change to https \: //services.gradle.org/distributions/gradle-6.4.1-all.zip.

Deleting all files in a directory with Python

you can create a function. Add maxdepth as you like for traversing subdirectories.

def findNremove(path,pattern,maxdepth=1):
    cpath=path.count(os.sep)
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                    try:
                        print "Removing %s" % (os.path.join(r,files))
                        #os.remove(os.path.join(r,files))
                    except Exception,e:
                        print e
                    else:
                        print "%s removed" % (os.path.join(r,files))

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")

Entity Framework The underlying provider failed on Open

  1. Search "Component Services" in Programs and Files
  2. Go to Services
  3. Find "Distributed Transaction Coordinator" Service
  4. Right click and Restart the Service

You've just done a restart of the service and the code should run without errors

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

Get position/offset of element relative to a parent container?

Example

So, if we had a child element with an id of "child-element" and we wanted to get it's left/top position relative to a parent element, say a div that had a class of "item-parent", we'd use this code.

var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);

Plugin Finally, for the actual plugin (with a few notes expalaining what's going on):

// offsetRelative (or, if you prefer, positionRelative)
(function($){
    $.fn.offsetRelative = function(top){
        var $this = $(this);
        var $parent = $this.offsetParent();
        var offset = $this.position();
        if(!top) return offset; // Didn't pass a 'top' element 
        else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
        else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to 
        else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to 
        else { // Get parent's relative offset
            var parent_offset = $parent.offsetRelative(top);
            offset.top += parent_offset.top;
            offset.left += parent_offset.left;
            return offset;
        }
    };
    $.fn.positionRelative = function(top){
        return $(this).offsetRelative(top);
    };
}(jQuery));

Note : You can Use this on mouseClick or mouseover Event

$(this).offsetRelative("div.item-parent");

How to get span tag inside a div in jQuery and assign a text?

Try this:

$("#message span").text("hello world!");

See it in your code!

function Errormessage(txt) {
    var m = $("#message");

    // set text before displaying message
    m.children("span").text(txt);

    // bind close listener
    m.children("a.close-notify").click(function(){
      m.fadeOut("slow");
    });

    // display message
    m.fadeIn("slow");
}

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

Passing a Bundle on startActivity()?

You can use the Bundle from the Intent:

Bundle extras = myIntent.getExtras();
extras.put*(info);

Or an entire bundle:

myIntent.putExtras(myBundle);

Is this what you're looking for?

CMake does not find Visual C++ compiler

I got this problem with CMake 3.12.1, after an update of Visual Studio 2017. I simply re-ran CMake and it worked.

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

What are some good SSH Servers for windows?

I agree that cygwin/OpenSSH is the best choice, but its setup can be involved to say the least. Here is a document to get you started though: Installing OpenSSH

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

Create mysql table directly from CSV file using the CSV Storage engine?

This is not possible, you can however overwrite an existing table file. But be sure, that the line endings in your file are unix style (ending only with \n), not windows style (ending with \r\n), whether you are working under windows or not.

Unable to generate an explicit migration in entity framework

I had the same problems and was only able to resolve it running Add-Migration 'MigrationName' -Force

With -Force being the important part.

How to know elastic search installed version from kibana?

You can check version of ElasticSearch by the following command. It returns some other information also:

curl -XGET 'localhost:9200'

{
  "name" : "Forgotten One",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.3.4",
    "build_hash" : "e455fd0c13dceca8dbbdbb1665d068ae55dabe3f",
    "build_timestamp" : "2016-06-30T11:24:31Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.0"
  },
  "tagline" : "You Know, for Search"
}

Here you can see the version number: 2.3.4

Typically Kibana is installed in /opt/logstash/bin/kibana . So you can get the kibana version as follows

/opt/kibana/bin/kibana --version

How do you disable browser Autocomplete on web form field / input tag?

A workaround is not to insert the password field into the DOM before the user wants to change the password. This may be applicable in certain cases:

In our system we have a password field which in an admin page, so we must avoid inadvertently setting other users' passwords. The form has an extra checkbox that will toggle the password field visibility for this reason.

So in this case, autofill from a password manager becomes a double problem, because the input won't even be visible to the user.

The solution was to have the checkbox trigger whether the password field is inserted in the DOM, not just its visibility.

Pseudo implementation for AngularJS:

<input type="checkbox" ng-model="createPassword">
<input ng-if="changePassword" type="password">

Gather multiple sets of columns

In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

df %>% 
    gather(question_number, value, starts_with("Q3.")) %>%
    mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
    select(id, time, loop_number, question_number, value) %>% 
    spread(key = question_number, value = value)

The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

How to create cross-domain request?

For me it was another problem. This might be trivial for some, but it took me a while to figure out. So this answer might be helpfull to some.

I had my API_BASE_URL set to localhost:58577. The coin dropped after reading the error message for the millionth time. The problem is in the part where it says that it only supports HTTP and some other protocols. I had to change the API_BASE_URL so that it includes the protocol. So changing API_BASE_URL to http://localhost:58577 it worked perfectly.

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

Angles between two n-dimensional vectors in Python

Building on sgt pepper's great answer and adding support for aligned vectors plus adding a speedup of over 2x using Numba

@njit(cache=True, nogil=True)
def angle(vector1, vector2):
    """ Returns the angle in radians between given vectors"""
    v1_u = unit_vector(vector1)
    v2_u = unit_vector(vector2)
    minor = np.linalg.det(
        np.stack((v1_u[-2:], v2_u[-2:]))
    )
    if minor == 0:
        sign = 1
    else:
        sign = -np.sign(minor)
    dot_p = np.dot(v1_u, v2_u)
    dot_p = min(max(dot_p, -1.0), 1.0)
    return sign * np.arccos(dot_p)

@njit(cache=True, nogil=True)
def unit_vector(vector):
    """ Returns the unit vector of the vector.  """
    return vector / np.linalg.norm(vector)

def test_angle():
    def npf(x):
        return np.array(x, dtype=float)
    assert np.isclose(angle(npf((1, 1)), npf((1,  0))),  pi / 4)
    assert np.isclose(angle(npf((1, 0)), npf((1,  1))), -pi / 4)
    assert np.isclose(angle(npf((0, 1)), npf((1,  0))),  pi / 2)
    assert np.isclose(angle(npf((1, 0)), npf((0,  1))), -pi / 2)
    assert np.isclose(angle(npf((1, 0)), npf((1,  0))),  0)
    assert np.isclose(angle(npf((1, 0)), npf((-1, 0))),  pi)

%%timeit results without Numba

  • 359 µs ± 2.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

And with

  • 151 µs ± 820 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

PHP - print all properties of an object

<?php var_dump(obj) ?>

or

<?php print_r(obj) ?>

These are the same things you use for arrays too.

These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.

If you want to know the member methods you can use get_class_methods():

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) 
{
    echo "$method_name<br/>";
}

Related stuff:

get_object_vars()

get_class_vars()

get_class() <-- for the name of the instance

Running the new Intel emulator for Android

Using SDK Manager to download Intel HAX did not work.

Downloading and installing it from the Intel website did work. http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/

Top Tip: making the change in my BIOS to enable virtualization and then using "restart" did not enable virtualization. Doing a cold boot (i.e. shutdown and restart) suddenly made it appear.

The first step (on Windows) is to make sure that the Micrsoft Hardware-Assisted Virtualization Tool reports that "this computer is configured with hardware-assisted virtualization". http://www.microsoft.com/en-us/download/details.aspx?id=592

How to Consolidate Data from Multiple Excel Columns All into One Column

Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.

Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.

Press Alt+F11 to open the VBE

Press Control+R to view the Project Explorer

Navigate to the project for your workbook and choose Insert - Module

Paste this code in the code pane

Sub MakeOneColumn()

    Dim vaCells As Variant
    Dim vOutput() As Variant
    Dim i As Long, j As Long
    Dim lRow As Long

    If TypeName(Selection) = "Range" Then
        If Selection.Count > 1 Then
            If Selection.Count <= Selection.Parent.Rows.Count Then
                vaCells = Selection.Value

                ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)

                For j = LBound(vaCells, 2) To UBound(vaCells, 2)
                    For i = LBound(vaCells, 1) To UBound(vaCells, 1)
                        If Len(vaCells(i, j)) > 0 Then
                            lRow = lRow + 1
                            vOutput(lRow, 1) = vaCells(i, j)
                        End If
                    Next i
                Next j

                Selection.ClearContents
                Selection.Cells(1).Resize(lRow).Value = vOutput
            End If
        End If
    End If

End Sub

Press F5 to run the code

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

There are a few options available for you depending on the library in question, how it's written, and what level of accuracy you're looking for. Let's review the options, in roughly descending order of desirability.

Maybe It Exists Already

Always check DefinitelyTyped (https://github.com/DefinitelyTyped/DefinitelyTyped) first. This is a community repo full of literally thousands of .d.ts files and it's very likely the thing you're using is already there. You should also check TypeSearch (https://microsoft.github.io/TypeSearch/) which is a search engine for NPM-published .d.ts files; this will have slightly more definitions than DefinitelyTyped. A few modules are also shipping their own definitions as part of their NPM distribution, so also see if that's the case before trying to write your own.

Maybe You Don't Need One

TypeScript now supports the --allowJs flag and will make more JS-based inferences in .js files. You can try including the .js file in your compilation along with the --allowJs setting to see if this gives you good enough type information. TypeScript will recognize things like ES5-style classes and JSDoc comments in these files, but may get tripped up if the library initializes itself in a weird way.

Get Started With --allowJs

If --allowJs gave you decent results and you want to write a better definition file yourself, you can combine --allowJs with --declaration to see TypeScript's "best guess" at the types of the library. This will give you a decent starting point, and may be as good as a hand-authored file if the JSDoc comments are well-written and the compiler was able to find them.

Get Started with dts-gen

If --allowJs didn't work, you might want to use dts-gen (https://github.com/Microsoft/dts-gen) to get a starting point. This tool uses the runtime shape of the object to accurately enumerate all available properties. On the plus side this tends to be very accurate, but the tool does not yet support scraping the JSDoc comments to populate additional types. You run this like so:

npm install -g dts-gen
dts-gen -m <your-module>

This will generate your-module.d.ts in the current folder.

Hit the Snooze Button

If you just want to do it all later and go without types for a while, in TypeScript 2.0 you can now write

declare module "foo";

which will let you import the "foo" module with type any. If you have a global you want to deal with later, just write

declare const foo: any;

which will give you a foo variable.

Better way to Format Currency Input editText?

In case someone is interested in a way of doing it using RxBinding and Kotlin:

var isEditing = false

RxTextView.textChanges(dollarValue)
            .filter { !isEditing }
            .filter { it.isNotBlank() }
            .map { it.toString().filter { it.isDigit() } }
            .map { BigDecimal(it).setScale(2, BigDecimal.ROUND_FLOOR).divide(100.toBigDecimal(), BigDecimal.ROUND_FLOOR) }
            .map { NumberFormat.getCurrencyInstance(Locale("pt", "BR")).format(it) }
            .subscribe {
                isEditing = true
                dollarValue.text = SpannableStringBuilder(it)
                dollarValue.setSelection(it.length)
                isEditing = false
            }

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

bool to int conversion

int x = 4<5;

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

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

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


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

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

§7.16 from C99 says,

The macro bool expands to _Bool.

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

When is the finalize() method called in Java?

Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:

protected void finalize(){
    // This is where the finalization code is entered
}

With the protected keyword, access to finalize() by code outside its class is prevented. It is important to understand that finalize() is called just just before the garbage collection. It is not called when an object leaves the scope, for example. It means you can not know when, or if, finalize() will be executed. As a result, the program must provide other means to free system resources or other resources used by the object. You should not rely on finalize() for normal running of the program.

Rename column SQL Server 2008

You can use sp_rename to rename a column.

USE YourDatabase;  
GO  
EXEC sp_rename 'TableName.OldColumnName', 'NewColumnName', 'COLUMN';  
GO  

The first parameter is the object to be modified, the second parameter is the new name that will be given to the object, and the third parameter COLUMN informs the server that the rename is for the column, and can also be used to rename tables, index and alias data type.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

If you are working with Source safe then make a new directory and take the latest there, this solved my issue...thanks

Angular2 QuickStart npm start is not working correctly

I met the same error. And after a lot search, I finally found this one: Angular2 application install & run via package.json. Then I tried to replace

"scripts": { "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ", "lite": "lite-server", "postinstall": "typings install", "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings" }, to

"scripts": { "start": "concurrently \"npm run tsc:w\" \"npm run lite\" ", "lite": "lite-server", "postinstall": "typings install", "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings" },

Hope it helps who get the same error.

PS: My error is not the same as Tomasz, which is my npm version is 3.7.3 and node version is 5.9.1.

recursion versus iteration

Most of the answers seem to assume that iterative = for loop. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.

All (computable) functions can be implemented both recursively and using while loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.

What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom

 <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>2.0.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
  </dependency>

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

How do I see the current encoding of a file in Sublime Text?

ShowEncoding is another simple plugin that shows you the encoding in the status bar. That's all it does, to convert between encodings use the built-in "Save with Encoding" and "Reopen with Encoding" commands.

Optimal way to DELETE specified rows from Oracle

I have tried this code and It's working fine in my case.

DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
  (
      SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
      FROM NG_USR_0_CLIENT_GRID_NEW
      WHERE wi_name = 'NB-0000001385-Process'
  )
  WHERE RN=2
);

Killing a process created with Python's subprocess.Popen()

Only use Popen kill method

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

Why split the <script> tag when writing it with document.write()?

The </script> inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).

To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
    }
    // -->
</script>

...but to be honest, using document.write is not something I would consider best practice. Why not manipulating the DOM directly?

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
        document.body.appendChild(script);
    }
    // -->
</script>

List submodules in a Git repository

git config allows to specify a config file.
And .gitmodules is a config file.

So, with the help of "use space as a delimiter with cut command":

git config --file=.gitmodules --get-regexp ^^submodule.*\.path$ | cut -d " " -f 2

That will list only the paths, one per declared submodule.

As Tino points out in the comments:

  • This fails for submodules with spaces in it.
  • submodule paths may contain newlines, as in

    git submodule add https://github.com/hilbix/bashy.git "sub module"
      git mv 'sub module' $'sub\nmodule'
    

As a more robust alternative, Tino proposes:

git config -z --file .gitmodules --get-regexp '\.path$' | \
  sed -nz 's/^[^\n]*\n//p' | \
  tr '\0' '\n' 

For paths with newlines in them (they can be created with git mv), leave away the | tr '\0' '\n' and use something like ... | while IFS='' read -d '' path; do ... for further processing with bash.
This needs a modern bash which understands read -d '' (do not forget the space between -d and '').

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

What about error messages in use site?

And what about when comes the use case one needs to integrate existing types with a custom one that fits a DSL. One have to be well educated on matters of association, precedence, implicit conversions, implicit parameters, higher kinds, and maybe existential types.

It's very good to know that mostly it's simple but it's not necessarily enough. At least there must be one guy who knows this stuff if widespread library is to be designed.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I encountered a similar problem using windows command line for R script, Rscript.exe, which is very sensitive to spaces in the path. The solution was to create a virtual path to the binary folder using the windows subst command.

The following fails: "C:\Program Files\R\R-3.4.0\bin\Rscript.exe"

Doing following succeeds:

subst Z: "C:\Program Files\R\R-3.4.0"
Z:\bin\Rscript.exe

The reason the above-proposed solutions didn't work, evidently, has to do with the Rscript.exe executable's own internal path resolution from its working directory (which has a space in it) rather the windows command line being confused with the space. So using ~ or " to resolve the issue at the command line is moot. The executable must be called within a path lacking spaces.

Is there a Pattern Matching Utility like GREP in Windows?

On Windows I use Far Manager for file search. BSD licensed, works in console, saves time on typing cmdline parameters. Here is its search dialog invoked by Alt-F7. Alt-F7

What is the default access modifier in Java?

Here is a code sample which should pretty much sum this up for you... In addition to the below, showing how you can't access a default in another package there is one more thing.

Default is not accessible in a subclass if the class that subclasses it is in another package, but it is accessible if the subclass is in the same package.

package main;

public class ClassA {
    private int privateVar;
    public int publicVar;
    int defaultVar;
}

package main;

public class ClassB {
    public static void main(String[] args) {
        ClassA a = new ClassA();
        int v1 = a.publicVar;   // Works
        int v2 = a.defaultVar;  // Works
        int v3 = a.privateVar;  // Doesn't work

    }
}

package other;

public class ClassC {
    public static void main(String[] args) {
        ClassA a = new ClassA();
        int v1 = a.publicVar;   // Works
        int v2 = a.defaultVar;  // Doesn't work
        int v3 = a.privateVar;  // Doesn't work
    }
}

jQuery click event not working after adding class

I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

Like this:

<script>
  $(function(){
    //your click code
    $("a.tabclick").on('click',function() {
      //do something
    });
  });
</script>

What do pty and tty mean?

If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system

Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).

Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .

For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

python 2 instead of python 3 as the (temporary) default python?

If you have some problems with virtualenv,

You can use it:

sudo ln -sf python2 /usr/bin/python

and

sudo ln -sf python3 /usr/bin/python

Angular Material: mat-select not selecting default

The solution for me was:

<mat-form-field>
  <mat-select #monedaSelect  formControlName="monedaDebito" [attr.disabled]="isLoading" [placeholder]="monedaLabel | async ">
  <mat-option *ngFor="let moneda of monedasList" [value]="moneda.id">{{moneda.detalle}}</mat-option>
</mat-select>

TS:

@ViewChild('monedaSelect') public monedaSelect: MatSelect;
this.genericService.getOpciones().subscribe(res => {

  this.monedasList = res;
  this.monedaSelect._onChange(res[0].id);


});

Using object: {id: number, detalle: string}

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;
}

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

Apache won't start in wamp

This solved the issue for me:

Right click on the WAMP system try icon -> Tools -> Reinstall all services

How do you use colspan and rowspan in HTML tables?

If you're confused how table layouts work, they basically start at x=0, y=0 and work their way across. Let's explain with graphics, because they're so much fun!

When you start a table, you make a grid. Your first row and cell will be in the top left corner. Think of it like an array pointer, moving to the right with each incremented value of x, and moving down with each incremented value of y.

For your first row, you're only defining two cells. One spans 2 rows down and one spans 4 columns across. So when you reach the end of your first row, it looks something like this:

Preview #0001

<table>
    <tr>
        <td rowspan="2"></td>
        <td colspan="4"></td>
    </tr>
</table>

Now that the row has ended, the "array pointer" jumps down to the next row. Since x position 0 is already taken up by a previous cell, x jumps to position 1 to start filling in cells. * See note about difference between rowspans.

This row has four cells in it which are all 1x1 blocks, filling in the same width of the row above it.

Preview #0002

<table>
    <tr>
        <td rowspan="2"></td>
        <td colspan="4"></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

The next row is all 1x1 cells. But, for example, what if you added an extra cell? Well, it would just pop off the edge to the right.

Preview #0003

<table>
    <tr>
        <td rowspan="2"></td>
        <td colspan="4"></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

* But what if we instead (rather than adding the extra cell) made all these cells have a rowspan of 2? The thing you need to consider here is that even though you're not going to be adding any more cells in the next row, the row still must exist (even though it's an empty row). If you did try to add new cells in the row immediately after, you'd notice that it would start adding them to the end of the bottom row.

Preview #0004

<table>
    <tr>
        <td rowspan="2"></td>
        <td colspan="4"></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td rowspan="2"></td>
        <td rowspan="2"></td>
        <td rowspan="2"></td>
        <td rowspan="2"></td>
        <td rowspan="2"></td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>

Enjoy the wonderful world of creating tables!

How to concatenate items in a list to a single string?

We can also use Python's reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

Quick way to list all files in Amazon S3 bucket?

Be carefull, amazon list only returns 1000 files. If you want to iterate over all files you have to paginate the results using markers :

In ruby using aws-s3

bucket_name = 'yourBucket'
marker = ""

AWS::S3::Base.establish_connection!(
  :access_key_id => 'your_access_key_id',
  :secret_access_key => 'your_secret_access_key'
)

loop do
  objects = Bucket.objects(bucket_name, :marker=>marker, :max_keys=>1000)
  break if objects.size == 0
  marker = objects.last.key

  objects.each do |obj|
      puts "#{obj.key}"
  end
end

end

Hope this helps, vincent

Converts scss to css

In terminal run this command in the folder where the systlesheets are:

sass --watch style.scss:style.css 

Source:

http://sass-lang.com/

When ever it notices a change in the .scss file it will update your .css

This only works when your .scss is on your local machine. Try copying the code to a file and running it locally.

Find unused code

I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!

Refresh a page using PHP

Besides all the PHP ways to refresh a page, the page will also be refreshed with the following HTML meta tag:

<meta http-equiv="refresh" content="5">

See Meta refresh - "automatically refresh the current web page or frame after a given time interval"

You can set the time within the content value.

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Indexes of all occurrences of character in a string

This can be done by iterating myString and shifting fromIndex parameter in indexOf():

  int currentIndex = 0;

  while (
    myString.indexOf(
      mySubstring,
      currentIndex) >= 0) {

    System.out.println(currentIndex);

    currentIndex++;
  }

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Generate a heatmap in MatPlotLib using a scatter data set

and the initial question was... how to convert scatter values to grid values, right? histogram2d does count the frequency per cell, however, if you have other data per cell than just the frequency, you'd need some additional work to do.

x = data_x # between -10 and 4, log-gamma of an svc
y = data_y # between -4 and 11, log-C of an svc
z = data_z #between 0 and 0.78, f1-values from a difficult dataset

So, I have a dataset with Z-results for X and Y coordinates. However, I was calculating few points outside the area of interest (large gaps), and heaps of points in a small area of interest.

Yes here it becomes more difficult but also more fun. Some libraries (sorry):

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
from scipy.interpolate import griddata

pyplot is my graphic engine today, cm is a range of color maps with some initeresting choice. numpy for the calculations, and griddata for attaching values to a fixed grid.

The last one is important especially because the frequency of xy points is not equally distributed in my data. First, let's start with some boundaries fitting to my data and an arbitrary grid size. The original data has datapoints also outside those x and y boundaries.

#determine grid boundaries
gridsize = 500
x_min = -8
x_max = 2.5
y_min = -2
y_max = 7

So we have defined a grid with 500 pixels between the min and max values of x and y.

In my data, there are lots more than the 500 values available in the area of high interest; whereas in the low-interest-area, there are not even 200 values in the total grid; between the graphic boundaries of x_min and x_max there are even less.

So for getting a nice picture, the task is to get an average for the high interest values and to fill the gaps elsewhere.

I define my grid now. For each xx-yy pair, i want to have a color.

xx = np.linspace(x_min, x_max, gridsize) # array of x values
yy = np.linspace(y_min, y_max, gridsize) # array of y values
grid = np.array(np.meshgrid(xx, yy.T))
grid = grid.reshape(2, grid.shape[1]*grid.shape[2]).T

Why the strange shape? scipy.griddata wants a shape of (n, D).

Griddata calculates one value per point in the grid, by a predefined method. I choose "nearest" - empty grid points will be filled with values from the nearest neighbor. This looks as if the areas with less information have bigger cells (even if it is not the case). One could choose to interpolate "linear", then areas with less information look less sharp. Matter of taste, really.

points = np.array([x, y]).T # because griddata wants it that way
z_grid2 = griddata(points, z, grid, method='nearest')
# you get a 1D vector as result. Reshape to picture format!
z_grid2 = z_grid2.reshape(xx.shape[0], yy.shape[0])

And hop, we hand over to matplotlib to display the plot

fig = plt.figure(1, figsize=(10, 10))
ax1 = fig.add_subplot(111)
ax1.imshow(z_grid2, extent=[x_min, x_max,y_min, y_max,  ],
            origin='lower', cmap=cm.magma)
ax1.set_title("SVC: empty spots filled by nearest neighbours")
ax1.set_xlabel('log gamma')
ax1.set_ylabel('log C')
plt.show()

Around the pointy part of the V-Shape, you see I did a lot of calculations during my search for the sweet spot, whereas the less interesting parts almost everywhere else have a lower resolution.

Heatmap of a SVC in high resolution

Is it possible to overwrite a function in PHP

Monkey patch in namespace php >= 5.3

A less evasive method than modifying the interpreter is the monkey patch.

Monkey patching is the art of replacing the actual implementation with a similar "patch" of your own.

Ninja skills

Before you can monkey patch like a PHP Ninja we first have to understand PHPs namespaces.

Since PHP 5.3 we got introduced to namespaces which you might at first glance denote to be equivalent to something like java packages perhaps, but it's not quite the same. Namespaces, in PHP, is a way to encapsulate scope by creating a hierarchy of focus, especially for functions and constants. As this topic, fallback to global functions, aims to explain.

If you don't provide a namespace when calling a function, PHP first looks in the current namespace then moves down the hierarchy until it finds the first function declared within that prefixed namespace and executes that. For our example if you are calling print_r(); from namespace My\Awesome\Namespace; What PHP does is to first look for a function called My\Awesome\Namespace\print_r(); then My\Awesome\print_r(); then My\print_r(); until it finds the PHP built in function in the global namespace \print_r();.

You will not be able to define a function print_r($object) {} in the global namespace because this will cause a name collision since a function with that name already exists.

Expect a fatal error to the likes of:

Fatal error: Cannot redeclare print_r()

But nothing stops you, however, from doing just that within the scope of a namespace.

Patching the monkey

Say you have a script using several print_r(); calls.

Example:

<?php
     print_r($some_object);
     // do some stuff
     print_r($another_object);
     // do some other stuff
     print_r($data_object);
     // do more stuff
     print_r($debug_object);

But you later change your mind and you want the output wrapped in <pre></pre> tags instead. Ever happened to you?

Before you go and change every call to print_r(); consider monkey patching instead.

Example:

<?php
    namespace MyNamespace {
        function print_r($object) 
        {
            echo "<pre>", \print_r($object, true), "</pre>"; 
        }

        print_r($some_object);
        // do some stuff
        print_r($another_object);
        // do some other stuff
        print_r($data_object);
        // do more stuff
        print_r($debug_object);
    }

Your script will now be using MyNamespace\print_r(); instead of the global \print_r();

Works great for mocking unit tests.

nJoy!

Regex: matching up to the first occurrence of a character

This will match up to the first occurrence only in each string and will ignore subsequent occurrences.

/^([^;]*);*/

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

Press enter in textbox to and execute button command

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

Here's an example from the article linked:

<Button IsDefault = "true" 
        Click     = "SaveClicked"
        Content   = "Save"  ... />
'''

String to list in Python

Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Verify ImageMagick installation

This is as short and sweet as it can get:

if (!extension_loaded('imagick'))
    echo 'imagick not installed';

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

Passing additional variables from command line to make

There's another option not cited here which is included in the GNU Make book by Stallman and McGrath (see http://www.chemie.fu-berlin.de/chemnet/use/info/make/make_7.html). It provides the example:

archive.a: ...
ifneq (,$(findstring t,$(MAKEFLAGS)))
        +touch archive.a
        +ranlib -t archive.a
else
        ranlib archive.a
endif

It involves verifying if a given parameter appears in MAKEFLAGS. For example .. suppose that you're studying about threads in c++11 and you've divided your study across multiple files (class01, ... , classNM) and you want to: compile then all and run individually or compile one at a time and run it if a flag is specified (-r, for instance). So, you could come up with the following Makefile:

CXX=clang++-3.5
CXXFLAGS = -Wall -Werror -std=c++11
LDLIBS = -lpthread

SOURCES = class01 class02 class03

%: %.cxx
    $(CXX) $(CXXFLAGS) -o [email protected] $^ $(LDLIBS)
ifneq (,$(findstring r,  $(MAKEFLAGS)))
    ./[email protected]
endif

all: $(SOURCES)

.PHONY: clean

clean:
    find . -name "*.out" -delete

Having that, you'd:

  • build and run a file w/ make -r class02;
  • build all w/ make or make all;
  • build and run all w/ make -r (suppose that all of them contain some certain kind of assert stuff and you just want to test them all)

Can you require two form fields to match with HTML5?

JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):

<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
  <input type="password" name="p1" value="" required />
  <input type="password" name="p2" value="" required />
  <output name="result"></output>
</form>

Android Paint: .measureText() vs .getTextBounds()

This is how I calculated the real dimensions for the first letter (you can change the method header to suit your needs, i.e. instead of char[] use String):

private void calculateTextSize(char[] text, PointF outSize) {
    // use measureText to calculate width
    float width = mPaint.measureText(text, 0, 1);

    // use height from getTextBounds()
    Rect textBounds = new Rect();
    mPaint.getTextBounds(text, 0, 1, textBounds);
    float height = textBounds.height();
    outSize.x = width;
    outSize.y = height;
}

Note that I'm using TextPaint instead of the original Paint class.

Convert python datetime to epoch with strftime

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

Why you should not use datetime.strftime('%s')

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I struggled with this issue for a long time and found out that when you run configure, just pass it the path to the correct php-config tool.

In my case, it was

./configure --with-php-config=/usr/local/zend/bin/php-config 

... If you're unsure, run a locate php-config on your machine and find the right one amongst the different versions installed.

Hope this helps somebody in the future.

PS. My default php-config was set to 20090926 which is PHP 5.3. The one I manually entered as a param for ./configure was for PHP 5.4 (2010...)

How do I get the first element from an IEnumerable<T> in .net?

FirstOrDefault ?

Elem e = enumerable.FirstOrDefault();
//do something with e

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

curl : (1) Protocol https not supported or disabled in libcurl

I solve it just by changing 'http://webname...' to "http://webname..."

Notice the quote. It should be double (") instead of single (').

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

how to implement regions/code collapse in javascript

None of these answers did not work for me with visual studio 2017.

The best plugin for VS 2017: JavaScript Regions

Example 1:

enter image description here

Example 2:

enter image description here

Tested and approved:

enter image description here

What is the difference between `throw new Error` and `throw someObject`?

throw something works with both object and strings.But it is less supported than the other method.throw new Error("") Will only work with strings and turns objects into useless [Object obj] in the catch block.

Is there an addHeaderView equivalent for RecyclerView?

Native API doesn't have such "addHeader" feature, but has the concept of "addItem".

I was able to include this specific feature of headers and extends for footers as well in my FlexibleAdapter project. I called it Scrollable Headers and Footers.

Here how they work:

Scrollable Headers and Footers are special items that scroll along with all others, but they don't belongs to main items (business items) and they are always handled by the adapter beside the main items. Those items are persistently located at the first and last positions.

enter image description here

There's a lot to say about them, better to read the detailed wiki page.

Moreover the FlexibleAdapter allows you to create headers/sections, also you can have them sticky and tens of others features like expandable items, endless scroll, UI extensions etc... all in one library!

What does @media screen and (max-width: 1024px) mean in CSS?

It targets some specified feature to execute some other codes...

For example:

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
    padding: 0;

  }

the above snippet say if the device that run this program have screen with 600px or less than 600px width, in this case our program must execute this part .

Python os.path.join() on a list

The problem is, os.path.join doesn't take a list as argument, it has to be separate arguments.

This is where *, the 'splat' operator comes into play...

I can do

>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I had the exact same error message doing a database export via Sequel Pro on a mac. I was the root user so i knew it wasn't permissions. Then i tried it with mysqldump and got a different error message: Got error: 1449: The user specified as a definer ('joey'@'127.0.0.1') does not exist when using LOCK TABLES

Ahh, I had restored this database from a backup on the dev site and I hadn't created that user on this machine. "grant all on . to 'joey'@'127.0.0.1' identified by 'joeypass'; " did the trick.

hth

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file

Renew Provisioning Profile

I've done what you suggest, and I don't see a "Renew" button either.

The following is how I got mine renewed.

I see my three profiles (companynameProfile, "Team Provisioning Profile", and productnameProfile). THe first and third are going to expire within a couple of weeks. The second (and only the second) is flagged as "managed by Xcode". The profile names appear in a table with columns labelled: "Provisioning Profile", App ID, Status, and Actions. The status for all three is "Active". First 1 and 3, the Actions column has a "Download" button, and an "Edit" link. For 2, gthe Actions column has only the "Download" button.

There is no "Renew" (or "Refresh") button / link anywhere (and I did a view-source and searched that too :)

So, I thought...click on "Edit" on #3 ... two choices pop-up: Modify and Duplicate. I chose "Modify"

There is still no renew/refresh ... but there is a "Submit" button ... which doesn't work (turns out its sort of grayed out, but that's not at all obvious...bad UI design).

I discovered that if I change something on the screen (in my case, I selected a previously unused device), "Submit" darkens (becomes available). Click on "Submit". You're quietly (another UI problem :) taken back to the prior page, and the "Download" and "Edit" buttons are gone, and the status column should say "Pending"!

After awhile, I refreshed the window (reloaded) (don't know if it would have auto-refreshed) ... and saw that the status column had changed to "Active".

Now...I downloaded the new profile (the one that the darn page doesn't tell you is new, and doesn't LIST THE EXPIRATION DATE so you could tell yourself ... third UI flaw already :)

I downloaded the profile, deleted the old profile from the list in the Organizer window of Xcode, then dragged the new one into the Organizer window of Xcode, and ... voila, Organizer shows a new expiration date (of about 3 months from today).

Hope that helps,

Stan Cupertino, CA, USA

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

Clear text from textarea with selenium

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

Concatenating multiple text files into a single file in Bash

The most upvoted answers will fail if the file list is too long.

A more portable solution would be using fd

fd -e txt -d 1 -X awk 1 > combined.txt

-d 1 limits the search to the current directory. If you omit this option then it will recursively find all .txt files from the current directory.
-X (otherwise known as --exec-batch) executes a command (awk 1 in this case) for all the search results at once.

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

How does true/false work in PHP?

Zero is false, nonzero is true.

In php you can test more explicitly using the === operator.

if (0==false) 
    echo "works"; // will echo works

if (0===false) 
    echo "works"; // will not echo anything

Java: get greatest common divisor

As far as I know, there isn't any built-in method for primitives. But something as simple as this should do the trick:

public int gcd(int a, int b) {
   if (b==0) return a;
   return gcd(b,a%b);
}

You can also one-line it if you're into that sort of thing:

public int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); }

It should be noted that there is absolutely no difference between the two as they compile to the same byte code.

How to delete shared preferences data from App in Android

To remove specific values: SharedPreferences.Editor.remove() followed by a commit()

To remove them all SharedPreferences.Editor.clear() followed by a commit()

If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.

How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

java.util.zip.ZipException: error in opening zip file

I faced the same problem. I had a zip archive which java.util.zip.ZipFile was not able to handle but WinRar unpacked it just fine. I found article on SDN about compressing and decompressing options in Java. I slightly modified one of example codes to produce method which was finally capable of handling the archive. Trick is in using ZipInputStream instead of ZipFile and in sequential reading of zip archive. This method is also capable of handling empty zip archive. I believe you can adjust the method to suit your needs as all zip classes have equivalent subclasses for .jar archives.

public void unzipFileIntoDirectory(File archive, File destinationDir) 
    throws Exception {
    final int BUFFER_SIZE = 1024;
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(archive);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destFile;
    while ((entry = zis.getNextEntry()) != null) {
        destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
        if (entry.isDirectory()) {
            destFile.mkdirs();
            continue;
        } else {
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            destFile.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(destFile);
            dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
            fos.close();
        }
    }
    zis.close();
    fis.close();
}

Determining the size of an Android view at runtime

Based on @mbaird's advice, I found a workable solution by subclassing the ImageView class and overriding onLayout(). I then created an observer interface which my activity implemented and passed a reference to itself to the class, which allowed it to tell the activity when it was actually finished sizing.

I'm not 100% convinced that this is the best solution (hence my not marking this answer as correct just yet), but it does work and according to the documentation is the first time when one can find the actual size of a view.

com.sun.jdi.InvocationException occurred invoking method

I have received com.sun.jdi.InvocationException occurred invoking method when I lazy loaded entity field which used secondary database config (Spring Boot with 2 database configs - lazy loading with second config does not work). Temporary solution was to add FetchType.EAGER.

How to access environment variable values?

As for the environment variables:

import os
print os.environ["HOME"]

I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

I had the exact same problem. Running mvn clean install instead of mvn clean compile resolved it. The difference only occurs when using multi-maven-project since the project dependencies are uploaded to the local repository by using install.