Programs & Examples On #Ldd

ldd is a unix command-line tool to print shared library dependencies for an executable or shared library.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How to add image in Flutter

How to include images in your app

1. Create an assets/images folder

  • This should be located in the root of your project, in the same folder as your pubspec.yaml file.
  • In Android Studio you can right click in the Project view
  • You don't have to call it assets or images. You don't even need to make images a subfolder. Whatever name you use, though, is what you will regester in the pubspec.yaml file.

2. Add your image to the new folder

  • You can just copy your image into assets/images. The relative path of lake.jpg, for example, would be assets/images/lake.jpg.

3. Register the assets folder in pubspec.yaml

  • Open the pubspec.yaml file that is in the root of your project.

  • Add an assets subsection to the flutter section like this:

      flutter:
        assets:
          - assets/images/lake.jpg
    
  • If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /):

      flutter:
        assets:
          - assets/images/
    

4. Use the image in code

  • Get the asset in an Image widget with Image.asset('assets/images/lake.jpg').

  • The entire main.dart file is here:

      import 'package:flutter/material.dart';
    
      void main() => runApp(MyApp());
    
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            home: Scaffold(
              appBar: AppBar(
                title: Text("Image from assets"),
              ),
              body: Image.asset('assets/images/lake.jpg'), //   <--- image
            ),
          );
        }
      }
    

5. Restart your app

When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.

Running the app now you should have something like this:

enter image description here

Further reading

  • See the documentation for how to do things like provide alternate images for different densities.

Videos

The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

enter image description heregoto Android->sdk->build-tools directory make sure you have all the versions required . if not , download them . after that goto File-->Settigs-->Build,Execution,Depoyment-->Gradle

choose use default gradle wapper (recommended)

and untick Offline work

gradle build finishes successfully for once you can change the settings

If it dosent simply solve the problem

check this link to find an appropriate support library revision

https://developer.android.com/topic/libraries/support-library/revisions

Make sure that the compile sdk and target version same as the support library version. It is recommended maintain network connection atleast for the first time build (Remember to rebuild your project after doing this)

Unable to merge dex

One of possible root causes: duplicate transient dependencies that weren't properly handled by Android Studio import of multi-module projects. Check your list and remove them. For me, the fix was literally this:

--- a/project/module/build.gradle
+++ b/project/module/build.gradle
@@ -21,5 +21,4 @@ android {
 dependencies {
     implementation project(':upstream-dependency-project')
     implementation 'com.android.support:support-v4:18.0.0'
-    implementation files('libs/slf4j-android-1.6.1-RC1.jar')
 }

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

For things to compile via command line I needed to include the maven repo in BOTH buildscript and allprojects.

root build.gradle:

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        ...
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

It's needed in the buildscript block to find the AGP, and in allprojects block to find android.arch and com.android.databinding packages (and others)

UPDATE: It looks like the new repo is just called google() but I still needed to declare it in both places.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I had a similar problem. The problem was that I incorrectly wrote the properties of the model in the attributes of the view:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{ferm.coin.value}"/> 

This part was wrong:

@{ferm.coin.value}

When I wrote the correct property, the error was resolved.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

  • changed distrubutionUrl from 4.1 to 4.4

  • changed build gradle version to 3.1.1 under project/android

works for me.

How to use local docker images with Minikube?

In addition to the accepted answer, you can also achieve what you originally wanted (creating a deployment using the run command) with the following command:

kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 --generator=run-pod/v1 

I found the information about the generator on the Kubernetes-dev forum:

If you're using kubectl run, it generates a manifest for you that happens to have imagePullPolicy set to Always by default. You can use this command to get an imagePullPolicy of IfNotPresent, which will work for minikube:

kubectl run --image=<container> --generator=run-pod/v1

Dan Lorenc

https://groups.google.com/forum/#!topic/kubernetes-dev/YfvWuFr_XOM

Error:Cause: unable to find valid certification path to requested target

Most of the times when I face this issue. I remove replace https with http. It solves the issue.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

I observed the same issue, and added the command and args block in yaml file. I am copying sample of my yaml file for reference

 apiVersion: v1
    kind: Pod
    metadata:
      labels:
        run: ubuntu
      name: ubuntu
      namespace: default
    spec:
      containers:
      - image: gcr.io/ow/hellokubernetes/ubuntu
        imagePullPolicy: Never
        name: ubuntu
        resources:
          requests:
            cpu: 100m
        command: ["/bin/sh"]
        args: ["-c", "while true; do echo hello; sleep 10;done"]
      dnsPolicy: ClusterFirst
      enableServiceLinks: true

Passing data into "router-outlet" child components

Following this question, in Angular 7.2 you can pass data from parent to child using the history state. So you can do something like

Send:

this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Retrieve:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.example);
}

But be careful to be consistent. For example, suppose you want to display a list on a left side bar and the details of the selected item on the right by using a router-outlet. Something like:


Item 1 (x) | ..............................................

Item 2 (x) | ......Selected Item Details.......

Item 3 (x) | ..............................................

Item 4 (x) | ..............................................


Now, suppose you have already clicked some items. Clicking the browsers back buttons will show the details from the previous item. But what if, meanwhile, you have clicked the (x) and delete from your list that item? Then performing the back click, will show you the details of a deleted item.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

This is due to MultiDex.

Steps to solve:

  1. In gradle->dependencies->(compile'com.android.support:multidex:1.0.1') Add this in dependencies

  2. In your project application class extends MultiDexApplication like this (public class MyApplication extends MultiDexApplication)

  3. Run and check

ImportError: No module named google.protobuf

The reason for this would be mostly due to the evil command pip install google. I was facing a similar issue for google-cloud, but the same steps are true for protobuf as well. Both of our issues deal with a namespace conflict over the 'google' namespace.

If you executed the pip install google command like I did then you are in the correct place. The google package is actually not owned by Google which can be confirmed by the command pip show google which outputs:

 Name: google
 Version: 1.9.3
 Summary: Python bindings to the Google search engine.
 Home-page: http://breakingcode.wordpress.com/
 Author: Mario Vilas
 Author-email: [email protected]
 License: UNKNOWN
 Location: <Path where this package is installed>
 Requires: beautifulsoup4

Because of this package, the google namespace is reserved and coincidentally google-cloud also expects namespace google > cloud and it results in a namespace collision for these two packages.

See in below screenshot namespace of google-protobuf as google > protobuf

google-cloud namespace screenshot google > cloud > datastore

Solution :- Unofficial google package need to be uninstalled which can be done by using pip uninstall google after this you can reinstall google-cloud using pip install google-cloud or protobuf using pip install protobuf

FootNotes :- Assuming you have installed the unofficial google package by mistake and you don't actually need it along with google-cloud package. If you need both unofficial google and google-cloud above solution won't work.

Furthermore, the unofficial 'google' package installs with it 'soupsieve' and 'beautifulsoup4'. You may want to also uninstall those packages.

Let me know if this solves your particular issue.

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

I had this issue today, I find the Facebook documentation and SDK disrespectful and arogant towards other developers to say the least.

Besides having the "app domains" in two different locations without much information (3 if you add a "web" platform), you also need to go to app products / facebook login / settings and add your redirect URL under Valid OAuth Redirect URIs

The error says NOTHING about the oauth settings.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Find your own local android-SDK, if you download the relevant SDK of ndk, there will be a folder called "ndk-bundle"

enter image description here

There is a folder called "toolchains" inside.

enter image description here

We noticed that there are no mips64el related files inside.

enter image description here

The solution is as follows:

Click here to download the NDK package separately through the browser. After unzipping, open the "toolchains" folder, compare it with the android-sdk->ndk-bundle->toolchains folder, find the missing folder, copy the past three. Recompile, the problem is solved.

ionic build Android | error: No installed build tools found. Please install the Android build tools

Warning for developers using Virtual Machines

I spent a very long time trying to resolve this issue. I tried everything in this post and many more solutions on the web. However, after many failures and going through what everyone on the web was saying I still couldn't resolve the issue on my VM - which is a Windows 10 image on VMWare Workstation.

After reviewing all the solutions and descriptions of machines/operating systems people were developing on the glaring difference in my setup was I was developing in a VM.

Solution: I pulled all my code onto the host machine (Windows 10 OS), reinstalled all the dependencies, and sure as heck it all worked out first go around. After a lot of research I found some warnings that Android Studio has some known issues around installing properly in some VMs. So if you were like me & tried all solutions (many times over) and nothing worked, but you're in a VM, you may need to consider building on your host (or other physical machine)

How do I check when a UITextField changes?

txf_Subject.addTarget(self, action:#selector(didChangeFirstText), for: .editingChanged)

@objc func didChangeText(textField:UITextField) {
    let str = textField.text
    if(str?.contains(" "))!{
        let newstr = str?.replacingOccurrences(of: " ", with: "")
        textField.text = newstr
    }
}

@objc func didChangeFirstText(textField:UITextField) {
    if(textField.text == " "){
        textField.text = ""
    }
}

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.

sudo modprobe bcm2835-v4l2

BTW, for this error please check your camera and file path is workable or not

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Remove the redundant Hibernate Configuration

If you're using Spring Boot, you don't need to provide the JPA and Hibernate configuration explicitly, as Spring Boot can do that for you.

Add database configuration properties

In the application.properties Spring Boot configuration file, you have the add your database configuration properties:

spring.datasource.driverClassName = "org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://localhost:5432/teste?charSet=LATIN1
spring.datasource.username = klebermo
spring.datasource.password = 123

Add Hibernate specific properties

And, in the same application.properties configuration file, you can also set custom Hibernate properties:

# Log SQL statements
spring.jpa.show-sql = false

# Hibernate ddl auto for generating the database schema
spring.jpa.hibernate.ddl-auto = create

# Hibernate database Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

That's it!

NSRange to Range<String.Index>

You need to use Range<String.Index> instead of the classic NSRange. The way I do it (maybe there is a better way) is by taking the string's String.Index a moving it with advance.

I don't know what range you are trying to replace, but let's pretend you want to replace the first 2 characters.

var start = textField.text.startIndex // Start at the string's start index
var end = advance(textField.text.startIndex, 2) // Take start index and advance 2 characters forward
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)

textField.text.stringByReplacingCharactersInRange(range, withString: string)

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

for sbt, use below versions

val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"

val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"

val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"

Add swipe to delete UITableViewCell

Swift 3:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // delete data and row
        dataList.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

If you want to do your part as developer, utilizing open source libraries, you should try including all those open source licenses within your apk. To do this, you can use the merge method in your packagingOptions.

Example:

packagingOptions {
        // This will get include every license and notice regardless of what dir it’s in.
        merge '**/LICENSE.txt'
        merge '**/NOTICE.txt'
        merge '**/notice.txt'
        merge '**/license.txt'
        merge '**/NOTICE'
        merge '**/LICENSE'
        merge '**/notice'
        merge '**/license'
        merge '**/LGPL2.1'
        // This will exclude any README files, regardless of the dir or the file type.
        exclude '**/README.*'
}

This answer is better than using pickFirst because that method only picks the first license it finds and disregards all the rest, kinda rendering it useless in this case.

So in short, use the merge method to include all those licenses from those kickass open source libraries you’ve been using.

More info on Gradle PackagingOptions.

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Actually, you need to update your repo first, then an upgrade of your Glibc can fix this issue.

Java: Convert String to TimeStamp

I'm sure the solution is that your oldDateString is something like "2009-10-20". Obviously this does not contain any time data lower than days. If you format this string with your new formatter where should it get the minutes, seconds and milliseconds from?

So the result is absolutely correct: 2009-10-20 00:00:00.000

What you'll need to solve this, is the original timestamp (incl. time data) before your first formatting.

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

How to dismiss keyboard iOS programmatically when pressing return

SWIFT 4:

self.view.endEditing(true)

or

Set text field's delegate to current viewcontroller and then:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true

}

Objective-C:

[self.view endEditing:YES];

or

Set text field's delegate to current viewcontroller and then:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

sending email via php mail function goes to spam

One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Check The data you are writing to Server. May be data has delimiter which is not used.

like

045|2272575|0.000|0.000|2013-10-07
045|2272585|0.000|0.000;2013-10-07

your delimiter is '|' but data has a delimiter ';'. So for this you are getting the error.

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Combining the results of two SQL queries as separate columns

You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1

SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y

Get value (String) of ArrayList<ArrayList<String>>(); in Java

listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);

You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");

ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");

collection.Add(listOfSomething1);    
collection.Add(listOfSomething2);

Show empty string when date field is 1/1/1900

Use this inside of query, no need to create extra variables.

CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN ''  ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'

Works like a charm.

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

Multiple left joins on multiple tables in one query

This kind of query should work - after rewriting with explicit JOIN syntax:

SELECT something
FROM   master      parent
JOIN   master      child ON child.parent_id = parent.id
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  parent.parent_id = 'rootID'

The tripping wire here is that an explicit JOIN binds before "old style" CROSS JOIN with comma (,). I quote the manual here:

