Programs & Examples On #Rapidminer

RapidMiner is an environment for machine learning, data mining, text mining, predictive analytics, and business analytics. RapidMiner is written in Java and it was open source. However, the current version is no longer published as source code.

Replace console output in Python

In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.

Explode string by one or more spaces or tabs

This works:

$string = 'A   B C          D';
$arr = preg_split('/[\s]+/', $string);

jQuery-UI datepicker default date

Jquery Datepicker defaultDate ONLY set the default date that you chose on the calendar that pops up when you click on your field. If you want the default date to APPEAR on your input before the user clicks on the field you should give a val() to your field. Something like this:

$("#searchDateFrom").datepicker({ defaultDate: "-1y -1m -6d" });
$("#searchDateFrom").val((date.getMonth()) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

How to import js-modules into TypeScript file?

In your second statement

import {FriendCard} from './../pages/FriendCard'

you are telling typescript to import the FriendCard class from the file './pages/FriendCard'

Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.

You have two options here. If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file. See https://github.com/Microsoft/TypeScript/issues/3019 for more details. about why you need to add the file.

Option 1

Refactor the Friend card js file to be typed.

export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;

constructor(card) {
    this.webElement = card;
    this.menuButton;
    this.serialNumber;
}



getAsWebElement = function () {
    return this.webElement;
};

clickMenuButton = function () {
    this.menuButton.click();
};

setSerialNumber = function (numberOfElements) {
    this.serialNumber = numberOfElements + 1;
    this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};

deleteFriend = function () {
    element(by.css('[ng-click="deleteFriend(person);"]')).click();
    element(by.css('[ng-click="confirm()"]')).click();
}
};

Option 2

You can import the anonymous function

 import * as FriendCard from module("./FriendCardJs");

There are a few options for a d.ts file definition. This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

How do I check if string contains substring?

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 

How to check if a string contains a specific text

If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.

if (strpos($a,'word') !== false) {
echo 'true';
}

or use the is_string method. Whichs returns true or false on the given variable.

<?php
$a = '';
is_string($a);
?>

JavaScript Array splice vs slice

S LICE = Gives part of array & NO splitting original array

SP LICE = Gives part of array & SPlitting original array

I personally found this easier to remember, as these 2 terms always confused me as beginner to web development.

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

Can't use Swift classes inside Objective-C

Details: Objective-C project with Swift 3 code in Xcode 8.1

Tasks:

  1. Use swift enum in objective-c class
  2. Use objective-c enum in swift class

FULL SAMPLE

1. Objective-C class which use Swift enum

ObjcClass.h

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ObjcEnum) {
    ObjcEnumValue1,
    ObjcEnumValue2,
    ObjcEnumValue3
};

@interface ObjcClass : NSObject

+ (void) PrintEnumValues;

@end

ObjcClass.m

#import "ObjcClass.h"
#import "SwiftCode.h"

@implementation ObjcClass

+ (void) PrintEnumValues {
    [self PrintEnumValue:SwiftEnumValue1];
    [self PrintEnumValue:SwiftEnumValue2];
    [self PrintEnumValue:SwiftEnumValue3];
}

+ (void) PrintEnumValue:(SwiftEnum) value {
    switch (value) {
        case SwiftEnumValue1:
            NSLog(@"-- SwiftEnum: SwiftEnumValue1");
            break;
            
        case SwiftEnumValue2:
        case SwiftEnumValue3:
            NSLog(@"-- SwiftEnum: long value = %ld", (long)value);
            break;
    }
}

@end

Detect Swift code in Objective-C code

In my sample I use SwiftCode.h to detect Swift code in Objective-C. This file generate automatically (I did not create a physical copy of this header file in a project), and you can only set name of this file:

enter image description here

enter image description here

If the compiler can not find your header file Swift code, try to compile the project.

2. Swift class which use Objective-C enum

import Foundation

@objc
enum SwiftEnum: Int {
    case Value1, Value2, Value3
}

@objc
class SwiftClass: NSObject {
    
    class func PrintEnumValues() {
        PrintEnumValue(.Value1)
        PrintEnumValue(.Value2)
        PrintEnumValue(.Value3)
    }
    
    class func PrintEnumValue(value: ObjcEnum) {
        switch value {
        case .Value1, .Value2:
            NSLog("-- ObjcEnum: int value = \(value.rawValue)")
            
        case .Value3:
            NSLog("-- ObjcEnum: Value3")
            break
        }
        
    }
}

Detect Objective-C code in Swift code

You need to create bridging header file. When you add Swift file in Objective-C project, or Objective-C file in swift project Xcode will suggest you to create bridging header.

enter image description here

You can change bridging header file name here:

enter image description here

Bridging-Header.h

#import "ObjcClass.h"

Usage

#import "SwiftCode.h"
...
[ObjcClass PrintEnumValues];
[SwiftClass PrintEnumValues];
[SwiftClass PrintEnumValue:ObjcEnumValue3];

Result

enter image description here


MORE SAMPLES

Full integration steps Objective-c and Swift described above. Now I will write some other code examples.

3. Call Swift class from Objective-c code

Swift class

import Foundation

@objc
class SwiftClass:NSObject {
    
    private var _stringValue: String
    var stringValue: String {
        get {
            print("SwiftClass get stringValue")
            return _stringValue
        }
        set {
            print("SwiftClass set stringValue = \(newValue)")
            _stringValue = newValue
        }
    }
    
    init (stringValue: String) {
        print("SwiftClass init(String)")
        _stringValue = stringValue
    }
    
    func printValue() {
        print("SwiftClass printValue()")
        print("stringValue = \(_stringValue)")
    }
    
}

Objective-C code (calling code)

SwiftClass *obj = [[SwiftClass alloc] initWithStringValue: @"Hello World!"];
[obj printValue];
NSString * str = obj.stringValue;
obj.stringValue = @"HeLLo wOrLd!!!";

Result

enter image description here

4. Call Objective-c class from Swift code

Objective-C class (ObjcClass.h)

#import <Foundation/Foundation.h>

@interface ObjcClass : NSObject
@property NSString* stringValue;
- (instancetype) initWithStringValue:(NSString*)stringValue;
- (void) printValue;
@end

ObjcClass.m

#import "ObjcClass.h"

@interface ObjcClass()

@property NSString* strValue;

@end

@implementation ObjcClass

- (instancetype) initWithStringValue:(NSString*)stringValue {
    NSLog(@"ObjcClass initWithStringValue");
    _strValue = stringValue;
    return self;
}

- (void) printValue {
    NSLog(@"ObjcClass printValue");
    NSLog(@"stringValue = %@", _strValue);
}

- (NSString*) stringValue {
    NSLog(@"ObjcClass get stringValue");
    return _strValue;
}

- (void) setStringValue:(NSString*)newValue {
    NSLog(@"ObjcClass set stringValue = %@", newValue);
    _strValue = newValue;
}

@end

Swift code (calling code)

if let obj = ObjcClass(stringValue:  "Hello World!") {
    obj.printValue()
    let str = obj.stringValue;
    obj.stringValue = "HeLLo wOrLd!!!";
}

Result

enter image description here

5. Use Swift extension in Objective-c code

Swift extension

extension UIView {
    static func swiftExtensionFunc() {
        NSLog("UIView swiftExtensionFunc")
    }
}

Objective-C code (calling code)

[UIView swiftExtensionFunc];

6. Use Objective-c extension in swift code

Objective-C extension (UIViewExtension.h)

#import <UIKit/UIKit.h>

@interface UIView (ObjcAdditions)
+ (void)objcExtensionFunc;
@end

UIViewExtension.m

@implementation UIView (ObjcAdditions)
+ (void)objcExtensionFunc {
    NSLog(@"UIView objcExtensionFunc");
}
@end

Swift code (calling code)

UIView.objcExtensionFunc()

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Emulate Samsung Galaxy Tab

What resolution and density should I set?

  • 1024x600

How can I indicate that this is large screen device?

  • you can't really (not that i know of)

What hardware does this tablet support?

What is max heap size?

  • not sure

Which Android version?

  • 2.2

Hope that helps - check the spec page for all unanswered questions.

cannot redeclare block scoped variable (typescript)

In my case the following tsconfig.json solved problem:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "ES2020",
    "moduleResolution": "node"
  }
}

There should be no type: module in package.json.

How do you test your Request.QueryString[] variables?

Use int.TryParse instead to get rid of the try-catch block:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

Search for executable files using find command

Tip of the hat to @gniourf_gniourf for clearing up a fundamental misconception.

This answer attempts to provide an overview of the existing answers and to discuss their subtleties and relative merits as well as to provide background information, especially with respect to portability.

Finding files that are executable can refer to two distinct use cases:

  • user-centric: find files that are executable by the current user.
  • file-centric: find files that have (one or more) executable permission bits set.

Note that in either scenario it may make sense to use find -L ... instead of just find ... in order to also find symlinks to executables.

Note that the simplest file-centric case - looking for executables with the executable permissions bit set for ALL three security principals (user, group, other) - will typically, but not necessarily yield the same results as the user-centric scenario - and it's important to understand the difference.

User-centric (-executable)

  • The accepted answer commendably recommends -executable, IF GNU find is available.

    • GNU find comes with most Linux distros
      • By contrast, BSD-based platforms, including macOS, come with BSD find, which is less powerful.
    • As the scenario demands, -executable matches only files the current user can execute (there are edge cases.[1]).
  • The BSD find alternative offered by the accepted answer (-perm +111) answers a different, file-centric question (as the answer itself states).

    • Using just -perm to answer the user-centric question is impossible, because what is needed is to relate the file's user and group identity to the current user's, whereas -perm can only test the file's permissions.
      Using only POSIX find features, the question cannot be answered without involving external utilities.
    • Thus, the best -perm can do (by itself) is an approximation of -executable. Perhaps a closer approximation than -perm +111 is -perm -111, so as to find files that have the executable bit set for ALL security principals (user, group, other) - this strikes me as the typical real-world scenario. As a bonus, it also happens to be POSIX-compliant (use find -L to include symlinks, see farther below for an explanation):

      find . -type f -perm -111  # or: find . -type f -perm -a=x
      
  • gniourf_gniourf's answer provides a true, portable equivalent of -executable, using -exec test -x {} \;, albeit at the expense of performance.

    • Combining -exec test -x {} \; with -perm +111 (i.e., files with at least one executable bit set) may help performance in that exec needn't be invoked for every file (the following uses the POSIX-compliant equivalent of BSD find -perm +111 / GNU find -perm /111; see farther below for an explanation):

      find . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) -exec test -x {} \; -print
      

File-centric (-perm)

  • To answer file-centric questions, it is sufficient to use the POSIX-compliant -perm primary (known as a test in GNU find terminology).
    • -perm allows you to test for any file permissions, not just executability.
    • Permissions are specified as either octal or symbolic modes. Octal modes are octal numbers (e.g., 111), whereas symbolic modes are strings (e.g., a=x).
    • Symbolic modes identify the security principals as u (user), g (group) and o (other), or a to refer to all three. Permissions are expressed as x for executable, for instance, and assigned to principals using operators =, + and -; for a full discussion, including of octal modes, see the POSIX spec for the chmod utility.
    • In the context of find:
      • Prefixing a mode with - (e.g., -ug=x) means: match files that have all the permissions specified (but matching files may have additional permissions).
      • Having NO prefix (e.g. 755) means: match files that have this full, exact set of permissions.
      • Caveat: Both GNU find and BSD find implement an additional, nonstandard prefix with are-ANY-of-the-specified-permission-bits-set logic, but do so with incompatible syntax:
        • BSD find: +
        • GNU find: / [2]
      • Therefore, avoid these extensions, if your code must be portable.
  • The examples below demonstrate portable answers to various file-centric questions.

File-centric command examples

Note:

  • The following examples are POSIX-compliant, meaning they should work in any POSIX-compatible implementation, including GNU find and BSD find; specifically, this requires:
    • NOT using nonstandard mode prefixes + or /.
    • Using the POSIX forms of the logical-operator primaries:
      • ! for NOT (GNU find and BSD find also allow -not); note that \! is used in the examples so as to protect ! from shell history expansions
      • -a for AND (GNU find and BSD find also allow -and)
      • -o for OR (GNU find and BSD find also allow -or)
  • The examples use symbolic modes, because they're easier to read and remember.
    • With mode prefix -, the = and + operators can be used interchangeably (e.g., -u=x is equivalent to -u+x - unless you apply -x later, but there's no point in doing that).
    • Use , to join partial modes; AND logic is implied; e.g., -u=x,g=x means that both the user and the group executable bit must be set.
    • Modes cannot themselves express negative matching in the sense of "match only if this bit is NOT set"; you must use a separate -perm expression with the NOT primary, !.
  • Note that find's primaries (such as -print, or -perm; also known as actions and tests in GNU find) are implicitly joined with -a (logical AND), and that -o and possibly parentheses (escaped as \( and \) for the shell) are needed to implement OR logic.
  • find -L ... instead of just find ... is used in order to also match symlinks to executables
    • -L instructs find to evaluate the targets of symlinks instead of the symlinks themselves; therefore, without -L, -type f would ignore symlinks altogether.
# Match files that have ALL executable bits set - for ALL 3 security
# principals (u (user), g (group), o (others)) and are therefore executable
# by *anyone*.
# This is the typical case, and applies to executables in _system_ locations
# (e.g., /bin) and user-installed executables in _shared_ locations
# (e.g., /usr/local/bin), for instance. 
find -L . -type f -perm -a=x  # -a=x is the same as -ugo=x

# The POSIX-compliant equivalent of `-perm +111` from the accepted answer:
# Match files that have ANY executable bit set.
# Note the need to group the permission tests using parentheses.
find -L . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \)

# A somewhat contrived example to demonstrate the use of a multi-principial
# mode (comma-separated clauses) and negation:
# Match files that have _both_ the user and group executable bit set, while
# also _not_ having the other executable bit set.
find -L . -type f -perm -u=x,g=x  \! -perm -o=x

[1] Description of -executable from man find as of GNU find 4.4.2:

Matches files which are executable and directories which are searchable (in a file name resolution sense). This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.

[2] GNU find versions older than 4.5.12 also allowed prefix +, but this was first deprecated and eventually removed, because combining + with symbolic modes yields likely yields unexpected results due to being interpreted as an exact permissions mask. If you (a) run on a version before 4.5.12 and (b) restrict yourself to octal modes only, you could get away with using + with both GNU find and BSD find, but it's not a good idea.

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

Thread Safe C# Singleton Pattern

Performing a lock: Quite cheap (still more expensive than a null test).

Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.

Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.

For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.

Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.