In any case JOIN binds more tightly than the commas separating FROM-list items.

After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.

Just to make my point, this would work, too:

SELECT something
FROM   master parent
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
,      master child
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  child.parent_id = parent.id
AND    parent.parent_id = 'rootID'

But explicit JOIN syntax is generally preferable, as your case illustrates once again.

And be aware that multiple (LEFT) JOIN can multiply rows:

Child element click event trigger the parent click event

You need to use event.stopPropagation()

Live Demo

$('#childDiv').click(function(event){
    event.stopPropagation();
    alert(event.target.id);
});?

event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);

How do I scroll the UIScrollView when the keyboard appears?

Use following extension if you don't want to calculate too much:

func scrollSubviewToBeVisible(subview: UIView, animated: Bool) {
    let visibleFrame = UIEdgeInsetsInsetRect(self.bounds, self.contentInset)
    let subviewFrame = subview.convertRect(subview.bounds, toView: self)
    if (!CGRectContainsRect(visibleFrame, subviewFrame)) {
        self.scrollRectToVisible(subviewFrame, animated: animated)
    }
}

And maybe you want keep your UITextField always visible:

func textViewDidChange(textView: UITextView) {
    self.scrollView?.scrollSubviewToBeVisible(textView, animated: false)
}

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

Remove

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency> 

slf4j-log4j12 is the log4j binding for slf4j you dont need to add another log4j dependency.

Added
Provide the log4j configuration in log4j.properties and add it to your class path. There are sample configurations here

or you can change your binding to

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>

if you are configuring slf4j due to some dependencies requiring it.

ldconfig error: is not a symbolic link

Solved, at least at the point of the question.

I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.

VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:

ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link

I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.

My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.

Thanks.

libaio.so.1: cannot open shared object file

I'm having a similar issue.

I found

conda install pyodbc

is wrong!

when I use

apt-get install python-pyodbc

I solved this problem?

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

It does work by just taking the argument 'rb' read binary instead of 'r' read

configure: error: C compiler cannot create executables

I just had this issue building apache. The solution I used was the same as Mostafa, I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

This was one Mac OSX Mavericks

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

What is this date format? 2011-08-12T20:17:46.384Z

tl;dr

Standard ISO 8601 format is used by your input string.

Instant.parse ( "2011-08-12T20:17:46.384Z" ) 

ISO 8601

This format is defined by the sensible practical standard, ISO 8601.

The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is pronounced “Zulu”.

java.time

The old date-time classes bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. Avoid them.

Instead, use the java.time framework built into Java 8 and later. The java.time classes supplant both the old date-time classes and the highly successful Joda-Time library.

The java.time classes use ISO 8601 by default when parsing/generating textual representations of date-time values.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. That class can directly parse your input string without bothering to define a formatting pattern.

Instant instant = Instant.parse ( "2011-08-12T20:17:46.384Z" ) ;

Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

How to write multiple conditions in Makefile.am with "else if"

ifeq ($(CHIPSET),8960)
   BLD_ENV_BUILD_ID="8960"
else ifeq ($(CHIPSET),8930)
   BLD_ENV_BUILD_ID="8930"
else ifeq ($(CHIPSET),8064)
   BLD_ENV_BUILD_ID="8064"
else ifeq ($(CHIPSET), 9x15)
   BLD_ENV_BUILD_ID="9615"
else
   BLD_ENV_BUILD_ID=
endif

Python executable not finding libpython shared library

I had the same problem and I solved it this way:

If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0 in your case, you can just create a symbolic link to it:

sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

Then try running ldd again and see if it worked.

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

How to assign colors to categorical variables in ggplot2 that have stable mapping?

Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE, FALSE).

boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)

ggplot(myDataFrame, aes(date, duration)) + 
  geom_point(aes(colour = myboolean)) +
  boolScale

Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.

Here myboolean is the name of the column in myDataFrame holding the TRUE/FALSE factor. date and duration are the column names to be mapped to the x and y axis of the plot in this example.

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

Determine direct shared object dependencies of a Linux binary?

The objdump tool can tell you this information. If you invoke objdump with the -x option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".

For example running objdump -x /usr/lib/libXpm.so.4 on my system gives the following information in the "Dynamic Section":

Dynamic Section:
  NEEDED               libX11.so.6
  NEEDED               libc.so.6
  SONAME               libXpm.so.4
  INIT                 0x0000000000002450
  FINI                 0x000000000000e0e8
  GNU_HASH             0x00000000000001f0
  STRTAB               0x00000000000011a8
  SYMTAB               0x0000000000000470
  STRSZ                0x0000000000000813
  SYMENT               0x0000000000000018
  PLTGOT               0x000000000020ffe8
  PLTRELSZ             0x00000000000005e8
  PLTREL               0x0000000000000007
  JMPREL               0x0000000000001e68
  RELA                 0x0000000000001b38
  RELASZ               0x0000000000000330
  RELAENT              0x0000000000000018
  VERNEED              0x0000000000001ad8
  VERNEEDNUM           0x0000000000000001
  VERSYM               0x00000000000019bc
  RELACOUNT            0x000000000000001b

The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4 on my system just needs libX11.so.6 and libc.so.6.

It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.

Maven does not find JUnit tests to run

One more tip (in addition to the previous answers):

In Eclipse, go to your project's Properties > click Run/Debug Settings:

"This page allows you to manage launch configurations with the currently selected resource"

In there you can add (New...) or remove (Delete) any JU (JUnit) tests you have in your project (under the src/test/java folder, or course).

How to re-sign the ipa file?

The answers posted here all didn't quite work for me. They mainly skipped signing embedded frameworks (or including the entitlements).

Here's what's worked for me (it assumes that one ipa file exists is in the current directory):

PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in the keychain

unzip -q *.ipa
rm -rf Payload/*.app/_CodeSignature/

# Replace embedded provisioning profile
cp "$PROVISION" Payload/*.app/embedded.mobileprovision

# Extract entitlements from app
codesign -d --entitlements :entitlements.plist Payload/*.app/

# Re-sign embedded frameworks
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/Frameworks/*

# Re-sign the app (with entitlements)
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/

zip -qr resigned.ipa Payload

# Cleanup
rm entitlements.plist
rm -r Payload/

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

a href link for entire div in HTML/CSS

Two things you can do:

  1. Change #childdivimage to a span element, and change #parentdivimage to an anchor tag. This may require you to add some more styling to get things looking perfect. This is preffered, since it uses semantic markup, and does not rely on javascript.

  2. Use Javascript to bind a click event to #parentdivimage. You must redirect the browser window by modifying window.location inside this event. This is TheEasyWayTM, but will not degrade gracefully.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

"No such file or directory" error when executing a binary

Old question, but hopefully this'll help someone else.

In my case I was using a toolchain on Ubuntu 12.04 that was built on Ubuntu 10.04 (requires GCC 4.1 to build). As most of the libraries have moved to multiarch dirs, it couldn't find ld.so. So, make a symlink for it.

Check required path:

$ readelf -a arm-linux-gnueabi-gcc | grep interpreter:
      [Requesting program interpreter: /lib/ld-linux-x86-64.so.2]

Create symlink:

$ sudo ln -s /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib/ld-linux-x86-64.so.2

If you're on 32bit, it'll be i386-linux-gnu and not x86_64-linux-gnu.

Align DIV's to bottom or baseline

I had something similar and got it to work by effectively adding some padding-top to the child.

I'm sure some of the other answers here would get to the solution, but I couldn't get them to easily work after a lot of time; I instead ended up with the padding-top solution which is elegant in its simplicity, but seems kind of hackish to me (not to mention the pixel value it sets would probably depend on the parent height).

.htaccess redirect all pages to new domain

My solution as SymLinks did not work on my server so I used an If in my PHP.

function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
$redirect = str_replace("www.", "", curPageURL());
$remove_http_root    = str_replace('http://', '', $redirect);
$split_url_array     = explode('/', $remove_http_root );


if($split_url_array[0] == "olddomain.com"){
    header("Location: http://www.newdomain.com/$split_url_array[1]");
    die();
}

nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}

How to clear all <div>s’ contents inside a parent <div>?

$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});

or

$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});

Calculating the difference between two Java date instances

This is another sample. Which basically works for user-defined pattern.

   public static LinkedHashMap<String, Object> checkDateDiff(DateTimeFormatter dtfObj, String startDate, String endDate)
   {
          Map<String, Object> dateDiffMap = new HashMap<String, Object>();
          DateTime start = DateTime.parse(startDate,dtfObj);
          DateTime end = DateTime.parse(endDate,dtfObj);
          Interval interval = new Interval(start, end);
          Period period = interval.toPeriod();

          dateDiffMap.put("ISO-8601_PERIOD_FORMAT", period);
          dateDiffMap.put("YEAR", period.getYears());
          dateDiffMap.put("MONTH", period.getMonths());
          dateDiffMap.put("WEEK", period.getWeeks());
          dateDiffMap.put("DAY", period.getWeeks());             
          dateDiffMap.put("HOUR", period.getHours());
          dateDiffMap.put("MINUTE", period.getMinutes());
          dateDiffMap.put("SECOND", period.getSeconds());

          return dateDiffMap;        
   }

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Just found this class:

https://github.com/OliverLetterer/SLScrollViewKeyboardSupport

And so far it works very well on iPhone, including animations & the correct offset.

To use it, simply add to viewDidLoad:

self.support = [[SLScrollViewKeyboardSupport alloc] initWithScrollView:self.scrollView];

Is it possible to clone html element objects in JavaScript / JQuery?

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        {
        AssetID = x.AssetID,
        Status = xx.Online ?? false
        };

ld cannot find an existing library

The problem is the linker is looking for libmagic.so but you only have libmagic.so.1

A quick hack is to symlink libmagic.so.1 to libmagic.so

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to set a Timer in Java?

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

Convert date formats in bash

#since this was yesterday
date -dyesterday +%Y%m%d

#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d

#assuming this is similar to yesterdays `date` question from you 
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d

#going on @seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d

#or a method to read it from stdin
read -p "  Get date >> " DATE; printf "  AS YYYYMMDD format >> %s"  `date
-d"$DATE" +%Y%m%d`    

#which then outputs the following:
#Get date >> 27 june 2011   
#AS YYYYMMDD format >> 20110627

#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash

#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line

More on Dates

note this only works on GNU date

I have read that:

Solaris version of date, which is unable to support -d can be resolve with replacing sunfreeware.com version of date

How to Update Multiple Array Elements in mongodb

$[] operator selects all nested array ..You can update all array items with '$[]'

.update({"events.profile":10},{$set:{"events.$[].handled":0}},false,true)

Reference

Python read JSON file and modify

I would like to present a modified version of Vadim's solution. It helps to deal with asynchronous requests to write/modify json file. I know it wasn't a part of the original question but might be helpful for others.

In case of asynchronous file modification os.remove(filename) will raise FileNotFoundError if requests emerge frequently. To overcome this problem you can create temporary file with modified content and then rename it simultaneously replacing old version. This solution works fine both for synchronous and asynchronous cases.

import os, json, uuid

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    # add, remove, modify content

# create randomly named temporary file to avoid 
# interference with other thread/asynchronous request
tempfile = os.path.join(os.path.dirname(filename), str(uuid.uuid4()))
with open(tempfile, 'w') as f:
    json.dump(data, f, indent=4)

# rename temporary file replacing old file
os.rename(tempfile, filename)

How to delete row in gridview using rowdeleting event?

See the following code and make some changes to get the answer for your question

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    void CustomersGridView_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }  

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView RowDeleting Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        GridView RowDeleting Example
    </h3>
    <asp:Label ID="Message" ForeColor="Red" runat="server" />
    <br />
    <asp:GridView ID="CustomersGridView" runat="server" 
        DataSourceID="CustomersSqlDataSource" 
        AutoGenerateColumns="False"
        AutoGenerateDeleteButton="True" 
        OnRowDeleting="CustomersGridView_RowDeleting"
        DataKeyNames="CustomerID,AddressID">
        <Columns>
            <asp:BoundField DataField="FirstName" 
                HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" 
                SortExpression="City" />
            <asp:BoundField DataField="StateProvince" HeaderText="State" 
                SortExpression="StateProvince" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
        SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
            SalesLT.CustomerAddress.AddressID, 
            SalesLT.Customer.FirstName, 
            SalesLT.Customer.LastName, 
            SalesLT.Address.City, 
            SalesLT.Address.StateProvince 
            FROM SalesLT.Customer 
            INNER JOIN SalesLT.CustomerAddress 
            ON SalesLT.Customer.CustomerID = 
                SalesLT.CustomerAddress.CustomerID 
            INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
                SalesLT.Address.AddressID"
        DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
            @CustomerID and AddressID = @AddressID" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
        <DeleteParameters>
            <asp:Parameter Name="AddressID" />
            <asp:Parameter Name="CustomerID" />
        </DeleteParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

Upgrade python in a virtualenv

Did you see this? If I haven't misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv version).

If your virtualenv is installed with the same python version of the old one and upgrading your virtualenv package is not an option, you may want to read this in order to install a virtualenv with the python version you want.

EDIT

I've tested this approach (the one that create a new virtualenv on top of the old one) and it worked fine for me. I think you may have some problems if you change from python 2.6 to 2.7 or 2.7 to 3.x but if you just upgrade inside the same version (staying at 2.7 as you want) you shouldn't have any problem, as all the packages are held in the same folders for both python versions (2.7.x and 2.7.y packages are inside your_env/lib/python2.7/).

If you change your virtualenv python version, you will need to install all your packages again for that version (or just link the packages you need into the new version packages folder, i.e: your_env/lib/python_newversion/site-packages)

Set mouse focus and move cursor to end of input using jQuery

Looks like clearing the value after focusing and then resetting works.

input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);

How to do joins in LINQ on multiple fields in single join

var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

Bootstrap close responsive menu "on click"

In the HTML I added a class of nav-link to the a tag of each navigation link.

$('.nav-link').click(
    function () {
        $('.navbar-collapse').removeClass('in');
    }
);

Log4net does not write the log in the log file

In my case I had to give the IIS_IUSRS Read\write permission to the log file.

Is right click a Javascript event?

If you want to detect right mouse click, you shouldn't use MouseEvent.which property as it is non-standard and there's large incompatibility among browsers. (see MDN) You should instead use MouseEvent.button. It returns a number representing a given button:

  • 0: Main button pressed, usually the left button or the un-initialized state
  • 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
  • 2: Secondary button pressed, usually the right button
  • 3: Fourth button, typically the Browser Back button
  • 4: Fifth button, typically the Browser Forward button

MouseEvent.button handles more input types than just standard mouse:

Buttons may be configured differently to the standard "left to right" layout. A mouse configured for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values.

Reference:

  1. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  2. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

ImportError: No module named PyQt4.QtCore

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

sudo apt-get install build-essential

, or just the g++ package:

sudo apt-get install g++

How to add border radius on table row

The tr element does honor the border-radius. Can use pure html and css, no javascript.

JSFiddle link: http://jsfiddle.net/pflies/zL08hqp1/10/

_x000D_
_x000D_
tr {_x000D_
    border: 0;_x000D_
    display: block;_x000D_
    margin: 5px;_x000D_
}_x000D_
.solid {_x000D_
    border: 2px red solid;_x000D_
    border-radius: 10px;_x000D_
}_x000D_
.dotted {_x000D_
    border: 2px green dotted;_x000D_
    border-radius: 10px;_x000D_
}_x000D_
.dashed {_x000D_
    border: 2px blue dashed;_x000D_
    border-radius: 10px;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 5px;_x000D_
}
_x000D_
<table>_x000D_
    <tr>_x000D_
        <td>01</td>_x000D_
        <td>02</td>_x000D_
        <td>03</td>_x000D_
        <td>04</td>_x000D_
        <td>05</td>_x000D_
        <td>06</td>_x000D_
    </tr>_x000D_
    <tr class='dotted'>_x000D_
        <td>07</td>_x000D_
        <td>08</td>_x000D_
        <td>09</td>_x000D_
        <td>10</td>_x000D_
        <td>11</td>_x000D_
        <td>12</td>_x000D_
    </tr>_x000D_
    <tr class='solid'>_x000D_
        <td>13</td>_x000D_
        <td>14</td>_x000D_
        <td>15</td>_x000D_
        <td>16</td>_x000D_
        <td>17</td>_x000D_
        <td>18</td>_x000D_
    </tr>_x000D_
    <tr class='dotted'>_x000D_
        <td>19</td>_x000D_
        <td>20</td>_x000D_
        <td>21</td>_x000D_
        <td>22</td>_x000D_
        <td>23</td>_x000D_
        <td>24</td>_x000D_
    </tr>_x000D_
    <tr class='dashed'>_x000D_
        <td>25</td>_x000D_
        <td>26</td>_x000D_
        <td>27</td>_x000D_
        <td>28</td>_x000D_
        <td>29</td>_x000D_
        <td>30</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}

cd into directory without having permission

chmod +x openfire worked for me. It adds execution permission to the openfire folder.

Switch focus between editor and integrated terminal in Visual Studio Code

control + '~' will work for toggling between the two. and '`' is just above the tab button. This shortcut only works in mac.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

What are the ways to sum matrix elements in MATLAB?

The best practice is definitely to avoid loops or recursions in Matlab.

Between sum(A(:)) and sum(sum(A)). In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum(). (One can test reshape() and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)

As such, there is no reason sum(sum(A)) should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A)) is very wide-spread amongst users. It is likely that they hard-code sum(sum(A)) to be a single loop, the same to sum(A(:)).

Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.

First is using tic toc.

Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.

Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.

Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.

Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27 (line 70)
A=rand(100000000,1);

Below is using cputime

Size 100x100
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x1
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000x1000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27_2 (line 70)
A=rand(100000000,1);

In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:)) and sum(sum(A)).

I tried the largest size allowed on my computer a few more times.

Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.2808
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

They seem equivalent. Either one is good. But sum(sum(A)) requires that you know the dimension of your array is 2.

Android studio - Failed to find target android-18

You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT

  1. If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+

  2. If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project

So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.

Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

Using Linq to get the last N elements of a collection?

Here's my solution:

public static class EnumerationExtensions
{
    public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> input, int count)
    {
        if (count <= 0)
            yield break;

        var inputList = input as IList<T>;

        if (inputList != null)
        {
            int last = inputList.Count;
            int first = last - count;

            if (first < 0)
                first = 0;

            for (int i = first; i < last; i++)
                yield return inputList[i];
        }
        else
        {
            // Use a ring buffer. We have to enumerate the input, and we don't know in advance how many elements it will contain.
            T[] buffer = new T[count];

            int index = 0;

            count = 0;

            foreach (T item in input)
            {
                buffer[index] = item;

                index = (index + 1) % buffer.Length;
                count++;
            }

            // The index variable now points at the next buffer entry that would be filled. If the buffer isn't completely
            // full, then there are 'count' elements preceding index. If the buffer *is* full, then index is pointing at
            // the oldest entry, which is the first one to return.
            //
            // If the buffer isn't full, which means that the enumeration has fewer than 'count' elements, we'll fix up
            // 'index' to point at the first entry to return. That's easy to do; if the buffer isn't full, then the oldest
            // entry is the first one. :-)
            //
            // We'll also set 'count' to the number of elements to be returned. It only needs adjustment if we've wrapped
            // past the end of the buffer and have enumerated more than the original count value.

            if (count < buffer.Length)
                index = 0;
            else
                count = buffer.Length;

            // Return the values in the correct order.
            while (count > 0)
            {
                yield return buffer[index];

                index = (index + 1) % buffer.Length;
                count--;
            }
        }
    }

    public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> input, int count)
    {
        if (count <= 0)
            return input;
        else
            return input.SkipLastIter(count);
    }

    private static IEnumerable<T> SkipLastIter<T>(this IEnumerable<T> input, int count)
    {
        var inputList = input as IList<T>;

        if (inputList != null)
        {
            int first = 0;
            int last = inputList.Count - count;

            if (last < 0)
                last = 0;

            for (int i = first; i < last; i++)
                yield return inputList[i];
        }
        else
        {
            // Aim to leave 'count' items in the queue. If the input has fewer than 'count'
            // items, then the queue won't ever fill and we return nothing.

            Queue<T> elements = new Queue<T>();

            foreach (T item in input)
            {
                elements.Enqueue(item);

                if (elements.Count > count)
                    yield return elements.Dequeue();
            }
        }
    }
}

The code is a bit chunky, but as a drop-in reusable component, it should perform as well as it can in most scenarios, and it'll keep the code that's using it nice and concise. :-)

My TakeLast for non-IList`1 is based on the same ring buffer algorithm as that in the answers by @Mark Byers and @MackieChan further up. It's interesting how similar they are -- I wrote mine completely independently. Guess there's really just one way to do a ring buffer properly. :-)

Looking at @kbrimington's answer, an additional check could be added to this for IQuerable<T> to fall back to the approach that works well with Entity Framework -- assuming that what I have at this point does not.

Vertically aligning CSS :before and :after content

I just found a pretty neat solution, I think. The trick is to set the line-height of image (or any content) height.

text

Using CSS:

div{
  line-height: 26px; /* height of the image in #submit span:after */
}

span:after{
    content: url('images/forward.png');
    vertical-align: bottom;
}

That would probably also work without the span.

ModuleNotFoundError: No module named 'sklearn'

install these ==>> pip install -U scikit-learn scipy matplotlib if still getting the same error then , make sure that your imoprted statment should be correct. i made the mistike while writing ensemble so ,(check spelling) its should be >>> from sklearn.ensemble import RandomForestClassifier

How to display a readable array - Laravel

I have added a helper da() to Laravel which in fact works as an alias for dd($object->toArray())

Here is the Gist: https://gist.github.com/TommyZG/0505eb331f240a6324b0527bc588769c

How do I create a slug in Django?

There is corner case with some utf-8 characters

Example:

>>> from django.template.defaultfilters import slugify
>>> slugify(u"test aescóln")
u'test-aescon' # there is no "l"

This can be solved with Unidecode

>>> from unidecode import unidecode
>>> from django.template.defaultfilters import slugify
>>> slugify(unidecode(u"test aescóln"))
u'test-aescoln'

Better way to find index of item in ArrayList?

ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index

int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
    Log.e(TAG, "Object not found in List");
} else {
    Log.i(TAG, "" + position);
}

Output: List Index : 7

If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.

Done

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

How can I set the form action through JavaScript?

document.forms[0].action="http://..."

...assuming it is the first form on the page.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Placeholder in UITextView

I found own solution

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:PLACEHOLDER_TEXT])
    {
        textView.textColor = [UIColor lightGrayColor];
        dispatch_async(dispatch_get_main_queue(), ^
                       {
                           textView.selectedRange = NSMakeRange(0, 0);
                       });
    }
    else
    {
        textView.textColor = [UIColor blackColor];
    }

    [textView becomeFirstResponder];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""])
    {
        textView.text = PLACEHOLDER_TEXT;
        textView.textColor = [UIColor lightGrayColor];
    }

    [textView resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    if (range.location == 0 && range.length == [[textView text] length] && [text isEqualToString:@""])
    {
        textView.text = PLACEHOLDER_TEXT;
        textView.textColor = [UIColor lightGrayColor];

        dispatch_async(dispatch_get_main_queue(), ^
                       {
                           textView.selectedRange = NSMakeRange(0, 0);
                       });

        return NO;
    }

    if ([textView.text isEqualToString:PLACEHOLDER_TEXT])
    {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }

    return YES;
}

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Uninstall Node.JS using Linux command line?

after installing using the "ROCK-SOLID NODE.JS PLATFORM ON UBUNTU" script, i get this output. Which tells you how to uninstall nodejs.

Done. The new package has been installed and saved to

/tmp/node-install/node-v0.8.19/nodejs_0.8.19-1_i386.deb

You can remove it from your system anytime using:

  dpkg -r nodejs

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

Where can I download the jar for org.apache.http package?

http://www.java2s.com/Code/Jar/s/Downloadservletapijar.htm

Download servlet-api.jar That has all the files below:

META-INF/LICENSE
META-INF/MANIFEST.MF
META-INF/NOTICE
javax.servlet.Async