(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton() or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

MySQL - Selecting data from multiple tables all with same structure but different data

Any of the above answers are valid, or an alternative way is to expand the table name to include the database name as well - eg:

SELECT * from us_music, de_music where `us_music.genre` = 'punk' AND `de_music.genre` = 'punk'

How to remove all .svn directories from my application directories

If you don't like to see a lot of

find: `./.svn': No such file or directory

warnings, then use the -depth switch:

find . -depth -name .svn -exec rm -fr {} \;

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

How to establish ssh key pair when "Host key verification failed"

Its means your remote host key was changed (May be host password change),

Your terminal suggested to execute this command as root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231

You have to remove that host name from hosts list on your pc/server. Copy that suggested command and execute as a root user.

$ sudo su                                                            // Login as a root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231   // Terminal suggested command execute here
Host [www.website.net]:4231 found: line 16 type ECDSA
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

$ exit                                                               // Exist from root user

$ sudo ssh [email protected] -p 4231                              // Try again

I Hope this works.

openpyxl - adjust column width size

My variation of Bufke's answer. Avoids a bit of branching with the array and ignores empty cells / columns.

Now fixed for non-string cell values.

ws = your current worksheet
dims = {}
for row in ws.rows:
    for cell in row:
        if cell.value:
            dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value))))    
for col, value in dims.items():
    ws.column_dimensions[col].width = value

As of openpyxl version 3.0.3 you need to use

 dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.value))))

as the openpyxl library will raise a TypeError if you pass column_dimensions a number instead of a column letter, everything else can stay the same.

Java: how to import a jar file from command line

If you're running a jar file with java -jar, the -classpath argument is ignored. You need to set the classpath in the manifest file of your jar, like so:

Class-Path: jar1-name jar2-name directory-name/jar3-name

See the Java tutorials: Adding Classes to the JAR File's Classpath.

Edit: I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the ':' after "Class-Path" like you showed, it would not work.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this...

List list=new ArrayList(); 
Criteria cr=session.createCriteria(Table1.class);
cr.add(Restrictions.sqlRestriction("this_.id not in (select t2.t1_id from Table2 t2 )"));
.
.

. . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement.

Can you get a Windows (AD) username in PHP?

I've got php mysql running on IIS - I can use $_SERVER["AUTH_USER"] if I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)

I've used this to get my user and domain:

$user = $_SERVER['AUTH_USER'];

$user will return a value like: DOMAIN\username on our network, and then it's just a case of removing the DOMAIN\ from the string.

This has worked in IE, FF, Chrome, Safari (tested) so far.

How to search for a string in text files?

found = False

def check():
    datafile = file('example.txt')
    for line in datafile:
        if blabla in line:
            found = True
            break
    return found

if check():
    print "true"
else:
    print "false"

Can't start hostednetwork

If none of the above answers worked for you, You can try the following solution which worked for me.

Go to Services manager(services.msc) and enable the below services and try again.
  1. WLAN AutoConfig
  2. Wi-Fi Direct Services Connection Manager Service

Hope this solved your problem.

Strange Jackson exception being thrown when serializing Hibernate object

You could use @JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" }) annotation on your class "Director"

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Python subprocess/Popen with a modified environment

With Python 3.5 you could do it this way:

import os
import subprocess

my_env = {**os.environ, 'PATH': '/usr/sbin:/sbin:' + os.environ['PATH']}

subprocess.Popen(my_command, env=my_env)

Here we end up with a copy of os.environ and overridden PATH value.

It was made possible by PEP 448 (Additional Unpacking Generalizations).

Another example. If you have a default environment (i.e. os.environ), and a dict you want to override defaults with, you can express it like this:

my_env = {**os.environ, **dict_with_env_variables}

How do I use the conditional operator (? :) in Ruby?

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

However, in Ruby, if is also an expression so: if a then b else c end === a ? b : c, except for precedence issues. Both are expressions.

Examples:

puts (if 1 then 2 else 3 end) # => 2

puts 1 ? 2 : 3                # => 2

x = if 1 then 2 else 3 end
puts x                        # => 2

Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1 with some extra junk after it), but they are not required in the last case as said issue does not arise.

You can use the "long-if" form for readability on multiple lines:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end

How do I create a comma delimited string from an ArrayList?

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:

TEXT...
<br><hr><br>
TEXT...

Resulting in:

TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...

how to display progress while loading a url to webview in android?

  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        alertDialog.setTitle("Error");
        alertDialog.setMessage(description);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alertDialog.show();
    }
});

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

There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.

How do you use "git --bare init" repository?

You could also ask git to create directory for you:

git init --bare test_repo.git

Can constructors be async?

Constructor acts very similarly to a method returning the constructed type. And async method can't return just any type, it has to be either “fire and forget” void, or Task.

If the constructor of type T actually returned Task<T>, that would be very confusing, I think.

If the async constructor behaved the same way as an async void method, that kind of breaks what constructor is meant to be. After constructor returns, you should get a fully initialized object. Not an object that will be actually properly initialized at some undefined point in the future. That is, if you're lucky and the async initialization doesn't fail.

All this is just a guess. But it seems to me that having the possibility of an async constructor brings more trouble than it's worth.

If you actually want the “fire and forget” semantics of async void methods (which should be avoided, if possible), you can easily encapsulate all the code in an async void method and call that from your constructor, as you mentioned in the question.

Convert Go map to json

It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.

json: unsupported type: map[int]main.Foo

JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.

You have two options:

1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):

datas := make(map[string]Foo, N)

for i := 0; i < 10; i++ {
    datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)

2 Simply just use a slice (javascript array):

datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
    datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)

playground

Save current directory in variable using Bash?

Similar to solution of mark with some checking of variables. Also I prefer not to use $variable but rather the same string I saved it under

save your folder/directory using save dir sdir myproject and go back to that folder using goto dir gdir myproject

in addition checkout the workings of native pushd and popd they will save the current folder and this is handy for going back and forth. In this case you can also use popd after gdir myproject and go back again

# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle

function sdir {
    [[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
    [[ ! -z "$1" ]] && cd "${!1}";
}

another handy trick is to combine the two pushd/popd and sdir and gdir wher you replace the cd in the goto dir function in pushd. This enables you to also fly back to your previous folder when making the jump to the saved folder.

# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle

function sdir {
    [[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
    [[ ! -z "$1" ]] && pushd "${!1}";
}

shell script to remove a file if it already exist

Don't bother checking if the file exists, just try to remove it.

rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null

Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f (short for --force) option. Depending on the situation, this may be an important detail.

But more likely, if you are appending to the file it is because your script is using >> to redirect something into the file. Just replace >> with >. It's hard to say since you've provided no code.

Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.

FileNotFoundError: [Errno 2] No such file or directory

Lets say we have a script in "c:\script.py" that contain :

result = open("index.html","r")
print(result.read())

Lets say that the index.html file is also in the same directory "c:\index.html" when i execute the script from cmd (or shell)

C:\Users\Amine>python c:\script.py

You will get error:

FileNotFoundError: [Errno 2] No such file or directory: 'index.html'

And that because "index.html" is not in working directory which is "C:\Users\Amine>". so in order to make it work you have to change the working directory

C:\python script.py

'<html><head></head><body></body></html>'

This is why is it preferable to use absolute path.

Why can a function modify some arguments as perceived by the caller, but not others?

It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].

You should declare your function f() like this:

def f(n, x=None):
    if x is None:
        x = []
    ...

How to convert a string of numbers to an array of numbers?

You can use Array.map to convert each element into a number.

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});

Check the Docs


Or more elegantly as pointed out by User: thg435

var b = a.split(',').map(Number);

Where Number() would do the rest:check here


Note: For older browsers that don't support map, you can add an implementation yourself like:

Array.prototype.map = Array.prototype.map || function(_x) {
    for(var o=[], i=0; i<this.length; i++) { 
        o[i] = _x(this[i]); 
    }
    return o;
};

How do I get the find command to print out the file size with the file name?

You need to use -exec or -printf. Printf works like this:

find . -name *.ear -printf "%p %k KB\n"

-exec is more powerful and lets you execute arbitrary commands - so you could use a version of 'ls' or 'wc' to print out the filename along with other information. 'man find' will show you the available arguments to printf, which can do a lot more than just filesize.

[edit] -printf is not in the official POSIX standard, so check if it is supported on your version. However, most modern systems will use GNU find or a similarly extended version, so there is a good chance it will be implemented.

When to use DataContract and DataMember attributes?

Since a lot of programmers were overwhelmed with the [DataContract] and [DataMember] attributes, with .NET 3.5 SP1, Microsoft made the data contract serializer handle all classes - even without any of those attributes - much like the old XML serializer.

So as of .NET 3.5 SP1, you don't have to add data contract or data member attributes anymore - if you don't then the data contract serializer will serialize all public properties on your class, just like the XML serializer would.

HOWEVER: by not adding those attributes, you lose a lot of useful capabilities:

  • without [DataContract], you cannot define an XML namespace for your data to live in
  • without [DataMember], you cannot serialize non-public properties or fields
  • without [DataMember], you cannot define an order of serialization (Order=) and the DCS will serialize all properties alphabetically
  • without [DataMember], you cannot define a different name for your property (Name=)
  • without [DataMember], you cannot define things like IsRequired= or other useful attributes
  • without [DataMember], you cannot leave out certain public properties - all public properties will be serialized by the DCS

So for a "quick'n'dirty" solution, leaving away the [DataContract] and [DataMember] attributes will work - but it's still a good idea to have them on your data classes - just to be more explicit about what you're doing, and to give yourself access to all those additional features that you don't get without them...

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .

you can define it like this:

new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };

and here is a more realistic example:

new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}

and finally in:

MVC 1

<%= Html.TextBox("test", new { style="width:50px" }) %> 

MVC 2

<%= Html.TextBox("test", null, new { style="width:50px" }) %> 

MVC 3

@Html.TextBox("test", null, new { style="width:50px" })

Git - Won't add files?

I had this problem with the first program in the folder. I did "git add" then "git commit". "git status" gave the error described i.e. "nothing to commit, working directory clean"

I ended up deleting the .git file from the program folder. Then I did a new git init, git add and git commit and it worked.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

In short

Summary

In its simplest form, this technique aims to wrap code inside a function scope.

It helps decreases chances of:

  • clashing with other applications/libraries
  • polluting superior (global most likely) scope

It does not detect when the document is ready - it is not some kind of document.onload nor window.onload

It is commonly known as an Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.

Code Explained

var someFunction = function(){ console.log('wagwan!'); };

(function() {                   /* function scope starts here */
  console.log('start of IIFE');

  var myNumber = 4;             /* number variable declaration */
  var myFunction = function(){  /* function variable declaration */
    console.log('formidable!'); 
  };
  var myObject = {              /* object variable declaration */
    anotherNumber : 1001, 
    anotherFunc : function(){ console.log('formidable!'); }
  };
  console.log('end of IIFE');
})();                           /* function scope ends */

someFunction();            // reachable, hence works: see in the console
myFunction();              // unreachable, will throw an error, see in the console
myObject.anotherFunc();    // unreachable, will throw an error, see in the console

In the example above, any variable defined in the function (i.e. declared using var) will be "private" and accessible within the function scope ONLY (as Vivin Paliath puts it). In other words, these variables are not visible/reachable outside the function. See live demo.

Javascript has function scoping. "Parameters and variables defined in a function are not visible outside of the function, and that a variable defined anywhere within a function is visible everywhere within the function." (from "Javascript: The Good Parts").


More details

Alternative Code

In the end, the code posted before could also be done as follows:

var someFunction = function(){ console.log('wagwan!'); };

var myMainFunction = function() {
  console.log('start of IIFE');

  var myNumber = 4;
  var myFunction = function(){ console.log('formidable!'); };
  var myObject = { 
    anotherNumber : 1001, 
    anotherFunc : function(){ console.log('formidable!'); }
  };
  console.log('end of IIFE');
};

myMainFunction();          // I CALL "myMainFunction" FUNCTION HERE
someFunction();            // reachable, hence works: see in the console
myFunction();              // unreachable, will throw an error, see in the console
myObject.anotherFunc();    // unreachable, will throw an error, see in the console

See live demo.


The Roots

Iteration 1

One day, someone probably thought "there must be a way to avoid naming 'myMainFunction', since all we want is to execute it immediately."

If you go back to the basics, you find out that:

  • expression: something evaluating to a value. i.e. 3+11/x
  • statement: line(s) of code doing something BUT it does not evaluate to a value. i.e. if(){}

Similarly, function expressions evaluate to a value. And one consequence (I assume?) is that they can be immediately invoked:

 var italianSayinSomething = function(){ console.log('mamamia!'); }();

So our more complex example becomes:

var someFunction = function(){ console.log('wagwan!'); };

var myMainFunction = function() {
  console.log('start of IIFE');

  var myNumber = 4;
  var myFunction = function(){ console.log('formidable!'); };
  var myObject = { 
    anotherNumber : 1001, 
    anotherFunc : function(){ console.log('formidable!'); }
  };
  console.log('end of IIFE');
}();

someFunction();            // reachable, hence works: see in the console
myFunction();              // unreachable, will throw an error, see in the console
myObject.anotherFunc();    // unreachable, will throw an error, see in the console

See live demo.

Iteration 2

The next step is the thought "why have var myMainFunction = if we don't even use it!?".

The answer is simple: try removing this, such as below:

 function(){ console.log('mamamia!'); }();

See live demo.

It won't work because "function declarations are not invokable".

The trick is that by removing var myMainFunction = we transformed the function expression into a function declaration. See the links in "Resources" for more details on this.

The next question is "why can't I keep it as a function expression with something other than var myMainFunction =?

The answer is "you can", and there are actually many ways you could do this: adding a +, a !, a -, or maybe wrapping in a pair of parenthesis (as it's now done by convention), and more I believe. As example:

 (function(){ console.log('mamamia!'); })(); // live demo: jsbin.com/zokuwodoco/1/edit?js,console.

or

 +function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wuwipiyazi/1/edit?js,console

or

 -function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wejupaheva/1/edit?js,console

So once the relevant modification is added to what was once our "Alternative Code", we return to the exact same code as the one used in the "Code Explained" example

var someFunction = function(){ console.log('wagwan!'); };

(function() {
  console.log('start of IIFE');

  var myNumber = 4;
  var myFunction = function(){ console.log('formidable!'); };
  var myObject = { 
    anotherNumber : 1001, 
    anotherFunc : function(){ console.log('formidable!'); }
  };
  console.log('end of IIFE');
})();

someFunction();            // reachable, hence works: see in the console
myFunction();              // unreachable, will throw an error, see in the console
myObject.anotherFunc();    // unreachable, will throw an error, see in the console

Read more about Expressions vs Statements:


Demystifying Scopes

One thing one might wonder is "what happens when you do NOT define the variable 'properly' inside the function -- i.e. do a simple assignment instead?"

(function() {
  var myNumber = 4;             /* number variable declaration */
  var myFunction = function(){  /* function variable declaration */
    console.log('formidable!'); 
  };
  var myObject = {              /* object variable declaration */
    anotherNumber : 1001, 
    anotherFunc : function(){ console.log('formidable!'); }
  };
  myOtherFunction = function(){  /* oops, an assignment instead of a declaration */
    console.log('haha. got ya!');
  };
})();
myOtherFunction();         // reachable, hence works: see in the console
window.myOtherFunction();  // works in the browser, myOtherFunction is then in the global scope
myFunction();              // unreachable, will throw an error, see in the console

See live demo.

Basically, if a variable that was not declared in its current scope is assigned a value, then "a look up the scope chain occurs until it finds the variable or hits the global scope (at which point it will create it)".

When in a browser environment (vs a server environment like nodejs) the global scope is defined by the window object. Hence we can do window.myOtherFunction().

My "Good practices" tip on this topic is to always use var when defining anything: whether it's a number, object or function, & even when in the global scope. This makes the code much simpler.

Note:

  • javascript does not have block scope (Update: block scope local variables added in ES6.)
  • javascript has only function scope & global scope (window scope in a browser environment)

Read more about Javascript Scopes:


Resources


Next Steps

Once you get this IIFE concept, it leads to the module pattern, which is commonly done by leveraging this IIFE pattern. Have fun :)

how can I debug a jar at runtime?

http://www.eclipsezone.com/eclipse/forums/t53459.html

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044

The application, at launch, will wait until you connect from another source.

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

how to make jni.h be found?

Use the following code:

make -I/usr/lib/jvm/jdk*/include

where jdk* is the directory name of your jdk installation (e.g. jdk1.7.0).

And there wouldn't be a system-wide solution since the directory name would be different with different builds of JDK downloaded and installed. If you desire an automated solution, please include all commands in a single script and run the said script in Terminal.

How to update the constant height constraint of a UIView programmatically?

Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.

//Connect them from Interface 
@IBOutlet viewHeight: NSLayoutConstraint! 
@IBOutlet view: UIView!

private func updateViewHeight(height:Int){
   guard let aView = view, aViewHeight = viewHeight else{
      return
   }
   aViewHeight.constant = height
   aView.layoutIfNeeded()
}

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


jQuery: value.attr is not a function

You are dealing with the raw DOM element .. need to wrap it in a jquery object

console.info("cat_id: ",$(value).attr('cat_id'));

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

Here is a simple approach which will print the 2 different elapsed time for each query.

DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;

SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);

SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);

OR try SET STATISTICS TIME (Transact-SQL)

SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;

It simply displays the number of milliseconds required to parse, compile, and execute each statement as below:

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 2 ms.

Cannot attach the file *.mdf as database

In my case removing Initail Cataloge=.... from connection string resolved the issue

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

How do I run a terminal inside of Vim?

I know that I'm not directly answering the question, but I think it's a good approach. Nobody has mentioned tmux (or at least not as a standalone answer). Tmux is a terminal multiplexor like screen. Most stuff can be made in both multiplexors, but afaik tmux it's more easily to configure. Also tmux right now is being more actively developed than screen and there's quite a big ecosystem around it, like tools that help the configuration, ecc.

Also for vim, there's another plugin: ViMUX, that helps a lot in the interaction between both tools. You can call commands with:

:call VimuxRunCommand("ls")

That command creates a small horizontal split below the current pane vim is in.

It can also let you run from a prompt in case you don't want to run the whole command:

<Leader>vp :VimuxPromptCommand<CR>

As it weren't enought, there are at least 6 'platform specific plugins':

Here is a nice "use case": Tests on demand using Vimux and Turbux with Spork and Guard

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Rotate axis text in python matplotlib

The simplest solution is to use:

plt.xticks(rotation=XX)

but also

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)

e.g for dates I used rotation=45 and bottom=0.20 but you can do some test for your data

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

How to style SVG with external CSS?

This method will work if the svg is viewed within a web browser but as soon as this code is uploaded to the sever and the class for the svg icon is coded as if it was a background image the color is lost and back to the default color. Seems like the color can not be changed from the external style sheet even though both the svg class for the color and the top layer class for the display and position of the svg are both mapped to the same directory.

PHP Constants Containing Arrays?

Doing some sort of ser/deser or encode/decode trick seems ugly and requires you to remember what exactly you did when you are trying to use the constant. I think the class private static variable with accessor is a decent solution, but I'll do you one better. Just have a public static getter method that returns the definition of the constant array. This requires a minimum of extra code and the array definition cannot be accidentally modified.

class UserRoles {
    public static function getDefaultRoles() {
        return array('guy', 'development team');
    }
}

initMyRoles( UserRoles::getDefaultRoles() );

If you want to really make it look like a defined constant you could give it an all caps name, but then it would be confusing to remember to add the '()' parentheses after the name.

class UserRoles {
    public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}

//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );

I suppose you could make the method global to be closer to the define() functionality you were asking for, but you really should scope the constant name anyhow and avoid globals.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

How to sum all column values in multi-dimensional array?

We need to check first if array key does exist.

CODE:

$sum = array();
foreach ($array as $key => $sub_array) {
    foreach ($sub_array as $sub_key => $value) {

        //If array key doesn't exists then create and initize first before we add a value.
        //Without this we will have an Undefined index error.
        if( ! array_key_exists($sub_key, $sum)) $sum[$sub_key] = 0;

        //Add Value
        $sum[$sub_key]+=$value;
    }
}
print_r($sum);

OUTPUT With Array Key Validation:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

OUTPUT Without Array Key Validation:

Notice: Undefined index: gozhi in F:\web\index.php on line 37

Notice: Undefined index: uzorong in F:\web\index.php on line 37

Notice: Undefined index: ngangla in F:\web\index.php on line 37

Notice: Undefined index: langthel in F:\web\index.php on line 37

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

This is a bad practice although it prints the output. Always check first if key does exist.

How to switch a user per task or set of tasks?

A solution is to use the include statement with remote_user var (describe there : http://docs.ansible.com/playbooks_roles.html) but it has to be done at playbook instead of task level.

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

How to write to a file, using the logging Python module?

This example should work fine. I have added streamhandler for console. Console log and file handler data should be similar.

    # MUTHUKUMAR_TIME_DATE.py #>>>>>>>> file name(module)

    import sys
    import logging
    import logging.config
    # ================== Logger ================================
    def Logger(file_name):
        formatter = logging.Formatter(fmt='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S') # %I:%M:%S %p AM|PM format
        logging.basicConfig(filename = '%s.log' %(file_name),format= '%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S', filemode = 'w', level = logging.INFO)
        log_obj = logging.getLogger()
        log_obj.setLevel(logging.DEBUG)
        # log_obj = logging.getLogger().addHandler(logging.StreamHandler())

        # console printer
        screen_handler = logging.StreamHandler(stream=sys.stdout) #stream=sys.stdout is similar to normal print
        screen_handler.setFormatter(formatter)
        logging.getLogger().addHandler(screen_handler)

        log_obj.info("Logger object created successfully..")
        return log_obj
    # =======================================================


MUTHUKUMAR_LOGGING_CHECK.py #>>>>>>>>>>> file name
# calling **Logger** function
file_name = 'muthu'
log_obj =Logger(file_name)
log_obj.info("yes   hfghghg ghgfh".format())
log_obj.critical("CRIC".format())
log_obj.error("ERR".format())
log_obj.warning("WARN".format())
log_obj.debug("debug".format())
log_obj.info("qwerty".format())
log_obj.info("asdfghjkl".format())
log_obj.info("zxcvbnm".format())
# closing file
log_obj.handlers.clear()

OUTPUT:
2019/07/13 23:54:40 MUTHUKUMAR_TIME_DATE,line: 17     INFO | Logger object created successfully..
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 8     INFO | yes   hfghghg ghgfh
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 9 CRITICAL | CRIC
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 10    ERROR | ERR
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 11  WARNING | WARN
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 12    DEBUG | debug
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 13     INFO | qwerty
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 14     INFO | asdfghjkl
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 15     INFO | zxcvbnm

Thanks, 

Output an Image in PHP

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

SQL Server convert select a column and convert it to a string

This a stab at creating a reusable column to comma separated string. In this case, I only one strings that have values and I do not want empty strings or nulls.

First I create a user defined type that is a one column table.

-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO

-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE 
(
    data NVARCHAR(max)
)
GO

The real purpose of the type is to simplify creating a scalar function to put the column into comma separated values.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  Rob Peterson        
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString 
(
    -- Add the parameters for the function here
    @column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @result VARCHAR(MAX)
DECLARE @current VARCHAR(MAX)
DECLARE @counter INT
DECLARE @c CURSOR

SET @result = ''
SET @counter = 0
-- Add the T-SQL statements to compute the return value here
SET @c = CURSOR FAST_FORWARD
    FOR SELECT COALESCE(data,'') FROM @column
    OPEN @c
    FETCH NEXT FROM @c
    INTO @current
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @result <> '' AND @current <> '' SET @result = @result + ',' + @current
        IF @result = '' AND @current <> '' SET @result = @current
    FETCH NEXT FROM @c
    INTO @current
    END
    CLOSE @c
    DEALLOCATE @c
-- Return the result of the function
RETURN @result

END
GO

Now, to use this. I select the column I want to convert to a comma separated string into the SingleVarcharColumn Type.

DECLARE @s as SingleVarcharColumn

INSERT INTO @s VALUES ('rob')
INSERT INTO @s VALUES ('paul')
INSERT INTO @s VALUES ('james')
INSERT INTO @s VALUES (null)


INSERT INTO @s
SELECT iClientID FROM [dbo].tClient

SELECT [dbo].fnGetCommaSeparatedString(@s)

To get results like this.

rob,paul,james,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159

I made my data column in my SingleVarcharColumn type an NVARCHAR(MAX) which may hurt performance, but I flexibility was what I was looking for and it runs fast enough for my purposes. It would probably be faster if it were a varchar and if it had a fixed and smaller width, but I have not tested it.

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

how to detect search engine bots with php?

If you really need to detect GOOGLE engine bots you should never rely on "user_agent" or "IP" address because "user_agent" can be changed and acording to what google said in: Verifying Googlebot

To verify Googlebot as the caller:

1.Run a reverse DNS lookup on the accessing IP address from your logs, using the host command.

2.Verify that the domain name is in either googlebot.com or google.com

3.Run a forward DNS lookup on the domain name retrieved in step 1 using the host command on the retrieved domain name. Verify that it is the same as the original accessing IP address from your logs.

Here is my tested code :

<?php
$remote_add=$_SERVER['REMOTE_ADDR'];
$hostname = gethostbyaddr($remote_add);
$googlebot = 'googlebot.com';
$google = 'google.com';
if (stripos(strrev($hostname), strrev($googlebot)) === 0 or stripos(strrev($hostname),strrev($google)) === 0 ) 
{
//add your code
}

?>

In this code we check "hostname" which should contain "googlebot.com" or "google.com" at the end of "hostname" which is really important to check exact domain not subdomain. I hope you enjoy ;)

Possible to make labels appear when hovering over a point in matplotlib?

If you use jupyter notebook, my solution is as simple as:

%pylab
import matplotlib.pyplot as plt
import mplcursors
plt.plot(...)
mplcursors.cursor(hover=True)
plt.show()

YOu can get something like enter image description here

How can I get a Bootstrap column to span multiple rows?

I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50 class on the row containing boxes 2, 3, 4, and 5.

Note: I am using Bootstrap-4, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)

getActionBar() returns null

This may also help some people.

In my case, it was because I had not defined a context in the menu.xml

Try this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.ActionBarActivity">

Instead of this:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

How to convert base64 string to image?

Return converted image without saving:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

How to use an output parameter in Java?

Thank you. I use passing in an object as a parameter. My Android code is below

    String oPerson= null;
    if (CheckAddress("5556", oPerson))
    {
        Toast.makeText(this, 
                "It's Match! " + oPerson,                   
                Toast.LENGTH_LONG).show();
    }

    private boolean CheckAddress(String iAddress, String oPerson)
{
    Cursor cAddress = mDbHelper.getAllContacts();
    String address = "";        
    if (cAddress.getCount() > 0) {
        cAddress.moveToFirst();
        while (cAddress.isAfterLast() == false) {
            address = cAddress.getString(2).toString();
            oPerson = cAddress.getString(1).toString(); 
            if(iAddress.indexOf(address) != -1)
            {
                Toast.makeText(this, 
                        "Person : " + oPerson,                  
                        Toast.LENGTH_LONG).show();
                System.out.println(oPerson);
                cAddress.close();
                return true;                    
            }
            else cAddress.moveToNext();
        }
    }
    cAddress.close();
    return false;
}

The result is

Person : John

It's Match! null

Actually, "It's Match! John"

Please check my mistake.

How To have Dynamic SQL in MySQL Stored Procedure

You can pass thru outside the dynamic statement using User-Defined Variables

Server version: 5.6.25-log MySQL Community Server (GPL)

mysql> PREPARE stmt FROM 'select "AAAA" into @a';
Query OK, 0 rows affected (0.01 sec)
Statement prepared

mysql> EXECUTE stmt;
Query OK, 1 row affected (0.01 sec)

DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.01 sec)

mysql> select @a;
+------+
| @a   |
+------+
|AAAA  |
+------+
1 row in set (0.01 sec)

How to find sum of several integers input by user using do/while, While statement or For statement

A simple program shows how to use for loop to find sum of serveral integers.

#include <iostream>    
using namespace std;

int main ()
{
    int sum = 0;

    int endnum = 2;

    for(int i = 0; i<=endnum; i++){
        sum += i;
    }
    cout<<sum;
}

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

How to delete zero components in a vector in Matlab?

I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:

b = snip(a,'0')

you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices

It also works with all other 'x', nan or whatever elements.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

This works for me everytime:

Thread.getAllStackTraces().keySet().each() {
if (it.name.contains('YOUR JOBNAME')) {  
  println "Stopping $it.name"
  it.stop()
}

Thanks to funql.org

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

Compiling a java program into an executable

There is a small handful of programs that do that... TowerJ is one that comes to mind (I'll let you Google for it) but it costs significant money.

The most useful reference for this topic I found is at: http://mindprod.com/jgloss/nativecompiler.html

it mentions a few other products, and alternatives to achieve the same purpose.

Multiple controllers with AngularJS in single page app

I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.

app = angular.module('myApp', []);                                                                             

app.config(function($routeProvider, $locationProvider) {                        
  $routeProvider                                                                
       .when('/home/', {                                            
         templateUrl: "templates/home.html",                                               
         controller:'homeController',                                
        })                                                                      
        .when('/about/', {                                       
            templateUrl: "templates/about.html",     
            controller: 'aboutController',  
        }) 
        .otherwise({                      
            template: 'does not exists'   
        });      
});

app.controller('homeController', [              
    '$scope',                              
    function homeController($scope,) {        
        $scope.message = 'HOME PAGE';                  
    }                                                
]);                                                  

app.controller('aboutController', [                  
    '$scope',                               
    function aboutController($scope) {        
        $scope.about = 'WE LOVE CODE';                       
    }                                                
]); 

base.html

<html>
<body>

    <div id="sideMenu">
        <!-- MENU CONTENT -->
    </div>

    <div id="content" ng-view="">
        <!-- Angular view would show here -->
    </div>

<body>
</html>

How to make an Asynchronous Method return a value?

Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.

    public void UseBackgroundWorker()
    {
        var worker = new BackgroundWorker();
        worker.DoWork += DoWork;
        worker.RunWorkerCompleted += WorkDone;
        worker.RunWorkerAsync("input");
    }

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = e.Argument.Equals("input");
        Thread.Sleep(1000);
    }

    public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
    {
        var result = (bool) e.Result;
    }

Array.size() vs Array.length

.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.

If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.

Angular 4 checkbox change value

I am guessing that this is what something you are trying to achieve.

<input type="checkbox" value="a" (click)="click($event)">A
<input type="checkbox" value="b" (click)="click($event)">B

click(ev){
   console.log(ev.target.defaultValue);
}

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Add BindingResult parameter in your method. For reference please my code below.

save(@ModelAttribute Employee employee,BindingResult bindingResult)

Finding local maxima/minima with Numpy in a 1D numpy array

For curves with not too much noise, I recommend the following small code snippet:

from numpy import *

# example data with some peaks:
x = linspace(0,4,1e3)
data = .2*sin(10*x)+ exp(-abs(2-x)**2)

# that's the line, you need:
a = diff(sign(diff(data))).nonzero()[0] + 1 # local min+max
b = (diff(sign(diff(data))) > 0).nonzero()[0] + 1 # local min
c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max


# graphical output...
from pylab import *
plot(x,data)
plot(x[b], data[b], "o", label="min")
plot(x[c], data[c], "o", label="max")
legend()
show()

The +1 is important, because diff reduces the original index number.

HTML -- two tables side by side

<div style="float: left;margin-right:10px">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>
<div style="float: left">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

Force div element to stay in same place, when page is scrolled

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

How to write new line character to a file in Java

The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.

Why should a Java class implement comparable?

The fact that a class implements Comparable means that you can take two objects from that class and compare them. Some classes, like certain collections (sort function in a collection) that keep objects in order rely on them being comparable (in order to sort you need to know which object is the "biggest" and so forth).

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

1.To install the virtualization driver:

Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager. After the download completes, execute /extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe. Follow the on-screen instructions to complete installation.

2.If it show any problem restart your computer and inter in BIOS an enable Virtualization Technology ...

3.To see your possessor is capable to virtualization go to the bellow link http://ark.intel.com/Products/VirtualizationTechnology

Checking if a variable is an integer in PHP

I had a similar problem just now!

You can use the filter_input() function with FILTER_VALIDATE_INT and FILTER_NULL_ON_FAILURE to filter only integer values out of the $_GET variable. Works pretty accurately! :)

Check out my question here: How to check whether a variable in $_GET Array is an integer?

LINQ order by null column where order is ascending and nulls should be last

This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue:

.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)

This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.

Using ffmpeg to encode a high quality video

Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH

Finding elements not in a list

If you run a loop taking items from z, how do you expect them not to be in z? IMHO it would make more sense comparing items from a different list to z.

CALL command vs. START with /WAIT option

This is what I found while running batch files in parallel (multiple instances of the same bat file at the same time with different input parameters) :

Lets say that you have an exe file that performs a long task called LongRunningTask.exe

If you call the exe directly from the bat file, only the first call to the LongRunningTask will succed, while the rest will get an OS error "File is already in use by the process"

If you use this command:

start /B /WAIT "" "LongRunningTask.exe" "parameters"

You will be able to run multiple instances of the bat and exe, while still waiting for the task to finish before the bat continues executing the remaining commands. The /B option is to avoid creating another window, the empty quotes are needed in order to the command to work, see the reference below.

Note that if you don´t use the /WAIT in the start, the LongRunningTask will be executed at the same time than the remaining commands in the batch file, so it might create problems if one of these commands requires the output of the LongRunningTask

Resuming :

This can´t run in parallel :

  • call LongRunningTask.exe

This will run in parallel and will be ok as far as there are no data dependencies between the output of the command and the rest of the bat file :

  • start /B "" "LongRunningTask.exe" "parameters"

This will run in parallel and wait for the task to finish, so you can use the output :

  • start /B /WAIT "" "LongRunningTask.exe" "parameters"

Reference for the start command : How can I run a program from a batch file without leaving the console open after the program start?

How can I convert a PFX certificate file for use with Apache on a linux server?

With OpenSSL you can convert pfx to Apache compatible format with next commands:

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key   

First command extracts public key to domain.cer.
Second command extracts private key to domain.key.

Update your Apache configuration file with:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 ...
</VirtualHost>

Make a borderless form movable?

Adding a MouseLeftButtonDown event handler to the MainWindow worked for me.

In the event function that gets automatically generated, add the below code:

base.OnMouseLeftButtonDown(e);
this.DragMove();

count number of characters in nvarchar column

I had a similar problem recently, and here's what I did:

    SELECT
         columnname as 'Original_Value',
         LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
         N'['+columnname+']' as 'UnicodeStr_Value',
         LEN(N'['+columnname+']')-2 as 'True_Char_Count'
    FROM mytable 

The first two columns look at the original value and count the characters (minus leading/trailing spaces).

I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.

By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.

HTML CSS Button Positioning

try changing that line-height change to a margin-top or padding-top change instead

#btnhome:active{
margin-top : 25px;
}

Edit: You could also try adding a span inside the button

<div id="header">           
    <button id="btnhome"><span>Home</span></button>          
    <button id="btnabout">About</button>
    <button id="btncontact">Contact</button>
    <button id="btnsup">Help Us</button>           
</div>

Then style that

#btnhome span:active { padding-top:25px;}

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

How can I create an object based on an interface file definition in TypeScript?

Many of the solutions so far posted use type assertions and therefor do not throw compilation errors if required interface properties are omitted in the implementation.

For those interested in some other robust, compact solutions:

Option 1: Instantiate an anonymous class which implements the interface:

new class implements MyInterface {
  nameFirst = 'John';
  nameFamily = 'Smith';
}();

Option 2: Create a utility function:

export function impl<I>(i: I) { return i; }

impl<MyInterface>({
  nameFirst: 'John';
  nameFamily: 'Smith';
})

Why is the minidlna database not being refreshed?

I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.

ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).

I'm still trying to find a way around this. If anyone has any input, it's most welcome.

jQuery - select all text from a textarea

I ended up using this:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

Dynamically load a JavaScript file

If you want a SYNC script loading, you need to add script text directly to HTML HEAD tag. Adding it as will trigger an ASYNC load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):

/*sample requires an additional method for array prototype:*/

if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) { if (this[i] === obj) return true; }
    return false;
};
};

/*define object that will wrap our logic*/
var ScriptLoader = {
LoadedFiles: [],

LoadFile: function (url) {
    var self = this;
    if (this.LoadedFiles.contains(url)) return;

    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                self.LoadedFiles.push(url);
                self.AddScript(xhr.responseText);
            } else {
                if (console) console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, false);/*last parameter defines if call is async or not*/
    xhr.send(null);
},

AddScript: function (code) {
    var oNew = document.createElement("script");
    oNew.type = "text/javascript";
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
}
};

/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/

ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id "tb1"*/
$(function () { alert($('#tb1').val()); });

How do I update Anaconda?

This can update the Python instance only:

conda update python

Add custom buttons on Slick Carousel

Why you cant use default CSS classes and add some your style?

.slick-next {
  /*my style*/
  background: url(my-image.png);
}

and

.slick-prev {
  /*my style*/
  background: url(my-image.png);
}

Are you used simple background css property?

in example: http://jsfiddle.net/BNvke/1/

You can use Font Awesome too. Don't forget about CSS pseudo elements.

And don't forget jQuery, you can replace elements, add classes, etc.

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

Jquery to get the id of selected value from dropdown

If you are trying to get the id, then please update your code like

  html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';

To retrieve id,

$('option:selected').attr("id")

To retrieve Value

$('option:selected').val()

in Javascript

var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;

jQuery Scroll To bottom of the page

$("div").scrollTop(1000);

Works for me. Scrolls to the bottom.

TypeError: 'list' object is not callable in python

Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.

HTTP GET with request body

You will likely encounter problems if you ever try to take advantage of caching. Proxies are not going to look in the GET body to see if the parameters have an impact on the response.

What does "exited with code 9009" mean during this build?

You need to make sure you have installed grunt globally

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

How to fix docker: Got permission denied issue

I solve this error with the command :

$ sudo chmod 666 /var/run/docker.sock

UNION with WHERE clause

In my experience, Oracle is very good at pushing simple predicates around. The following test was made on Oracle 11.2. I'm fairly certain it produces the same execution plan on all releases of 10g as well.

(Please people, feel free to leave a comment if you run an earlier version and tried the following)

create table table1(a number, b number);
create table table2(a number, b number);

explain plan for
select *
  from (select a,b from table1
        union 
        select a,b from table2
       )
 where a > 1;

select * 
  from table(dbms_xplan.display(format=>'basic +predicate'));

PLAN_TABLE_OUTPUT
---------------------------------------
| Id  | Operation            | Name   |
---------------------------------------
|   0 | SELECT STATEMENT     |        |
|   1 |  VIEW                |        |
|   2 |   SORT UNIQUE        |        |
|   3 |    UNION-ALL         |        |
|*  4 |     TABLE ACCESS FULL| TABLE1 |
|*  5 |     TABLE ACCESS FULL| TABLE2 |
---------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------    
   4 - filter("A">1)
   5 - filter("A">1)

As you can see at steps (4,5), the predicate is pushed down and applied before the sort (union).

I couldn't get the optimizer to push down an entire sub query such as

 where a = (select max(a) from empty_table)

or a join. With proper PK/FK constraints in place it might be possible, but clearly there are limitations :)

Can I embed a .png image into an html page?

I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);

my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;

print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html

print encode_base64($myimage);

print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>

end_html

Head and tail in one line

Under Python 3.x, you can do this nicely:

>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

It's also really readable.

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

How to delete last item in list?

If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

How to combine two strings together in PHP?

You can do this using PHP:

$txt1 = "the color is";
$txt2 = " red!";
echo $txt1.$txt2;

This will combine two strings and the putput will be: "the color is red!".

Check if a string is palindrome

Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.

It's sufficient to compare the first half of the string with the latter half, in reverse:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string s;
    std::cin >> s;
    if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "is a palindrome.\n";
    else
        std::cout << "is NOT a palindrome.\n";
}

demo: http://ideone.com/mq8qK

How to determine one year from now in Javascript

2020

It's perfect date/time library called Moment.js with this library you can simply write:

moment().subtract(1,'year')

and call any format you wish:

moment().subtract(1,'year').toDate()
moment().subtract(1,'year').toISOString()

See full documentation here: https://momentjs.com/

ImportError: No Module Named bs4 (BeautifulSoup)

If you are using Anaconda for package management, following should do:

conda install -c anaconda beautifulsoup4

How to empty a redis database?

You have two options:

  • FLUSHDB - clears currently active database
  • FLUSHALL - clears all the existing databases

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Convert base-2 binary number string to int

If you wanna know what is happening behind the scene, then here you go.

class Binary():
def __init__(self, binNumber):
    self._binNumber = binNumber
    self._binNumber = self._binNumber[::-1]
    self._binNumber = list(self._binNumber)
    self._x = [1]
    self._count = 1
    self._change = 2
    self._amount = 0
    print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
    self._number = number
    for i in range (1, len (self._number)):
        self._total = self._count * self._change
        self._count = self._total
        self._x.append(self._count)
    self._deep = zip(self._number, self._x)
    for self._k, self._v in self._deep:
        if self._k == '1':
            self._amount += self._v
    return self._amount
mo = Binary('101111110')

Write a file in UTF-8 using FileWriter (Java)?

Since Java 7 there is an easy way to handle character encoding of BufferedWriter and BufferedReaders. You can create a BufferedWriter directly by using the Files class instead of creating various instances of Writer. You can simply create a BufferedWriter, which considers character encoding, by calling:

Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);

You can find more about it in JavaDoc:

Round up value to nearest whole number in SQL UPDATE

Ceiling is the command you want to use.

Unlike Round, Ceiling only takes one parameter (the value you wish to round up), therefore if you want to round to a decimal place, you will need to multiply the number by that many decimal places first and divide afterwards.

Example.

I want to round up 1.2345 to 2 decimal places.

CEILING(1.2345*100)/100 AS Cost

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

Have you unistalled your Internet Explorer? I did, and I had the same issues, if so, you have to:

  1. Reactivate IE (Control Panel -- Programs and Features -- Turn Windows features on or off).
  2. restarting the computer
  3. (important!) running Windows Update to get all available updates for Microsoft Explorer
  4. restarting the computer (again)

Finally it works!

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

Android: keep Service running when app is killed

You can use android:stopWithTask="false"in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.

 <service android:name=".service.StickyService"
                  android:stopWithTask="false"/>

Write a file in external storage in Android

The code below creates a Documents directory and then a sub-directory for the application and saved the files to it.

public class loadDataTooDisk extends AsyncTask<String, Integer, String> {
    String sdCardFileTxt;
    @Override
    protected String doInBackground(String... params)
    {

        //check to see if external storage is avalibel
        checkState();
        if(canW == canR == true)
        {
            //get the path to sdcard 
            File pathToExternalStorage = Environment.getExternalStorageDirectory();
            //to this path add a new directory path and create new App dir (InstroList) in /documents Dir
            File appDirectory = new File(pathToExternalStorage.getAbsolutePath()  + "/documents/InstroList");
            // have the object build the directory structure, if needed.
            appDirectory.mkdirs();
            //test to see if it is a Text file
            if ( myNewFileName.endsWith(".txt") )
            {

                //Create a File for the output file data
                File saveFilePath = new File (appDirectory, myNewFileName);
                //Adds the textbox data to the file
                try{
                    String newline = "\r\n";
                    FileOutputStream fos = new FileOutputStream (saveFilePath);
                    OutputStreamWriter OutDataWriter  = new OutputStreamWriter(fos);

                    OutDataWriter.write(equipNo.getText() + newline);
                    // OutDataWriter.append(equipNo.getText() + newline);
                    OutDataWriter.append(equip_Type.getText() + newline);
                    OutDataWriter.append(equip_Make.getText()+ newline);
                    OutDataWriter.append(equipModel_No.getText()+ newline);
                    OutDataWriter.append(equip_Password.getText()+ newline);
                    OutDataWriter.append(equipWeb_Site.getText()+ newline);
                    //OutDataWriter.append(equipNotes.getText());
                    OutDataWriter.close();

                    fos.flush();
                    fos.close();

                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

This one builds the file name

   private String BuildNewFileName()
    { // creates a new filr name
        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();

        StringBuilder sb = new StringBuilder();

        sb.append(today.year + "");                // Year)
        sb.append("_");
        sb.append(today.monthDay + "");          // Day of the month (1-31)
        sb.append("_");
        sb.append(today.month + "");              // Month (0-11))
        sb.append("_");
        sb.append(today.format("%k:%M:%S"));      // Current time
        sb.append(".txt");                      //Completed file name

        myNewFileName = sb.toString();
        //Replace (:) with (_)
        myNewFileName = myNewFileName.replaceAll(":", "_");

        return myNewFileName;
    }

Hope this helps! It took me a long time to get it working.

ReCaptcha API v2 Styling

Late to the party, but maybe my solution will help somebody.

I haven't found any solution that works on a responsive website when the viewport changes or the layout is fluid.

So I've created a jQuery script for django-cms that is dynamically adapting to a changing viewport. I'm going to update this response as soon as I have the need for a modern variant of it that is more modular and has no jQuery dependency.


html

<div class="g-recaptcha" data-sitekey="{site_key}" data-size={size}> 
</div> 


css

.g-recaptcha { display: none; }

.g-recaptcha.g-recaptcha-initted { 
    display: block; 
    overflow: hidden; 
}

.g-recaptcha.g-recaptcha-initted > * {
    transform-origin: top left;
}


js

window.djangoReCaptcha = {
    list: [],
    setup: function() {
        $('.g-recaptcha').each(function() {
            var $container = $(this);
            var config = $container.data();

            djangoReCaptcha.init($container, config);
        });

        $(window).on('resize orientationchange', function() {
            $(djangoReCaptcha.list).each(function(idx, el) {
                djangoReCaptcha.resize.apply(null, el);
            });
        });
    },
    resize: function($container, captchaSize) {
        scaleFactor = ($container.width() / captchaSize.w);
        $container.find('> *').css({
            transform: 'scale(' + scaleFactor + ')',
            height: (captchaSize.h * scaleFactor) + 'px'
        });
    },
    init: function($container, config) {
        grecaptcha.render($container.get(0), config);

        var captchaSize, scaleFactor;
        var $iframe = $container.find('iframe').eq(0);

        $iframe.on('load', function() {
            $container.addClass('g-recaptcha-initted');
            captchaSize = captchaSize || { w: $iframe.width() - 2, h: $iframe.height() };
            djangoReCaptcha.resize($container, captchaSize);
            djangoReCaptcha.list.push([$container, captchaSize]);
        });
    },
    lateInit: function(config) {
        var $container = $('.g-recaptcha.g-recaptcha-late').eq(0).removeClass('.g-recaptcha-late');
        djangoReCaptcha.init($container, config);
    }
};

window.djangoReCaptchaSetup = window.djangoReCaptcha.setup;

Combine Multiple child rows into one row MYSQL

If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):

Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value

FROM Ordered_Items OI
    LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID
    LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID
    LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID
    LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID

GROUP BY OI.ID, OI.Item_Name

The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.

Putting an if-elif-else statement on one line?

It also depends on the nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.

But if all you need is a "dispatch" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.

Something like:

def save(): 
   ...
def edit():
   ...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}

option = get_input()
result = options[option]()

Instead of an if-else:

if option=="save":
    save()
...

How to get process ID of background process?

You need to save the PID of the background process at the time you start it:

foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID

You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.

Dynamically updating plot in matplotlib

In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw alone does not produce the plot (at least with the qt backend).

The following works for me:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

How to properly validate input values with React.JS?

Use onChange={this.handleChange.bind(this, "name") method and value={this.state.fields["name"]} on input text field and below that create span element to show error, see the below example.

export default class Form extends Component {

  constructor(){
    super()
    this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }
  }

  handleValidation(){
       let fields = this.state.fields;
       let errors = {};
       let formIsValid = true;

       if(!fields["name"]){
          formIsValid = false;
          errors["name"] = "Name field cannot be empty";
       }

       if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
          if(!fields["name"].match(/^[a-zA-Z]+$/)){
             formIsValid = false;
             errors["name"] = "Only letters";
          }
       }

       if(!fields["email"]){
          formIsValid = false;
          errors["email"] = "Email field cannot be empty";
       }

       if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
          let lastAtPos = fields["email"].lastIndexOf('@');
          let lastDotPos = fields["email"].lastIndexOf('.');

          if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
             formIsValid = false;
             errors["email"] = "Email is not valid";
           }
      }

      if(!fields["message"]){
         formIsValid = false;
         errors["message"] = " Message field cannot be empty";
      }

      this.setState({errors: errors});
      return formIsValid;
  }

  handleChange(field, e){
      let fields = this.state.fields;
      fields[field] = e.target.value;
      this.setState({fields});
  }

  handleSubmit(e){
      e.preventDefault();
      if(this.handleValidation()){
          console.log('validation successful')
        }else{
          console.log('validation failed')
        }
  }

  render(){
    return (
      <form onSubmit={this.handleSubmit.bind(this)} method="POST">
          <div className="row">
            <div className="col-25">
                <label htmlFor="name">Name</label>
            </div>
            <div className="col-75">
                <input type="text" placeholder="Enter Name"  refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                <span style={{color: "red"}}>{this.state.errors["name"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
              <label htmlFor="exampleInputEmail1">Email address</label>
            </div>
            <div className="col-75">
                <input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                <span style={{color: "red"}}>{this.state.errors["email"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
                <label htmlFor="message">Message</label>
            </div>
            <div className="col-75">
                <textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
                <span style={{color: "red"}}>{this.state.errors["message"]}</span>
            </div>
          </div>
          <div className="row">
            <button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
          </div>
      </form>
    )
  }
}

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

AngularJS - Passing data between pages

You need to create a service to be able to share data between controllers.

app.factory('myService', function() {
 var savedData = {}
 function set(data) {
   savedData = data;
 }
 function get() {
  return savedData;
 }

 return {
  set: set,
  get: get
 }

});

In your controller A:

myService.set(yourSharedData);

In your controller B:

$scope.desiredLocation = myService.get();

Remember to inject myService in the controllers by passing it as a parameter.

Axios get access to response header fields

For the SpringBoot2 just add

httpResponse.setHeader("Access-Control-Expose-Headers", "custom-header1, custom-header2");

to your CORS filter implementation code to have whitelisted custom-header1 and custom-header2 etc

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Generally, .c and .h files are for C or C-compatible code, everything else is C++.

Many folks prefer to use a consistent pairing for C++ files: .cpp with .hpp, .cxx with .hxx, .cc with .hh, etc. My personal preference is for .cpp and .hpp.

What is the Regular Expression For "Not Whitespace and Not a hyphen"

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

Official reasons for "Software caused connection abort: socket write error"

The java.net.SocketException is thrown when there is an error creating or accessing a socket (such as TCP). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn't receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.

The Socket Exception usually comes with the specified detail message about the issue.

Example of detailed messages:

  • Software caused connection abort: recv failed.

    The error indicates an attempt to send the message and the connection has been aborted by your server. If this happened while connecting to the database, this can be related to using not compatible Connector/J JDBC driver.

    Possible solution: Make sure you've proper libraries/drivers in your CLASSPATH.

  • Software caused connection abort: connect.

    This can happen when there is a problem to connect to the remote. For example due to virus-checker rejecting the remote mail requests.

    Possible solution: Check Virus scan service whether it's blocking the port for the outgoing requests for connections.

  • Software caused connection abort: socket write error.

    Possible solution: Make sure you're writing the correct length of bytes to the stream. So double check what you're sending. See this thread.

  • Connection reset by peer: socket write error / Connection aborted by peer: socket write error

    The application did not check whether keep-alive connection had been timed out on the server side.

    Possible solution: Ensure that the HttpClient is non-null before reading from the connection.E13222_01

  • Connection reset by peer.

    The connection has been terminated by the peer (server).

  • Connection reset.

    The connection has been either terminated by the client or closed by the server end of the connection due to request with the request.

    See: What's causing my java.net.SocketException: Connection reset?

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

Get the distance between two geo points

you can get distance and time using google Map API Google Map API

just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's

void parseJSONForDurationAndKMS(String json) throws JSONException {

    Log.d(TAG, "called parseJSONForDurationAndKMS");
    JSONObject jsonObject = new JSONObject(json);
    String distance;
    String duration;
    distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");

    Log.d(TAG, "distance : " + distance);
    Log.d(TAG, "duration : " + duration);

    distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);


}

How do I push a new local branch to a remote Git repository and track it too?

In Git 1.7.0 and later, you can checkout a new branch:

git checkout -b <branch>

Edit files, add and commit. Then push with the -u (short for --set-upstream) option:

git push -u origin <branch>

Git will set up the tracking information during the push.

Calling a parent window function from an iframe

Another addition for those who need it. Ash Clarke's solution does not work if they are using different protocols so be sure that if you are using SSL, your iframe is using SSL as well or it will break the function. His solution did work for the domains itself though, so thanks for that.

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

May be the problem is with your python-opencv version. It's better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.

How can I delete using INNER JOIN with SQL Server?

This version should work:

DELETE WorkRecord2
FROM WorkRecord2 
INNER JOIN Employee ON EmployeeRun=EmployeeNo
Where Company = '1' AND Date = '2013-05-06'

Move a view up only when the keyboard covers an input field

Swift 3 syntax:

func textFieldDidBeginEditing(_ textField: UITextField) {
    // add if for some desired textfields
        animateViewMoving(up: true, moveValue: 100)
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // add if for some desired textfields
        animateViewMoving(up: false, moveValue: 100)
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
     textFieldDidEndEditing(_ textField: UITextField) {

    let movementDuration:TimeInterval = 0.5

    let movement:CGFloat = ( up ? -moveValue : moveValue)

    UIView.beginAnimations("animateView", context: nil)

    UIView.setAnimationBeginsFromCurrentState(true)

    UIView.setAnimationDuration(movementDuration)

    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)

    UIView.commitAnimations()
}

this is a nice method to get what you want you can add "if" conditions for certain textfields but this type works for all... Hope it can be useful for everyone

How to return JSON data from spring Controller using @ResponseBody

I was facing same issue. I did not put @ResponseBody since I was using @RestController. But still I was getting error because I did not put the getter/setter method for the Company class. So after putting the getter/setter my problem was resolved.

Why is quicksort better than mergesort?

This is a pretty old question, but since I've dealt with both recently here are my 2c:

Merge sort needs on average ~ N log N comparisons. For already (almost) sorted sorted arrays this gets down to 1/2 N log N, since while merging we (almost) always select "left" part 1/2 N of times and then just copy right 1/2 N elements. Additionally I can speculate that already sorted input makes processor's branch predictor shine but guessing almost all branches correctly, thus preventing pipeline stalls.

Quick sort on average requires ~ 1.38 N log N comparisons. It does not benefit greatly from already sorted array in terms of comparisons (however it does in terms of swaps and probably in terms of branch predictions inside CPU).

My benchmarks on fairly modern processor shows the following:

When comparison function is a callback function (like in qsort() libc implementation) quicksort is slower than mergesort by 15% on random input and 30% for already sorted array for 64 bit integers.

On the other hand if comparison is not a callback, my experience is that quicksort outperforms mergesort by up to 25%.

However if your (large) array has a very few unique values, merge sort starts gaining over quicksort in any case.

So maybe the bottom line is: if comparison is expensive (e.g. callback function, comparing strings, comparing many parts of a structure mostly getting to a second-third-forth "if" to make difference) - the chances are that you will be better with merge sort. For simpler tasks quicksort will be faster.

That said all previously said is true: - Quicksort can be N^2, but Sedgewick claims that a good randomized implementation has more chances of a computer performing sort to be struck by a lightning than to go N^2 - Mergesort requires extra space

Collision Detection between two images in Java

Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.

Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'

I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.

Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.

Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)

edit: here we go

boolean

intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.

So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)

Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);

Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);

//detects when the two rectangles hit
if(rect1.intersects(rect2))
{

System.out.println("game over, g");
}

obviously you'd need to fit that in somewhere.

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

How to tell if homebrew is installed on Mac OS X

In my case Mac OS High Sierra 10.13.6

brew -v

OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)

How to save S3 object to a file using boto3

For those of you who would like to simulate the set_contents_from_string like boto2 methods, you can try

import boto3
from cStringIO import StringIO

s3c = boto3.client('s3')
contents = 'My string to save to S3 object'
target_bucket = 'hello-world.by.vor'
target_file = 'data/hello.txt'
fake_handle = StringIO(contents)

# notice if you do fake_handle.read() it reads like a file handle
s3c.put_object(Bucket=target_bucket, Key=target_file, Body=fake_handle.read())

For Python3:

In python3 both StringIO and cStringIO are gone. Use the StringIO import like:

from io import StringIO

To support both version:

try:
   from StringIO import StringIO
except ImportError:
   from io import StringIO

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore

How do I make HttpURLConnection use a proxy?

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax.

How to get the month name in C#?

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Simple bubble sort c#

It does the same in a more elegant way.

var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
   for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
   {
       if (arrayValues[mainLoop] <= arrayValues[innerLoop])
       {
         continue;
       }

       var temp = arrayValues[mainLoop];
       arrayValues[mainLoop] = arrayValues[innerLoop];
       arrayValues[innerLoop] = temp;
  }
}

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

Bootstrap 4, how to make a col have a height of 100%?

Use the Bootstrap 4 h-100 class for height:100%;

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">
    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>

https://www.codeply.com/go/zxd6oN1yWp

You'll also need ensure any parent(s) are also 100% height (or have a defined height)...

html,body {
  height: 100%;
}

Note: 100% height is not the same as "remaining" height.


Related: Bootstrap 4: How to make the row stretch remaining height?

How to decode HTML entities using jQuery?

I just had to have an HTML entity charater (⇓) as a value for a HTML button. The HTML code looks good from the beginning in the browser:

<input type="button" value="Embed & Share  &dArr;" id="share_button" />

Now I was adding a toggle that should also display the charater. This is my solution

$("#share_button").toggle(
    function(){
        $("#share").slideDown();
        $(this).attr("value", "Embed & Share " + $("<div>").html("&uArr;").text());
    }

This displays ⇓ again in the button. I hope this might help someone.

How to use su command over adb shell?

The su command does not execute anything, it just raise your privileges.

Try adb shell su -c YOUR_COMMAND.

Difference between a SOAP message and a WSDL?

A WSDL (Web Service Definition Language) is a meta-data file that describes the web service.

Things like operation name, parameters etc.

The soap messages are the actual payloads

Parse JSON with R

For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.

What is a serialVersionUID and why should I use it?

I can't pass up this opportunity to plug Josh Bloch's book Effective Java (2nd Edition). Chapter 11 is an indispensible resource on Java serialization.

Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the serialVersionUID. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).

If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool serialver to generate the serialVersionUID on the old class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by adding writeObject and readObject methods - see Serializable javadoc or aforementioned chapter 11.)

Importing json file in TypeScript

With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:

import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);

Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):

"resolveJsonModule": true,
"esModuleInterop": true,

Side notes:

  • Typescript 2.9.0 has a bug with this JSON feature, it was fixed with 2.9.2
  • The esModuleInterop is only necessary for the default import of the colorsJson. If you leave it set to false then you have to import it with import * as colorsJson from '../colors.json'

How to force a line break in a long word in a DIV?

Found that using the following worked across most major browsers (Chrome, IE, Safari iOS/OSX) except Firefox (v50.0.2) when using flexbox and relying on width: auto.

.your_element {
    word-wrap: break-word;   
    overflow-wrap: break-word;
    word-break: break-word;
}

Note: you may need to add browser vendor prefixes if you are not using an autoprefixer.

Another thing to watch out for is text using &nbsp; for spacing can cause line breaks mid-word.

Flutter does not find android sdk

I have got following issue on Flutter Doctor command.

X Android SDK file not found: ..\Android\sdk\platforms\android-28\android.jar.

to fix this just go to Tools=> Android Sdk =>Update Sdk Platform for which issue is there.(I installed SDK 28).

check flutter document for this issue

C# Connecting Through Proxy

            var getHtmlWeb = new HtmlWeb() { AutoDetectEncoding = false, OverrideEncoding = Encoding.GetEncoding("iso-8859-2") };

            WebProxy myproxy = new WebProxy("127.0.0.1:8888", false);
            NetworkCredential cred = (NetworkCredential)CredentialCache.DefaultCredentials;
            var document = getHtmlWeb.Load("URL", "GET", myproxy, cred);

Adjust width of input field to its input

FOR A NICER LOOK&FEEL

You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)

Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/

Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.

_x000D_
_x000D_
document.querySelector('input').addEventListener('input', onInput)_x000D_
_x000D_
function onInput(){_x000D_
    var spanElm = this.nextElementSibling;_x000D_
    spanElm.textContent = this.value; // the hidden span takes the value of the input; _x000D_
    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input_x000D_
};
_x000D_
/* it's important the input and its span have same styling */_x000D_
input, .measure {_x000D_
    padding: 5px;_x000D_
    font-size: 2.3rem;_x000D_
    font-family: Sans-serif;_x000D_
    white-space: pre; /* white-spaces will work effectively */_x000D_
}_x000D_
_x000D_
.measure{  _x000D_
  position: absolute;_x000D_
  left: -9999px;_x000D_
  top: -9999px;_x000D_
}
_x000D_
<input type="text" />_x000D_
<span class='measure'></span>
_x000D_
_x000D_
_x000D_

How to develop Desktop Apps using HTML/CSS/JavaScript?

I know for there's Fluid and Prism (there are others, that's the one I used to use) that let you load a website into what looks like a standalone app.

In Chrome, you can create desktop shortcuts for websites. (you do that from within Chrome, you can't/shouldn't package that with your app) Chrome Frame is different:

Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.

You'd need to have some sort of wrapper like that for your webapp, and then the rest is the web technologies you're used to. You can use HTML5 local storage to store data while the app is offline. I think you might even be able to work with SQLite.

I don't know how you would go about accessing OS specific features, though. What I described above has the same limitations as any "regular" website. Hopefully this gives you some sort of guidance on where to start.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

Maybe VT-X is not enabled in your BIOS.

See Intel HAXM documentation here: http://software.intel.com/en-us/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows

Intel VT-x not enabled

In some cases, Intel VT-x may be disabled in the system BIOS and must be enabled within the BIOS setup utility. To access the BIOS setup utility, a key must be pressed during the computer’s boot sequence. This key is dependent on which BIOS is used but it is typically the F2, Delete, or Esc key. Within the BIOS setup utility, Intel VT may be identified by the terms "VT", "Virtualization Technology", or "VT-d." Make sure to enable all of the Virtualization features.

Select mySQL based only on month and year

you can do it by changing $q to this:

$q="SELECT * FROM projects WHERE YEAR(date) = $year_v AND MONTH(date) = $month_v;