Context.class
javax.servlet.AsyncEvent.class
javax.servlet.AsyncListener.class
javax.servlet.DispatcherType.class
javax.servlet.Filter.class
javax.servlet.FilterChain.class
javax.servlet.FilterConfig.class
javax.servlet.FilterRegistration.class
javax.servlet.GenericServlet.class
javax.servlet.HttpConstraintElement.class
javax.servlet.HttpMethodConstraintElement.class
javax.servlet.MultipartConfigElement.class
javax.servlet.Registration.class
javax.servlet.RequestDispatcher.class
javax.servlet.Servlet.class
javax.servlet.ServletConfig.class
javax.servlet.ServletContainerInitializer.class
javax.servlet.ServletContext.class
javax.servlet.ServletContextAttributeEvent.class
javax.servlet.ServletContextAttributeListener.class
javax.servlet.ServletContextEvent.class
javax.servlet.ServletContextListener.class
javax.servlet.ServletException.class
javax.servlet.ServletInputStream.class
javax.servlet.ServletOutputStream.class
javax.servlet.ServletRegistration.class
javax.servlet.ServletRequest.class
javax.servlet.ServletRequestAttributeEvent.class
javax.servlet.ServletRequestAttributeListener.class
javax.servlet.ServletRequestEvent.class
javax.servlet.ServletRequestListener.class
javax.servlet.ServletRequestWrapper.class
javax.servlet.ServletResponse.class
javax.servlet.ServletResponseWrapper.class
javax.servlet.ServletSecurityElement.class
javax.servlet.SessionCookieConfig.class
javax.servlet.SessionTrackingMode.class
javax.servlet.SingleThreadModel.class
javax.servlet.UnavailableException.class
javax.servlet.annotation.HandlesTypes.class
javax.servlet.annotation.HttpConstraint.class
javax.servlet.annotation.HttpMethodConstraint.class
javax.servlet.annotation.MultipartConfig.class
javax.servlet.annotation.ServletSecurity.class
javax.servlet.annotation.WebFilter.class
javax.servlet.annotation.WebInitParam.class
javax.servlet.annotation.WebListener.class
javax.servlet.annotation.WebServlet.class
javax.servlet.descriptor.JspConfigDescriptor.class
javax.servlet.descriptor.JspPropertyGroupDescriptor.class
javax.servlet.descriptor.TaglibDescriptor.class
javax.servlet.http.Cookie.class
javax.servlet.http.HttpServlet.class
javax.servlet.http.HttpServletRequest.class
javax.servlet.http.HttpServletRequestWrapper.class
javax.servlet.http.HttpServletResponse.class
javax.servlet.http.HttpServletResponseWrapper.class
javax.servlet.http.HttpSession.class
javax.servlet.http.HttpSessionActivationListener.class
javax.servlet.http.HttpSessionAttributeListener.class
javax.servlet.http.HttpSessionBindingEvent.class
javax.servlet.http.HttpSessionBindingListener.class
javax.servlet.http.HttpSessionContext.class
javax.servlet.http.HttpSessionEvent.class
javax.servlet.http.HttpSessionListener.class
javax.servlet.http.HttpUtils.class
javax.servlet.http.NoBodyOutputStream.class
javax.servlet.http.NoBodyResponse.class
javax.servlet.http.Part.class
javax/servlet/LocalStrings.properties
javax/servlet/http/LocalStrings.properties
javax/servlet/resources/XMLSchema.dtd
javax/servlet/resources/datatypes.dtd
javax/servlet/resources/j2ee_1_4.xsd
javax/servlet/resources/j2ee_web_services_1_1.xsd
javax/servlet/resources/j2ee_web_services_client_1_1.xsd
javax/servlet/resources/javaee_5.xsd
javax/servlet/resources/javaee_6.xsd
javax/servlet/resources/javaee_web_services_1_2.xsd
javax/servlet/resources/javaee_web_services_1_3.xsd
javax/servlet/resources/javaee_web_services_client_1_2.xsd
javax/servlet/resources/javaee_web_services_client_1_3.xsd
javax/servlet/resources/web-app_2_2.dtd
javax/servlet/resources/web-app_2_3.dtd
javax/servlet/resources/web-app_2_4.xsd
javax/servlet/resources/web-app_2_5.xsd
javax/servlet/resources/web-app_3_0.xsd
javax/servlet/resources/web-common_3_0.xsd
javax/servlet/resources/web-fragment_3_0.xsd
javax/servlet/resources/xml.xsd

What is the fastest way to compare two sets in Java?

There is a method in Guava Sets which can help here:

public static <E>  boolean equals(Set<? extends E> set1, Set<? extends E> set2){
return Sets.symmetricDifference(set1,set2).isEmpty();
}

How to call window.alert("message"); from C#?

You should try this.

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);

How can I exclude all "permission denied" messages from "find"?

If you want to start search from root "/" , you will probably see output somethings like:

find: /./proc/1731/fdinfo: Permission denied
find: /./proc/2032/task/2032/fd: Permission denied

It's because of permission. To solve this:

  1. You can use sudo command:

    sudo find /. -name 'toBeSearched.file'
    

It asks super user's password, when enter the password you will see result what you really want. If you don't have permission to use sudo command which means you don't have super user's password, first ask system admin to add you to the sudoers file.

  1. You can use redirect the Standard Error Output from (Generally Display/Screen) to some file and avoid seeing the error messages on the screen! redirect to a special file /dev/null :

    find /. -name 'toBeSearched.file' 2>/dev/null
    
  2. You can use redirect the Standard Error Output from (Generally Display/Screen) to Standard output (Generally Display/Screen), then pipe with grep command with -v "invert" parameter to not to see the output lines which has 'Permission denied' word pairs:

    find /. -name 'toBeSearched.file' 2>&1 | grep -v 'Permission denied'
    

Display PDF file inside my android application

This is the perfect solution that worked for me without any 3rd party library.

Rendering a PDF Document in Android Activity/Fragment (Using PdfRenderer)

How do I get the position selected in a RecyclerView?

A different method - using setTag() and getTag() methods of the View class.

  1. use setTag() in the onBindViewHolder method of your adapter

    @Override
    public void onBindViewHolder(myViewHolder viewHolder, int position) {
        viewHolder.mCardView.setTag(position);
    }
    

    where mCardView is defined in the myViewHolder class

    private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
               public View mCardView;
    
               public myViewHolder(View view) {
                   super(view);
                   mCardView = (CardView) view.findViewById(R.id.card_view);
    
                   mCardView.setOnClickListener(this);
               }
           }
    
  2. use getTag() in your OnClickListener implementation

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();           
    
    //display toast with position of cardview in recyclerview list upon click
    Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

see https://stackoverflow.com/a/33027953/4658957 for more details

How to get value of checked item from CheckedListBox?

You can iterate over the CheckedItems property:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx

Error in Process.Start() -- The system cannot find the file specified

Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message

I.e. this causes an issue with Process.Start() not finding your exe:

PATH="C:\my program\bin";c:\windows\system32

Maybe it helps someone.

How would I create a UIAlertView in Swift?

Below is the reusable code for alert view and action sheet, Just write one line to show alert anywhere in application

class AlertView{

    static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

        for button in buttons{

            var style = UIAlertActionStyle.default
            let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
            if buttonText == "cancel"{
                style = .cancel
            }
            let action = UIAlertAction(title: button, style: style) { (_) in
                completionHandler(button)
            }
            alert.addAction(action)
        }

        DispatchQueue.main.async {
            if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
                rootViewController.present(alert, animated: true, completion: nil)
            }

        }
    }
}

Usage :

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
            print(button)
        }
    }

}

Example use of "continue" statement in Python?

Here is very good visual representation about continue and break statements

Chart

source

git: 'credential-cache' is not a git command

There is now a much easier way to setup Git password caching by double clicking a small exe on Windows. The program is still based on git-credential-winstore mentioned by the top voted answer, although the project has been moved from GitHub to http://gitcredentialstore.codeplex.com/

You can download the exe (and a binary for Mac) from this blog post: https://github.com/blog/1104-credential-caching-for-wrist-friendly-git-usage

Where is the Java SDK folder in my computer? Ubuntu 12.04

I found the solution to this with path name: /usr/lib/jvm/java-8-oracle

I'm on mint 18.1

Use PHP to convert PNG to JPG with compression?

You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.

HTH.

Read XLSX file in Java

If you want to work with xlsx, you'll have to use the org.apache.poi.ss package. This package has class XSSF, which can be used for parsing xlxs file. This Sample code works on Excel 2007 or later (.xlsx)

OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(data));
            Workbook wb = new XSSFWorkbook(pkg);
            Sheet sheet = wb.getSheetAt(0);
            Iterator<Row> rows = sheet.rowIterator();

        while (rows.hasNext()) {
            int j = 5;
            Person person= new Person ();
            Row row = rows.next();
            if (row.getRowNum() > 0) {
                person.setPersonId((int)(row.getCell(0).getNumericCellValue()));
                person.setFirstName(row.getCell(1).getStringCellValue());
                person.setLastName(row.getCell(2).getStringCellValue());
                person.setGroupId((int)(row.getCell(3).getNumericCellValue()));
                person.setUserName(row.getCell(4).getStringCellValue());
                person.setCreditId((int)(row.getCell(5).getNumericCellValue()));
            }

        }

Excel 1998-2003 file (.xls) - you may use HSSF library.
  just use :  Workbook wb = new HSSFWorkbook(pkg);

FromBody string parameter is giving null

Post the string with raw JSON, and do not forget the double quotation marks!

enter image description here

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

How do I filter ForeignKey choices in a Django ModelForm?

To do this with a generic view, like CreateView...

class AddPhotoToProject(CreateView):
    """
    a view where a user can associate a photo with a project
    """
    model = Connection
    form_class = CreateConnectionForm


    def get_context_data(self, **kwargs):
        context = super(AddPhotoToProject, self).get_context_data(**kwargs)
        context['photo'] = self.kwargs['pk']
        context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
        return context
    def form_valid(self, form):
        pobj = Photo.objects.get(pk=self.kwargs['pk'])
        obj = form.save(commit=False)
        obj.photo = pobj
        obj.save()

        return_json = {'success': True}

        if self.request.is_ajax():

            final_response = json.dumps(return_json)
            return HttpResponse(final_response)

        else:

            messages.success(self.request, 'photo was added to project!')
            return HttpResponseRedirect(reverse('MyPhotos'))

the most important part of that...

    context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)

, read my post here

Android View shadow

I'm using Android Studio 0.8.6 and I couldn't find:

android:background="@drawable/abc_menu_dropdown_panel_holo_light"

so I found this instead:

android:background="@android:drawable/dialog_holo_light_frame"

and it looks like this:

enter image description here

How to make a <div> or <a href="#"> to align center

In your html file:

<a href="contact.html" class="button large hpbottom">Get Started</a>

In your css file:

.hpbottom{
    text-align: center;
}

Easiest way to copy a table from one database to another?

I use Navicat for MySQL...

It makes all database manipulation easy !

You simply select both databases in Navicat and then use.

 INSERT INTO Database2.Table1 SELECT * from Database1.Table1

Calculate Age in MySQL (InnoDb)

You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2) function:

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

Demo

C++, What does the colon after a constructor mean?

This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++

Detecting value change of input[type=text] in jQuery

Try this.. credits to https://stackoverflow.com/users/1169519/teemu

for answering my question here: https://stackoverflow.com/questions/24651811/jquery-keyup-doesnt-work-with-keycode-filtering?noredirect=1#comment38213480_24651811

This solution helped me to progress on my project.

$("#your_textbox").on("input propertychange",function(){

   // Do your thing here.
});

Note: propertychange for lower versions of IE.

Javascript .querySelector find <div> by innerTEXT

Since you have asked it in javascript so you can have something like this

function contains(selector, text) {
  var elements = document.querySelectorAll(selector);
  return Array.prototype.filter.call(elements, function(element){
    return RegExp(text).test(element.textContent);
  });
}

And then call it like this

contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive

UIView touch event in controller

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
    self.viewLabel1.addGestureRecognizer(myView)
}

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true
 }

Oracle client and networking components were not found

Technology used: Windows 7, UFT 32 bit, Data Source ODBC pointing out to 32 bit C:\Windows\System32\odbcad32.exe, Oracle client with both versions installed 32 bit and 64 bit.

What worked for me:

1.Start -> search for Edit the system environment variables
2.System Variables -> Edit Path
3.Place the path for Oracle client 32 bit in front of the path for Oracle Client 64 bit.

Ex:

C:\APP\ORACLE\product\11.2.0\client_32\bin;C:\APP\ORACLE\product\11.2.0\client_64\bin

Get sum of MySQL column in PHP

Try this:

$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

PRINT statement in T-SQL

The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.

Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.

It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.

How can I convert a Unix timestamp to DateTime and vice versa?

See IdentityModel.EpochTimeExtensions

public static class EpochTimeExtensions
{
    /// <summary>
    /// Converts the given date value to epoch time.
    /// </summary>
    public static long ToEpochTime(this DateTime dateTime)
    {
        var date = dateTime.ToUniversalTime();
        var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
        var ts = ticks / TimeSpan.TicksPerSecond;
        return ts;
    }

    /// <summary>
    /// Converts the given date value to epoch time.
    /// </summary>
    public static long ToEpochTime(this DateTimeOffset dateTime)
    {
        var date = dateTime.ToUniversalTime();
        var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;
        var ts = ticks / TimeSpan.TicksPerSecond;
        return ts;
    }

    /// <summary>
    /// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind.
    /// </summary>
    public static DateTime ToDateTimeFromEpoch(this long intDate)
    {
        var timeInTicks = intDate * TimeSpan.TicksPerSecond;
        return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
    }

    /// <summary>
    /// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>.
    /// </summary>
    public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
    {
        var timeInTicks = intDate * TimeSpan.TicksPerSecond;
        return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);
    }
}

What's the best way to use R scripts on the command line (terminal)?

You might want to use python's rpy2 module. However, the "right" way to do this is with R CMD BATCH. You can modify this to write to STDOUT, but the default is to write to a .Rout file. See example below:

[ramanujan:~]$cat foo.R
print(rnorm(10))
[ramanujan:~]$R CMD BATCH foo.R
[ramanujan:~]$cat foo.Rout

R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]


 ~/.Rprofile loaded.
Welcome at  Fri Apr 17 13:33:17 2009
> print(rnorm(10))
 [1]  1.5891276  1.1219071 -0.6110963  0.1579430 -0.3104579  1.0072677 -0.1303165  0.6998849  1.9918643 -1.2390156
>

Goodbye at  Fri Apr 17 13:33:17 2009
> proc.time()
   user  system elapsed
  0.614   0.050   0.721

Note: you'll want to try out the --vanilla and other options to remove all the startup cruft.

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

Dictionary<int,string> comboSource = new Dictionary<int,string>();
comboSource.Add(1, "Sunday");
comboSource.Add(2, "Monday");

Aftr adding values to Dictionary, use this as combobox datasource:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

How to parse JSON response from Alamofire API in Swift?

I found the answer on GitHub for Swift2

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to clone ArrayList and also clone its contents?

A nasty way is to do it with reflection. Something like this worked for me.

public static <T extends Cloneable> List<T> deepCloneList(List<T> original) {
    if (original == null || original.size() < 1) {
        return new ArrayList<>();
    }

    try {
        int originalSize = original.size();
        Method cloneMethod = original.get(0).getClass().getDeclaredMethod("clone");
        List<T> clonedList = new ArrayList<>();

        // noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < originalSize; i++) {
            // noinspection unchecked
            clonedList.add((T) cloneMethod.invoke(original.get(i)));
        }
        return clonedList;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        System.err.println("Couldn't clone list due to " + e.getMessage());
        return new ArrayList<>();
    }
}

setTimeout in for-loop does not print consecutive values

I had the same problem once this is how I solved it.

Suppose I want 12 delays with an interval of 2 secs

    function animate(i){
         myVar=setTimeout(function(){
            alert(i);
            if(i==12){
              clearTimeout(myVar);
              return;
            }
           animate(i+1)
         },2000)
    }

    var i=1; //i is the start point 1 to 12 that is
    animate(i); //1,2,3,4..12 will be alerted with 2 sec delay

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

Scala vs. Groovy vs. Clojure

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

BitBucket - download source as ZIP

For git repositories, to download the latest commit, you can use:

https://bitbucket.org/owner/repository/get/HEAD.zip

For mercurial repositories:

https://bitbucket.org/owner/repository/get/tip.zip

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Immutable vs Mutable types

I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

Lets say you created a List

a = [1,2]

If you were to say:

b = a
b[1] = 3

Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.

PHP Foreach Arrays and objects

Assuming your sm_id and c_id properties are public, you can access them by using a foreach on the array:

$array = array(/* objects in an array here */);
foreach ($array as $obj) {
    echo $obj->sm_id . '<br />' . $obj->c_id . '<br />';
}

Determining whether an object is a member of a collection in VBA

I have some edit, best working for collections:

_x000D_
_x000D_
Public Function Contains(col As collection, key As Variant) As Boolean_x000D_
    Dim obj As Object_x000D_
    On Error GoTo err_x000D_
    Contains = True_x000D_
    Set obj = col.Item(key)_x000D_
    Exit Function_x000D_
    _x000D_
err:_x000D_
    Contains = False_x000D_
End Function
_x000D_
_x000D_
_x000D_

Static Classes In Java

There is a static nested class, this [static nested] class does not need an instance of the enclosing class in order to be instantiated itself.

These classes [static nested ones] can access only the static members of the enclosing class [since it does not have any reference to instances of the enclosing class...]

code sample:

public class Test { 
  class A { } 
  static class B { }
  public static void main(String[] args) { 
    /*will fail - compilation error, you need an instance of Test to instantiate A*/
    A a = new A(); 
    /*will compile successfully, not instance of Test is needed to instantiate B */
    B b = new B(); 
  }
}

accessing a variable from another class

I've tried making an object and tried using .getWidth and .getHeight but can't get it to work.

That´s because you are not setting the width and height fields in JFrame, but you are setting them on local variables. Fields HEIGHT and WIDTH are inhereted from ImageObserver

Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

See http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html

If width and height represent state of the frame, then you could refactorize them to fields, and write getters for them.

Then, you could create a Constructor that receives both values as parameters

public class DrawFrame extends JFrame {
 private int width;
 private int height;

 DrawFrame(int _width, int _height){

   this.width = _width;
   this.height = _height;

   //other stuff here
}
 public int getWidth(){}
 public int getHeight(){}

 //other methods
}

If widht and height are going to be constant (after created) then you should use the final modifier. This way, once they are assigned a value, they can´t be modified.

Also, the variables i use in DrawCircle, should I have them in the constructor or not?

The way it is writen now, will only allow you to create one type of circle. If you wan´t to create different circles, you should overload the constructor with one with arguments).

For example, if you want to change the attributes xPoint and yPoint, you could have a constructor

public DrawCircle(int _xpoint, int _ypoint){
  //build circle here.
 }

EDIT:

Where does _width and _height come from?

Those are arguments to constructors. You set values on them when you call the Constructor method.

In DrawFrame I set width and height. In DrawCircle I need to access the width and height of DrawFrame. How do I do this?

DrawFrame(){
   int width = 400;
   int height =400;

   /*
   * call DrawCircle constructor
   */
   content.pane(new DrawCircle(width,height));

   // other stuff

}

Now when the DrawCircle constructor executes, it will receive the values you used in DrawFrame as _width and _height respectively.

EDIT:

Try doing

 DrawFrame frame = new DrawFrame();//constructor contains code on previous edit.
 frame.setPreferredSize(new Dimension(400,400));

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html

How to merge two arrays of objects by ID using lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

var merge = _.merge(arr1, arr2);

Which is the short version of:

var merge = _.chain(arr1).zip(arr2).map(function(item) {
    return _.merge.apply(null, item);
}).value();

Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

var merge = _.map(arr1, function(item) {
    return _.merge(item, _.find(arr2, { 'member' : item.member }));
});

You can easily convert this to a mixin. See the example below:

_x000D_
_x000D_
_.mixin({_x000D_
  'mergeByKey' : function(arr1, arr2, key) {_x000D_
    var criteria = {};_x000D_
    criteria[key] = null;_x000D_
    return _.map(arr1, function(item) {_x000D_
      criteria[key] = item[key];_x000D_
      return _.merge(item, _.find(arr2, criteria));_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "name": 'yyyyyyyyyy',_x000D_
  "age": 26_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "name": 'xxxxxx',_x000D_
  "age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

Validate that text field is numeric usiung jQuery

I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/

if($('#Field').val() != "")
{
    if($.isNumeric($('#Field').val()) {
        errors+= "Field must be numeric.<br/>";
        success = false;
    }
}

CSS: 100% width or height while keeping aspect ratio?

By setting the CSS max-width property to 100%, an image will fill the width of it's parenting element, but won’t render larger than it's actual size, thus preserving resolution.

Setting the height property to auto maintains the aspect ratio of the image, using this technique allows static height to be overridden and enables the image to flex proportionally in all directions.

img {
    max-width: 100%;
    height: auto;      
}

What is the difference between screenX/Y, clientX/Y and pageX/Y?

I don't like and understand things, which can be explained visually, by words.

enter image description here

Better naming in Tuple classes than "Item1", "Item2"

I think I would create a class but another alternative is output parameters.

public void GetOrderRelatedIds(out int OrderGroupId, out int OrderTypeId, out int OrderSubTypeId, out int OrderRequirementId)

Since your Tuple only contains integers you could represent it with a Dictionary<string,int>

var orderIds = new Dictionary<string, int> {
    {"OrderGroupId", 1},
    {"OrderTypeId", 2},
    {"OrderSubTypeId", 3},
    {"OrderRequirementId", 4}.
};

but I don't recommend that either.

Create XML file using java

Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
        // root element


Element rootElement = doc.createElement("words");
            doc.appendChild(rootElement);
while (ptbt.hasNext()) {
                CoreLabel label = ptbt.next();
                System.out.println(label);

                m = r1.matcher(label.toString());
                //System.out.println(m.find());
                if (m.find() == true) {
                    Element w = doc.createElement("word");                  
                    w.appendChild(doc.createTextNode(label.toString()));
                    rootElement.appendChild(w);
                }

TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
        transformer.transform(source, result);
        // Output to console for testing
        StreamResult consoleResult = new StreamResult(System.out);
        transformer.transform(source, consoleResult);

This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I've read the sentence from a file)

What does body-parser do with express?

Let’s try to keep this least technical.

Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !

So, where is our data ? How will we extract it if its not only present in my request.

Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.

But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.

body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.

For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.

Extracting username and password from your request goes as simple as below if you use body-parser.

var loginDetails = {    
    username : request.body.username,    
    password : request.body.password    
};

So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.

gulp command not found - error after installing gulp

This works for me:

 npm link gulp
 npm update

jquery toggle slide from left to right and back

Sliding from the right:

$('#example').animate({width:'toggle'},350);

Sliding to the left:

$('#example').toggle({ direction: "left" }, 1000);

Python list subtraction operation

If the lists allow duplicate elements, you can use Counter from collections:

from collections import Counter
result = list((Counter(x)-Counter(y)).elements())

If you need to preserve the order of elements from x:

result = [ v for c in [Counter(y)] for v in x if not c[v] or c.subtract([v]) ]

Autoincrement VersionCode with gradle extra properties

Examples shown above don't work for different reasons

Here is my ready-to-use variant based on ideas from this article:

android {
    compileSdkVersion 28

    // https://stackoverflow.com/questions/21405457

    def propsFile = file("version.properties")
    // Default values would be used if no file exist or no value defined
    def customAlias = "Alpha"
    def customMajor = "0"
    def customMinor = "1"
    def customBuild = "1" // To be incremented on release

    Properties props = new Properties()
    if (propsFile .exists())
        props.load(new FileInputStream(propsFile ))

    if (props['ALIAS'] == null) props['ALIAS'] = customAlias else customAlias = props['ALIAS']
    if (props['MAJOR'] == null) props['MAJOR'] = customMajor else customMajor = props['MAJOR']
    if (props['MINOR'] == null) props['MINOR'] = customMinor else customMinor = props['MINOR']
    if (props['BUILD'] == null) props['BUILD'] = customBuild else customBuild = props['BUILD']

    if (gradle.startParameter.taskNames.join(",").contains('assembleRelease')) {
        customBuild = "${customBuild.toInteger() + 1}"
        props['BUILD'] = "" + customBuild

        applicationVariants.all { variant ->
            variant.outputs.all { output ->
                if (output.outputFile != null && (output.outputFile.name == "app-release.apk"))
                    outputFileName = "app-${customMajor}-${customMinor}-${customBuild}.apk"
            }
        }
    }

    props.store(propsFile.newWriter(), "Incremental Build Version")

    defaultConfig {
        applicationId "org.example.app"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode customBuild.toInteger()
        versionName "$customAlias $customMajor.$customMinor ($customBuild)"

        ...
    }
...
}

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

PG::ConnectionBad - could not connect to server: Connection refused

I have managed to solve the problem by following the Chris Slade's answer, but to restart the server, I had to use the following commands:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

that I found here (pjammer's answer down at the bottom)

Execute a shell script in current shell with sudo permission

I'm not sure if this breaks any rules but

sudo bash script.sh

seems to work for me.

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

How to get the cell value by column name not by index in GridView in asp.net

Based on something found on Code Project

Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.

protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (DataTable)((GridView)sender).DataSource;
        int colIndex = dt.Columns["MyColumnName"].Ordinal;

        e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
    }
}

How to clone an InputStream?

Below is the solution with Kotlin.

You can copy your InputStream into ByteArray

val inputStream = ...

val byteOutputStream = ByteArrayOutputStream()
inputStream.use { input ->
    byteOutputStream.use { output ->
        input.copyTo(output)
    }
}

val byteInputStream = ByteArrayInputStream(byteOutputStream.toByteArray())

If you need to read the byteInputStream multiple times, call byteInputStream.reset() before reading again.

https://code.luasoftware.com/tutorials/kotlin/how-to-clone-inputstream/

Check if a JavaScript string is a URL

One function that I have been using to validate a URL "string" is:

var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;

function isUrl(string){
  return matcher.test(string);
}

This function will return a boolean whether the string is a URL.

Examples:

isUrl("https://google.com");     // true
isUrl("http://google.com");      // true
isUrl("http://google.de");       // true
isUrl("//google.de");            // true
isUrl("google.de");              // false
isUrl("http://google.com");      // true
isUrl("http://localhost");       // true
isUrl("https://sdfasd");         // false

How to Change Margin of TextView

Your layout in xml probably already has a layout_margin(Left|Right|etc) attribute in it, which means you need to access the object generated by that xml and modify it.

I found this solution to be very simple:

ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mTextView
        .getLayoutParams();

mlp.setMargins(adjustmentPxs, 0, 0, 0);

break;

Get the LayoutParams instance of your textview, downcast it to MarginLayoutParams, and use the setMargins method to set the margins.

How do I delete specific characters from a particular String in Java?

You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.

In some cases a StringBuffer might help you instead.

How do I convert a PDF document to a preview image in PHP?

You can also get the page count using

$im->getNumberImages();

Then you can can create thumbs of all the pages using a loop, eg.

'file.pdf['.$x.']'

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

I'm pretty sure the classpath and the shared library search path have little to do with each other. According to The JNI Book (which admittedly is old), on Windows if you do not use the java.library.path system property, the DLL needs to be in the current working directory or in a directory listed in the Windows PATH environment variable.


Update:

Looks like Oracle has removed the PDF from its website. I've updated the link above to point to an instance of the PDF living at University of Texas - Arlington.

Also, you can also read Oracle's HTML version of the JNI Specification. That lives in the Java 8 section of the Java website and so hopefully will be around for a while.


Update 2:

At least in Java 8 (I haven't checked earlier versions) you can do:

java -XshowSettings:properties -version

to find the shared library search path. Look for the value of the java.library.path property in that output.

How to sort a list of strings numerically?

scores = ['91','89','87','86','85']
scores.sort()
print (scores)

This worked for me using python version 3, though it didn't in version 2.

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

How to read/write arbitrary bits in C/C++

Some 2+ years after I asked this question I'd like to explain it the way I'd want it explained back when I was still a complete newb and would be most beneficial to people who want to understand the process.

First of all, forget the "11111111" example value, which is not really all that suited for the visual explanation of the process. So let the initial value be 10111011 (187 decimal) which will be a little more illustrative of the process.

1 - how to read a 3 bit value starting from the second bit:

    ___  <- those 3 bits
10111011 

The value is 101, or 5 in decimal, there are 2 possible ways to get it:

  • mask and shift

In this approach, the needed bits are first masked with the value 00001110 (14 decimal) after which it is shifted in place:

    ___
10111011 AND
00001110 =
00001010 >> 1 =
     ___
00000101

The expression for this would be: (value & 14) >> 1

  • shift and mask

This approach is similar, but the order of operations is reversed, meaning the original value is shifted and then masked with 00000111 (7) to only leave the last 3 bits:

    ___
10111011 >> 1
     ___
01011101 AND
00000111
00000101

The expression for this would be: (value >> 1) & 7

Both approaches involve the same amount of complexity, and therefore will not differ in performance.

2 - how to write a 3 bit value starting from the second bit:

In this case, the initial value is known, and when this is the case in code, you may be able to come up with a way to set the known value to another known value which uses less operations, but in reality this is rarely the case, most of the time the code will know neither the initial value, nor the one which is to be written.

This means that in order for the new value to be successfully "spliced" into byte, the target bits must be set to zero, after which the shifted value is "spliced" in place, which is the first step:

    ___ 
10111011 AND
11110001 (241) =
10110001 (masked original value)

The second step is to shift the value we want to write in the 3 bits, say we want to change that from 101 (5) to 110 (6)

     ___
00000110 << 1 =
    ___
00001100 (shifted "splice" value)

The third and final step is to splice the masked original value with the shifted "splice" value:

10110001 OR
00001100 =
    ___
10111101

The expression for the whole process would be: (value & 241) | (6 << 1)

Bonus - how to generate the read and write masks:

Naturally, using a binary to decimal converter is far from elegant, especially in the case of 32 and 64 bit containers - decimal values get crazy big. It is possible to easily generate the masks with expressions, which the compiler can efficiently resolve during compilation:

  • read mask for "mask and shift": ((1 << fieldLength) - 1) << (fieldIndex - 1), assuming that the index at the first bit is 1 (not zero)
  • read mask for "shift and mask": (1 << fieldLength) - 1 (index does not play a role here since it is always shifted to the first bit
  • write mask : just invert the "mask and shift" mask expression with the ~ operator

How does it work (with the 3bit field beginning at the second bit from the examples above)?

00000001 << 3
00001000  - 1
00000111 << 1
00001110  ~ (read mask)
11110001    (write mask)

The same examples apply to wider integers and arbitrary bit width and position of the fields, with the shift and mask values varying accordingly.

Also note that the examples assume unsigned integer, which is what you want to use in order to use integers as portable bit-field alternative (regular bit-fields are in no way guaranteed by the standard to be portable), both left and right shift insert a padding 0, which is not the case with right shifting a signed integer.

Even easier:

Using this set of macros (but only in C++ since it relies on the generation of member functions):

#define GETMASK(index, size) ((((size_t)1 << (size)) - 1) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = (((data) & (~GETMASK((index), (size)))) | (((value) << (index)) & (GETMASK((index), (size))))))
#define FIELD(data, name, index, size) \
  inline decltype(data) name() const { return READFROM(data, index, size); } \
  inline void set_##name(decltype(data) value) { WRITETO(data, index, size, value); }

You could go for something as simple as:

struct A {
  uint bitData;
  FIELD(bitData, one, 0, 1)
  FIELD(bitData, two, 1, 2)
};

And have the bit fields implemented as properties you can easily access:

A a;
a.set_two(3);
cout << a.two();

Replace decltype with gcc's typeof pre-C++11.

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Combating AngularJS executing controller twice

I have the same issue in [email protected], and it because the extra slash in the end of regex route:

.when('/goods/publish/:classId/', option)

to

.when('/goods/publish/:classId', option)

and it works correctly.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

.NET does this for you. In your AssemblyInfo.cs file, set your assembly version to major.minor.* (for example: 1.0.*).

When you build your project the version is auto generated.

The build and revision numbers are generated based on the date, using the unix epoch, I believe. The build is based on the current day, and the revision is based on the number of seconds since midnight.

Imply bit with constant 1 or 0 in SQL Server

You might add the second snippet as a field definition for ICourseBased in a view.

DECLARE VIEW MyView
AS
  SELECT
  case 
  when FC.CourseId is not null then cast(1 as bit)
  else cast(0 as bit)
  end
  as IsCoursedBased
  ...

SELECT ICourseBased FROM MyView

How to set thymeleaf th:field value from other variable

It has 2 possible solutions:

1) You can set it in the view by javascript... (not recomended)

<input class="form-control"
       type="text"
       id="tbFormControll"
       th:field="*{clientName}"/>

<script type="text/javascript">
        document.getElementById("tbFormControll").value = "default";
</script>

2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.

public class FormControllModel {
    ...
    private String clientName = "default";
    public String getClientName () {
        return clientName;
    }
    public void setClientName (String value) {
        clientName = value;
    }
    ...
}

I hope it helps.

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

How can I get the baseurl of site?

I believe that the answers above doesn't consider when the site is not in the root of the website.

This is a for WebApi controller:

string baseUrl = (Url.Request.RequestUri.GetComponents(
                    UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/') 
                 + HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;

Why are static variables considered evil?

Summarising few basic Advantages & Disadvantages of using Static methods in Java:

Advantages:

  1. Globally accessible i.e. not tied with any particular object instance.
  2. One instance per JVM.
  3. Can be accessed by using class name (No object require).
  4. Contains a single value applicable to all instances.
  5. Load up on JVM startup and dies when JVM shuts down.
  6. They doesn't modify state of Object.

Disadvantages:

  1. Static members are always part of memory whether they are in use or not.
  2. You can not control creation and destruction of static variable. Usefully they have been created at program loading and destroyed when program unload (or when JVM shuts down).
  3. You can make statics thread safe using synchronize but you need some extra efforts.
  4. If one thread change value of a static variable that can possibly break functionality of other threads.
  5. You must know “static“ before using it.
  6. You cannot override static methods.
  7. Serialization doesn't work well with them.
  8. They don't participate in runtime polymorphism.
  9. There is a memory issue (to some extent but not much I guess) if a large number of static variables/methods are used. Because they will not be Garbage Collected until program ends.
  10. Static methods are hard to test too.

What's the most appropriate HTTP status code for an "item not found" error page

Getting overly clever with obscure-er HTTP error codes is a bad idea. Browsers sometimes react in unhelpful ways that obfuscate the situation. Stick with 404.

How to import Google Web Font in CSS file?

<link href="https://fonts.googleapis.com/css?family=(any font of your 
choice)" rel="stylesheet" type="text/css">

To choose the font you can visit the link : https://fonts.google.com

Write the font name of your choice from the website excluding the brackets.

For example you chose Lobster as a font of your choice then,

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" 
type="text/css">

Then you can use this normally as a font-family in your whole HTML/CSS file.

For example

<h2 style="Lobster">Please Like This Answer</h2>

Rendering HTML in a WebView with custom CSS

I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

How can I show an image using the ImageView component in javafx and fxml?

If you want to use FXML, you should separate the controller (like you were doing with the SampleController). Then your fx:controller in your FXML should point to that.

Probably you are missing the initialize method in your controller, which is part of the Initializable interface. This method is called after the FXML is loaded, so I recommend you to set your image there.

Your SampleController class must be something like this:

public class SampleController implements Initializable {

    @FXML
    private ImageView imageView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        File file = new File("src/Box13.jpg");
        Image image = new Image(file.toURI().toString());
        imageView.setImage(image);
    }
}

I tested here and it's working.

Inheriting constructors

If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
     using A::A;
};

This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

Combining two expressions (Expression<Func<T, bool>>)

I think this works fine, isn't it ?

Func<T, bool> expr1 = (x => x.Att1 == "a");
Func<T, bool> expr2 = (x => x.Att2 == "b");
Func<T, bool> expr1ANDexpr2 = (x => expr1(x) && expr2(x));
Func<T, bool> expr1ORexpr2 = (x => expr1(x) || expr2(x));
Func<T, bool> NOTexpr1 = (x => !expr1(x));

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

How store a range from excel into a Range variable?

Declare your dim as a variant, and pull the data as you would from an array. i.e.

Dim y As Variant
y = Range("A1:B2")

Now your excel range is all 1 variable (array), y

To pull the data, call the array position in the range "A1:B2" or whatever you choose. e.g.:

Msgbox y(1, 1)

This will return the top left box in the "A1:B2" range.

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

pip cannot install anything

I had the same issue with pip 1.5.6.

I just deleted the ~/.pip folder and it worked like a charm.

rm -r ~/.pip/

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

Configure apache to listen on port other than 80

This is working for me on Centos

First: in file /etc/httpd/conf/httpd.conf

add

Listen 8079 

after

Listen 80

This till your server to listen to the port 8079

Second: go to your virtual host for ex. /etc/httpd/conf.d/vhost.conf

and add this code below

<VirtualHost *:8079>
   DocumentRoot /var/www/html/api_folder
   ServerName example.com
   ServerAlias www.example.com
   ServerAdmin [email protected]
   ErrorLog logs/www.example.com-error_log
   CustomLog logs/www.example.com-access_log common
</VirtualHost>

This mean when you go to your www.example.com:8079 redirect to

/var/www/html/api_folder

But you need first to restart the service

sudo service httpd restart

Error: Cannot find module 'ejs'

The error hit me when i was working on goormIDE. This happens basically when node packages arent inside the running file. The place where app.js or home.js is executed.

How to check permissions of a specific directory?

In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.

Also, using ls -la myFile will list & show all the facts about that file.

Cannot authenticate into mongo, "auth fails"

I also received this error, what I needed was to specify the database where the user authentication data was stored:

mongo -u admin -p SECRETPASSWORD --authenticationDatabase admin

Update Nov 18 2017:

mongo admin -u admin -p

is a better solution. Mongo will prompt you for your password, this way you won't put your cleartext password into the shell history which is just terrible security practice.

Update a column value, replacing part of a string

UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

Spring Rest POST Json RequestBody Content type not supported

It looks an old thread, but in case someone still struggles, I have solved as Thibaut said it,

Avoid having two setter POJO class, I had two-setters for a specific property , The first one was in the regular setter and another one in under constructor after I removed the one in the constructor it worked.

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

Best way to do multiple constructors in PHP

In response to the best answer by Kris (which amazingly helped design my own class btw), here is a modified version for those that might find it useful. Includes methods for selecting from any column and dumping object data from array. Cheers!

public function __construct() {
    $this -> id = 0;
    //...
}

public static function Exists($id) {
    if (!$id) return false;
    $id = (int)$id;
    if ($id <= 0) return false;
    $mysqli = Mysql::Connect();
    if (mysqli_num_rows(mysqli_query($mysqli, "SELECT id FROM users WHERE id = " . $id)) == 1) return true;
    return false;
}

public static function FromId($id) {
    $u = new self();
    if (!$u -> FillFromColumn("id", $id)) return false;
    return $u;
}

public static function FromColumn($column, $value) {
    $u = new self();
    if (!$u -> FillFromColumn($column, $value)) return false;
    return $u;
}

public static function FromArray($row = array()) {
    if (!is_array($row) || $row == array()) return false;
    $u = new self();
    $u -> FillFromArray($row);
    return $u;
}

protected function FillFromColumn($column, $value) {
    $mysqli = Mysql::Connect();
    //Assuming we're only allowed to specified EXISTENT columns
    $result = mysqli_query($mysqli, "SELECT * FROM users WHERE " . $column . " = '" . $value . "'");
    $count = mysqli_num_rows($result);
    if ($count == 0) return false;
    $row = mysqli_fetch_assoc($result);
    $this -> FillFromArray($row);
}

protected function FillFromArray(array $row) {
    foreach($row as $i => $v) {
        if (isset($this -> $i)) {
            $this -> $i = $v;
        }
    }
}

public function ToArray() {
    $m = array();
    foreach ($this as $i => $v) {
        $m[$i] = $v;    
    }
    return $m;
}

public function Dump() {
    print_r("<PRE>");
    print_r($this -> ToArray());
    print_r("</PRE>");  
}

Convert a String representation of a Dictionary to a dictionary?

Use json. the ast library consumes a lot of memory and and slower. I have a process that needs to read a text file of 156Mb. Ast with 5 minutes delay for the conversion dictionary json and 1 minutes using 60% less memory!

Multiprocessing vs Threading Python

Threading's job is to enable applications to be responsive. Suppose you have a database connection and you need to respond to user input. Without threading, if the database connection is busy the application will not be able to respond to the user. By splitting off the database connection into a separate thread you can make the application more responsive. Also because both threads are in the same process, they can access the same data structures - good performance, plus a flexible software design.

Note that due to the GIL the app isn't actually doing two things at once, but what we've done is put the resource lock on the database into a separate thread so that CPU time can be switched between it and the user interaction. CPU time gets rationed out between the threads.

Multiprocessing is for times when you really do want more than one thing to be done at any given time. Suppose your application needs to connect to 6 databases and perform a complex matrix transformation on each dataset. Putting each job in a separate thread might help a little because when one connection is idle another one could get some CPU time, but the processing would not be done in parallel because the GIL means that you're only ever using the resources of one CPU. By putting each job in a Multiprocessing process, each can run on it's own CPU and run at full efficiency.

Efficient way to rotate a list in python

Another alternative:

def move(arr, n):
    return [arr[(idx-n) % len(arr)] for idx,_ in enumerate(arr)]

What is the path that Django uses for locating and loading templates?

If using Django settings as installed, then why not just use its baked-in, predefined BASE_DIR and TEMPLATES? In the pip installed Django(v1.8), I get:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            ### ADD YOUR DIRECTORY HERE LIKE SO:
            BASE_DIR + '/templates/',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Split function equivalent in T-SQL?

This is another version which really does not have any restrictions (e.g.: special chars when using xml approach, number of records in CTE approach) and it runs much faster based on a test on 10M+ records with source string average length of 4000. Hope this could help.

Create function [dbo].[udf_split] (
    @ListString nvarchar(max),
    @Delimiter  nvarchar(1000),
    @IncludeEmpty bit) 
Returns @ListTable TABLE (ID int, ListValue nvarchar(1000))
AS
BEGIN
    Declare @CurrentPosition int, @NextPosition int, @Item nvarchar(max), @ID int, @L int
    Select @ID = 1,
   @L = len(replace(@Delimiter,' ','^')),
            @ListString = @ListString + @Delimiter,
            @CurrentPosition = 1 
    Select @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
   While @NextPosition > 0 Begin
   Set  @Item = LTRIM(RTRIM(SUBSTRING(@ListString, @CurrentPosition, @NextPosition-@CurrentPosition)))
   If      @IncludeEmpty=1 or LEN(@Item)>0 Begin 
     Insert Into @ListTable (ID, ListValue) Values (@ID, @Item)
     Set @ID = @ID+1
   End
   Set  @CurrentPosition = @NextPosition+@L
   Set  @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
  End
    RETURN
END

The easiest way to transform collection to array?

For example, you have collection ArrayList with elements Student class:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

OK, just change your code to something like this:

<script>
function submit() {
   return confirm('Do you really want to submit the form?');
}
</script>

<form onsubmit="return submit(this);">
   <input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
      alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>

Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:

_x000D_
_x000D_
function submitForm() {_x000D_
  return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
  <input type="text" border="0" name="submit" />_x000D_
  <button value="submit">submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to install grunt and how to build script with it

You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.

Install grunt-cli with npm i -D grunt-cli instead of installing it globally with -g.

//package.json

...

"scripts": {
  "build": "grunt"
}

Then use npm run build to fire off grunt.

Symbol for any number of any characters in regex?

Do you mean

.*

. any character, except newline character, with dotall mode it includes also the newline characters

* any amount of the preceding expression, including 0 times

Exit/save edit to sudoers file? Putty SSH

To make changes to sudo from putty/bash:

  • Type visudo and press enter.
  • Navigate to the place you wish to edit using the up and down arrow keys.
  • Press insert to go into editing mode.
  • Make your changes - for example: user ALL=(ALL) ALL.
  • Note - it matters whether you use tabs or spaces when making changes.
  • Once your changes are done press esc to exit editing mode.
  • Now type :wq to save and press enter.
  • You should now be back at bash.
  • Now you can press ctrl + D to exit the session if you wish.

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

Get environment value in controller

In the book of Matt Stauffer he suggest to create an array in your config/app.php to add the variable and then anywhere you reference to it with:

$myvariable = new Namearray(config('fileWhichContainsVariable.array.ConfigKeyVariable'))

Have try this solution? is good ?

Returning string from C function

I came across this thread while working on my understanding of Cython. My extension to the original question might be of use to others working at the C / Cython interface. So this is the extension of the original question: how do I return a string from a C function, making it available to Cython & thus to Python?

For those not familiar with it, Cython allows you to statically type Python code that you need to speed up. So the process is, enjoy writing Python :), find its a bit slow somewhere, profile it, calve off a function or two and cythonize them. Wow. Close to C speed (it compiles to C) Fixed. Yay. The other use is importing C functions or libraries into Python as done here.

This will print a string and return the same or another string to Python. There are 3 files, the c file c_hello.c, the cython file sayhello.pyx, and the cython setup file sayhello.pyx. When they are compiled using python setup.py build_ext --inplace they generate a shared library file that can be imported into python or ipython and the function sayhello.hello run.

c_hello.c

#include <stdio.h>

char *c_hello() {
  char *mystr = "Hello World!\n";
  return mystr;
  // return "this string";  // alterative
}

sayhello.pyx

cdef extern from "c_hello.c":
    cdef char* c_hello()

def hello():
    return c_hello()

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize


ext_modules = cythonize([Extension("sayhello", ["sayhello.pyx"])])


setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

.append(), prepend(), .after() and .before()

Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.

The append() adds a new node to the child of the node you called it on.

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

The after() adds a new node as a sibling or at the same level or child to the parent of the node you called it on.

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Sort Array of object by object field in Angular 6

Not tested but should work

 products.sort((a,b)=>a.title.rendered > b.title.rendered)

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

How to install iPhone application in iPhone Simulator

This thread discusses how to install the binary on the simulator. I've done it and it works: http://forums.macrumors.com/showthread.php?t=547557

From the thread:

Look inside your ~/Library/Application Support/iPhone Simulator/User/Applications/ directory and see what happens inside this directory when you install and run apps using XCode, and also when you delete apps using the Simulator.

You can run the Simulator by itself (without starting XCode).

If you start the Simulator, delete an app, quit the Simulator, put back copies of the files that were deleted from the support directory, and restart the Simulator, the app will reappear in the Simulator. Email those files with instructions about how to copy them into the appropriate support directory.

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

SVN upgrade working copy

You can also get strange messages about the need to upgrade your working copy when there are other working copies nested into yours. I had this issue with a Symphony project were some framework folders are working copy, that I suppose have not been cleaned up properly before they were published.

In this case, just make a file search for .svn, and delete the .svn folders that you don't want (don't delete yours at the root of course).

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

var functionName = function() {} vs function functionName() {}

Another difference between both function is functionOne can be used as a variable that can hold multiple functions within and functionTwo holds some block of code that gets executed all when called. Please check below :

   var functionOne = (function() {
      return {

         sayHello: function(){
                console.log('say hello')

         },
         redirectPage:function(_url){
                window.location.href = _url;
         }

      }
})();

You have a choice which function to be called. e.g functionOne.sayHello or functionOne. redirectPage. And if you call functionTwo then whole block of code will get executed.

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

select * from user_tables;

(showing all tables)

Can I update a component's props in React.js?

PROPS

A React component should use props to store information that can be changed, but can only be changed by a different component.

STATE

A React component should use state to store information that the component itself can change.

A good example is already provided by Valéry.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

i had this issue, and fixed it. the problem seemed to be this:

wrong:

<add key="aaa" value="server=[abc\SQL2K8];database=bbb;uid=ccc;password=ddd;" />

right

<add key="aaa" value="server=abc\SQL2K8;database=bbb;uid=ccc;password=ddd;" />

How do I select text nodes with jQuery?

I had the same problem and solved it with:

Code:

$.fn.nextNode = function(){
  var contents = $(this).parent().contents();
  return contents.get(contents.index(this)+1);
}

Usage:

$('#my_id').nextNode();

Is like next() but also returns the text nodes.

The import android.support cannot be resolved

andorid-support-v4.jar is an external jar file that you have to import into your project.

This is how you do it in Android Studio:

Go to File -> Project Structure enter image description here

Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency" enter image description here

Select the support library "support-v4 (com.android.support:support-v4:23.0.1)" enter image description here

Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1' directly into your dependencies{} instead of doing it through the GUI.

enter image description here

Rebuild your project and now everything should work. enter image description here

How to update /etc/hosts file in Docker image during "docker build"

I think docker recently added the --add-host flag to docker build which is really great.

[Edit] So this feature was updated on 17.04.0-ce

For more detail on how to use docker build with the --add-host flag please visit: https://docs.docker.com/edge/engine/reference/commandline/build/

How can I create a table with borders in Android?

How about overriding the onDraw method and then painting lines to the canvas?

for(int i = 0; i < rows; i++)
    {
        canvas.drawLine(0, i * m_cellHeight, m_totalWidth, i * m_cellHeight, paint);
    }
    for(int i = 0; i < m_columns; i++){
        canvas.drawLine(i* m_cellWidth, 0, i * m_cellWidth, m_cellHeight * rows, paint);
    }

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

How do you determine the size of a file in C?

If you're fine with using the std c library:

#include <sys/stat.h>
off_t fsize(char *file) {
    struct stat filestat;
    if (stat(file, &filestat) == 0) {
        return filestat.st_size;
    }
    return 0;
}

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

How do I simulate placeholder functionality on input date field?

The input[type="date"] DOMElement only takes the following value: YYYY-MM-DD, any other format or text with be skipped.

Live Demo

HTML

<input type="text" placeholder="bingo" />
<input type="date" placeholder="2013-01-25" />

Pure JavaScript

window.onload = function () {
    /* Grab all elements with a placeholder attribute */
    var element = document.querySelectorAll('[placeholder]');

    /* Loop through each found elements */
    for (var i in element) {
        /* If the element is a DOMElement and has the nodeName "INPUT" */
        if (element[i].nodeType == 1 && element[i].nodeName == "INPUT") {

            /* We change the value of the element to its placeholder attr value */
            element[i].value = element[i].getAttribute('placeholder');
            /* We change its color to a light gray */
            element[i].style.color = "#777";

            /* When the input is selected/clicked on */
            element[i].onfocus = function (event) {
                /* If the value within it is the placeholder, we clear it */
                if (this.value == this.getAttribute('placeholder')) {
                    this.value = "";
                    /* Setting default text color */
                    this.style.color = "#000";
                };
            };

            /* We the input is left */
            element[i].onblur = function (event) {
                /* If the field is empty, we set its value to the placeholder */
                if (this.value == "") {
                    this.value = this.getAttribute('placeholder');
                    this.style.color = "#777";
                }
            };
        }
    }
}

Performance review

In this exact case, with 2 input elements, Pure JavaScript is ~40% ± 10% faster.

With 32 input elements, the difference remains the same (~43% ± 10% faster for Pure JS).

Referencing Row Number in R

This is probably the simplest way:

data$rownumber = 1:dim(data)[1]

It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation

data[3,]

vs.

data[data$rownumber==3,]

So I'm not really sure what this new column accomplishes.

How to get commit history for just one branch?

You can use a range to do that.

git log master..

If you've checked out your my_experiment branch. This will compare where master is at to HEAD (the tip of my_experiment).

Cannot find firefox binary in PATH. Make sure firefox is installed

java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.firefox.bin="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

Put selenium jar file on desktop, go to cmd and run the above command.

Elegant Python function to convert CamelCase to snake_case?

I was looking for a solution to the same problem, except that I needed a chain; e.g.

"CamelCamelCamelCase" -> "Camel-camel-camel-case"

Starting from the nice two-word solutions here, I came up with the following:

"-".join(x.group(1).lower() if x.group(2) is None else x.group(1) \
         for x in re.finditer("((^.[^A-Z]+)|([A-Z][^A-Z]+))", "stringToSplit"))

Most of the complicated logic is to avoid lowercasing the first word. Here's a simpler version if you don't mind altering the first word:

"-".join(x.group(1).lower() for x in re.finditer("(^[^A-Z]+|[A-Z][^A-Z]+)", "stringToSplit"))

Of course, you can pre-compile the regular expressions or join with underscore instead of hyphen, as discussed in the other solutions.

How to parse data in JSON format?

Sometimes your json is not a string. For example if you are getting a json from a url like this:

j = urllib2.urlopen('http://site.com/data.json')

you will need to use json.load, not json.loads:

j_obj = json.load(j)

(it is easy to forget: the 's' is for 'string')

round() doesn't seem to be rounding properly

Formatting works correctly even without having to round:

"%.1f" % n

How to call codeigniter controller function from view

Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.

A good start for clarifying the best practice is to follow this tutorial:

https://codeigniter.com/user_guide/tutorial/index.html

It's simple, but it really lays out an excellent how-to.

I hope this helps!

Python how to write to a binary file?

Use pickle, like this: import pickle

Your code would look like this:

import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
    pickle.dump(mybytes, mypicklefile)

To read the data back, use the pickle.load method

Is Python faster and lighter than C++?

All the slowest (>100x) usages of Python on the shootout are scientific operations that require high GFlop/s count. You should NOT use python for those anyways. The correct way to use python is to import a module that does those calculations, and then go have a relaxing afternoon with your family. That is the pythonic way :)

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

Replacing H1 text with a logo image: best method for SEO and accessibility?

<h1>
  <a href="http://stackoverflow.com">
  Stack Overflow<img src="logo.png" alt="Stack Overflow" />
  </a>
</h1>

This was the good option for SEO because SEO gives the H1 tag high priority, inside the h1 tag should be your site name. Using this method if you search the site name in SEO it will show your site logo as well.

you want to hide the site name OR text please use text-indent in negative value. ex

h1 a {
 text-indent: -99999px;
}

How to find list of possible words from a letter matrix [Boggle Solver]

I solved this too, with Java. My implementation is 269 lines long and pretty easy to use. First you need to create a new instance of the Boggler class and then call the solve function with the grid as a parameter. It takes about 100 ms to load the dictionary of 50 000 words on my computer and it finds the words in about 10-20 ms. The found words are stored in an ArrayList, foundWords.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Boggler {
    private ArrayList<String> words = new ArrayList<String>();      
    private ArrayList<String> roundWords = new ArrayList<String>(); 
    private ArrayList<Word> foundWords = new ArrayList<Word>();     
    private char[][] letterGrid = new char[4][4];                   
    private String letters;                                         

    public Boggler() throws FileNotFoundException, IOException, URISyntaxException {
        long startTime = System.currentTimeMillis();

        URL path = GUI.class.getResource("words.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path.toURI()).getAbsolutePath()), "iso-8859-1"));
        String line;
        while((line = br.readLine()) != null) {
            if(line.length() < 3 || line.length() > 10) {
                continue;
            }

            this.words.add(line);
        }
    }

    public ArrayList<Word> getWords() {
        return this.foundWords;
    }

    public void solve(String letters) {
        this.letters = "";
        this.foundWords = new ArrayList<Word>();

        for(int i = 0; i < letters.length(); i++) {
            if(!this.letters.contains(letters.substring(i, i + 1))) {
                this.letters += letters.substring(i, i + 1);
            }
        }

        for(int i = 0; i < 4; i++) {
            for(int j = 0; j < 4; j++) {
                this.letterGrid[i][j] = letters.charAt(i * 4 + j);
            }
        }

        System.out.println(Arrays.deepToString(this.letterGrid));               

        this.roundWords = new ArrayList<String>();      
        String pattern = "[" + this.letters + "]+";     

        for(int i = 0; i < this.words.size(); i++) {

            if(this.words.get(i).matches(pattern)) {
                this.roundWords.add(this.words.get(i));
            }
        }

        for(int i = 0; i < this.roundWords.size(); i++) {
            Word word = checkForWord(this.roundWords.get(i));

            if(word != null) {
                System.out.println(word);
                this.foundWords.add(word);
            }
        }       
    }

    private Word checkForWord(String word) {
        char initial = word.charAt(0);
        ArrayList<LetterCoord> startPoints = new ArrayList<LetterCoord>();

        int x = 0;  
        int y = 0;
        for(char[] row: this.letterGrid) {
            x = 0;

            for(char letter: row) {
                if(initial == letter) {
                    startPoints.add(new LetterCoord(x, y));
                }

                x++;
            }

            y++;
        }

        ArrayList<LetterCoord> letterCoords = null;
        for(int initialTry = 0; initialTry < startPoints.size(); initialTry++) {
            letterCoords = new ArrayList<LetterCoord>();    

            x = startPoints.get(initialTry).getX(); 
            y = startPoints.get(initialTry).getY();

            LetterCoord initialCoord = new LetterCoord(x, y);
            letterCoords.add(initialCoord);

            letterLoop: for(int letterIndex = 1; letterIndex < word.length(); letterIndex++) {
                LetterCoord lastCoord = letterCoords.get(letterCoords.size() - 1);  
                char currentChar = word.charAt(letterIndex);                        

                ArrayList<LetterCoord> letterLocations = getNeighbours(currentChar, lastCoord.getX(), lastCoord.getY());

                if(letterLocations == null) {
                    return null;    
                }       

                for(int foundIndex = 0; foundIndex < letterLocations.size(); foundIndex++) {
                    if(letterIndex != word.length() - 1 && true == false) {
                        char nextChar = word.charAt(letterIndex + 1);
                        int lastX = letterCoords.get(letterCoords.size() - 1).getX();
                        int lastY = letterCoords.get(letterCoords.size() - 1).getY();

                        ArrayList<LetterCoord> possibleIndex = getNeighbours(nextChar, lastX, lastY);
                        if(possibleIndex != null) {
                            if(!letterCoords.contains(letterLocations.get(foundIndex))) {
                                letterCoords.add(letterLocations.get(foundIndex));
                            }
                            continue letterLoop;
                        } else {
                            return null;
                        }
                    } else {
                        if(!letterCoords.contains(letterLocations.get(foundIndex))) {
                            letterCoords.add(letterLocations.get(foundIndex));

                            continue letterLoop;
                        }
                    }
                }
            }

            if(letterCoords != null) {
                if(letterCoords.size() == word.length()) {
                    Word w = new Word(word);
                    w.addList(letterCoords);
                    return w;
                } else {
                    return null;
                }
            }
        }

        if(letterCoords != null) {
            Word foundWord = new Word(word);
            foundWord.addList(letterCoords);

            return foundWord;
        }

        return null;
    }

    public ArrayList<LetterCoord> getNeighbours(char letterToSearch, int x, int y) {
        ArrayList<LetterCoord> neighbours = new ArrayList<LetterCoord>();

        for(int _y = y - 1; _y <= y + 1; _y++) {
            for(int _x = x - 1; _x <= x + 1; _x++) {
                if(_x < 0 || _y < 0 || (_x == x && _y == y) || _y > 3 || _x > 3) {
                    continue;
                }

                if(this.letterGrid[_y][_x] == letterToSearch && !neighbours.contains(new LetterCoord(_x, _y))) {
                    neighbours.add(new LetterCoord(_x, _y));
                }
            }
        }

        if(neighbours.isEmpty()) {
            return null;
        } else {
            return neighbours;
        }
    }
}

class Word {
    private String word;    
    private ArrayList<LetterCoord> letterCoords = new ArrayList<LetterCoord>();

    public Word(String word) {
        this.word = word;
    }

    public boolean addCoords(int x, int y) {
        LetterCoord lc = new LetterCoord(x, y);

        if(!this.letterCoords.contains(lc)) {
            this.letterCoords.add(lc);

            return true;
        }

        return false;
    }

    public void addList(ArrayList<LetterCoord> letterCoords) {
        this.letterCoords = letterCoords;
    } 

    @Override
    public String toString() {
        String outputString = this.word + " ";
        for(int i = 0; i < letterCoords.size(); i++) {
            outputString += "(" + letterCoords.get(i).getX() + ", " + letterCoords.get(i).getY() + ") ";
        }

        return outputString;
    }

    public String getWord() {
        return this.word;
    }

    public ArrayList<LetterCoord> getList() {
        return this.letterCoords;
    }
}

class LetterCoord extends ArrayList {
    private int x;          
    private int y;          

    public LetterCoord(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    @Override
    public boolean equals(Object o) {
        if(!(o instanceof LetterCoord)) {
            return false;
        }

        LetterCoord lc = (LetterCoord) o;

        if(this.x == lc.getX() &&
                this.y == lc.getY()) {
            return true;
        }

        return false;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + this.x;
        hash = 24 * hash + this.y;
        return hash;
    }
}

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I second Shobhit Verma, and I have a little note to add : in his post he told that in Chrome (Opera for myself) the players need to be muted in order for the autoplay to succeed... And ironically, if you elevate the volume after load, it will still play... It's like all those anti-pop-ups mechanic that ignore invisible frame slid into your code... php-echoed html and javascript is : 10-second setTimeout onLoad of body tag that rises volume to maximum, video with autoplay and muted='muted' (yeah that $muted_code part is = "muted='muted")

echo "<body style='margin-bottom:0pt; margin-top:0pt; margin-left:0pt; margin-right:0pt' onLoad=\"setTimeout(function() {var vid = document.getElementById('hourglass_video'); vid.volume = 1.0;},10000);\">";
    echo "<div id='hourglass_container' width='100%' height='100%' align='center' style='text-align:right; vertical-align:bottom'>";
    echo "<video autoplay {$muted_code}title=\"!!! Pausing this video will immediately end your turn!!!\" oncontextmenu=\"dont_stop_hourglass(event);\" onPause=\"{$action}\" id='hourglass_video' frameborder='0' style='width:95%; margin-top:28%'>";

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

How to reproduce this error with as few lines as possible:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> C.f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as 
first argument (got nothing instead)

It fails because of TypeError because you didn't instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.

It looks like you want to run the method in a static way, do this:

>>> class C:
...   @staticmethod
...   def f():
...     print "hi"
...
>>> C.f()
hi

Or, what you probably meant is to use the instantiated instance like this:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> c1 = C()
>>> c1.f()
hi
>>> C().f()
hi

If this confuses you, ask these questions:

  1. What is the difference between the behavior of a static method vs the behavior of a normal method?
  2. What does it mean to instantiate a class?
  3. Differences between how static methods are run vs normal methods.
  4. Differences between class and object.

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

implementing merge sort in C++

#include <iostream>
using namespace std;

template <class T>
void merge_sort(T array[],int beg, int end){
    if (beg==end){
        return;
    }
    int mid = (beg+end)/2;
    merge_sort(array,beg,mid);
    merge_sort(array,mid+1,end);
    int i=beg,j=mid+1;
    int l=end-beg+1;
    T *temp = new T [l];
    for (int k=0;k<l;k++){
        if (j>end || (i<=mid && array[i]<array[j])){
            temp[k]=array[i];
            i++;
        }
        else{
            temp[k]=array[j];
            j++;
        }
    }
    for (int k=0,i=beg;k<l;k++,i++){
        array[i]=temp[k];
    }
    delete temp;
}

int main() {
    float array[] = {1000.5,1.2,3.4,2,9,4,3,2.3,0,-5};
    int l = sizeof(array)/sizeof(array[0]);
    merge_sort(array,0,l-1);
    cout << "Result:\n";
    for (int k=0;k<l;k++){
        cout << array[k] << endl;
    }
    return 0;
}

Pipenv: Command Not Found

On Mac OS X Catalina it appears to follow the Linux path. Using any of:

pip install pipenv
pip3 install pipenv
sudo pip install pipenv
sudo pip3 install pipenv

Essentially installs pipenv here:

/Users/mike/Library/Python/3.7/lib/python/site-packages/pipenv

But its not the executable and so is never found. The only thing that worked for me was

pip install --user pipenv

This seems to result in an __init__.py file in the above directory that has contents to correctly expose the pipenv command.

and everything started working, when all other posted and commented suggestions on this question failed.

The pipenv package certainly seems quite picky.

List directory in Go

ioutil.ReadDir is a good find, but if you click and look at the source you see that it calls the method Readdir of os.File. If you are okay with the directory order and don't need the list sorted, then this Readdir method is all you need.

Lookup City and State by Zip Google Geocode Api

couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.

Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP() method.

You will be able to query by any zipcode (ex: 40220) and you will have a response back as the following...

<?xml version="1.0" encoding="UTF-8"?>
 <NewDataSet>
  <Table>
   <CITY>Louisville</CITY> 
   <STATE>KY</STATE> 
   <ZIP>40220</ZIP> 
   <AREA_CODE>502</AREA_CODE> 
   <TIME_ZONE>E</TIME_ZONE> 
  </Table> 
</NewDataSet>

Hope this helps...