Programs & Examples On #Uiwebview

A class used to display web content from within an iOS application. Note that UIWebView is deprecated since iOS 8, it is recommended by Apple to use WKWebView instead.

Can we open pdf file using UIWebView on iOS?

NSString *folderName=[NSString stringWithFormat:@"/documents/%@",[tempDictLitrature objectForKey:@"folder"]];
NSString *fileName=[tempDictLitrature objectForKey:@"name"];
[self.navigationItem setTitle:fileName];
NSString *type=[tempDictLitrature objectForKey:@"type"];

NSString *path=[[NSBundle mainBundle]pathForResource:fileName ofType:type inDirectory:folderName];

NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 730)];
[webView setBackgroundColor:[UIColor lightGrayColor]];
webView.scalesPageToFit = YES;

[[webView scrollView] setContentOffset:CGPointZero animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];

Stop UIWebView from "bouncing" vertically?

In the iOS 5 SDK you can access the scroll view associated with a web view directly rather than iterating through its subviews.

So to disable 'bouncing' in the scroll view you can use:

myWebView.scrollView.bounces = NO;

See the UIWebView Class Reference.

(However if you need to support versions of the SDK before 5.0, you should follow Mirek Rusin's advice.)

How to determine the content size of a UIWebView?

I'm using a UIWebView that isn't a subview (and thus isn't part of the window hierarchy) to determine the sizes of HTML content for UITableViewCells. I found that the disconnected UIWebView doesn't report its size properly with -[UIWebView sizeThatFits:]. Additionally, as mentioned in https://stackoverflow.com/a/3937599/9636, you must set the UIWebView's frame height to 1 in order to get the proper height at all.

If the UIWebView's height is too big (i.e. you have it set to 1000, but the HTML content size is only 500):

UIWebView.scrollView.contentSize.height
-[UIWebView stringByEvaluatingJavaScriptFromString:@"document.height"]
-[UIWebView sizeThatFits:]

All return a height of 1000.

To solve my problem in this case, I used https://stackoverflow.com/a/11770883/9636, which I dutifully voted up. However, I only use this solution when my UIWebView.frame.width is the same as the -[UIWebView sizeThatFits:] width.

Load resources from relative path using local html in uiwebview

@sdbrain's answer in Swift 3:

    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
    webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)

Change User Agent in UIWebView

Very simple in Swift. Just place the following into your App Delegate.

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom Agent"])

If you want to append to the existing agent string then:

let userAgent = UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")! + " Custom Agent"
UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])

Note: You may will need to uninstall and reinstall the App to avoid appending to the existing agent string.

UIWebView open links in Safari

Here's the Xamarin iOS equivalent of drawnonward's answer.

class WebviewDelegate : UIWebViewDelegate {
    public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
        if (navigationType == UIWebViewNavigationType.LinkClicked) {
            UIApplication.SharedApplication.OpenUrl (request.Url);
            return false;
        }
        return true;
    }
}

How to Migrate to WKWebView?

Swift 4

    let webView = WKWebView()   // Set Frame as per requirment, I am leaving it for you
    let url = URL(string: "http://www.google.com")!
    webView.load(URLRequest(url: url))
    view.addSubview(webView)

Using HTML and Local Images Within UIWebView

These answers did help me -- specifically the file:\\xxxxxxx.xxx, but I had to do a workaround to display the image.

In my case, I have an HTML file on my server which I download to the documents directory. I want to it to display with a local graphic in a UIWebView which I could not get to work. Here's what I did:

  1. Copy the file from the NSBundle to the local documents directory
  2. Reference the file in my HTML document as "file:\\filename.png"

So in startup copy the file to documents directory:

-(BOOL)copyBundleFilesToDocumentsDirectoryForFileName:(NSString *)fileNameToCopy OverwriteExisting:(BOOL)overwrite {
        //GET DOCUMENTS DIR
        //Search for standard documents using NSSearchPathForDirectoriesInDomains
        //First Param = Searching the documents directory
        //Second Param = Searching the Users directory and not the System
        //Expand any tildes and identify home directories.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];

        //COPY FILE FROM NSBUNDLE File to Local Documents Dir
        NSString *writableFilePath = [documentsDir  stringByAppendingPathComponent:fileNameToCopy];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *fileError;

        DDLogVerbose(@"File Copy From Bundle to Documents Dir would go to this path: %@", writableFilePath);

        if ([fileManager fileExistsAtPath:writableFilePath]) {
            DDLogVerbose(@"File %@ already exists in Documents Dir", fileNameToCopy);

            if (overwrite) {
                [fileManager removeItemAtPath:writableFilePath error:nil];
                DDLogVerbose(@"OLD File %@ was Deleted from  Documents Dir Successfully", fileNameToCopy);
            } else {
                return (NO);
            }
        }

        NSArray *fileNameParts = [fileNameToCopy componentsSeparatedByString:@"."];
        NSString *bundlePath = [[NSBundle mainBundle]pathForResource:[fileNameParts objectAtIndex:0] ofType:[fileNameParts objectAtIndex:1]];
        BOOL success = [fileManager copyItemAtPath:bundlePath toPath:writableFilePath error:&fileError];

        if (success) {
            DDLogVerbose(@"Copied %@ from Bundle to Documents Dir Successfully", fileNameToCopy);
        } else {
            DDLogError(@"File %@ could NOT be copied from bundle to Documents Dir due to error %@!!", fileNameToCopy, fileError);
        }

    return (success);
}

Reading HTML content from a UIWebView

To get the whole HTML raw data (with <head> and <body>):

NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

Clearing UIWebview cache

Don't disable caching completely, it'll hurt your app performance and it's unnecessary. The important thing is to explicitly configure the cache at app startup and purge it when necessary.

So in application:DidFinishLaunchingWithOptions: configure the cache limits as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{   
    int cacheSizeMemory = 4*1024*1024; // 4MB
    int cacheSizeDisk = 32*1024*1024; // 32MB
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
    [NSURLCache setSharedURLCache:sharedCache];

    // ... other launching code
}

Once you have it properly configured, then when you need to purge the cache (for example in applicationDidReceiveMemoryWarning or when you close a UIWebView) just do:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

and you'll see the memory is recovered. I blogged about this issue here: http://twobitlabs.com/2012/01/ios-ipad-iphone-nsurlcache-uiwebview-memory-utilization/

How to load local html file into UIWebView

[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];

It may be late but if the file from pathForResource is nil you should add it in the Build Phases > Copy Bundle Resources.

enter image description here

How to display .svg image using swift

SVG file support is added to Xcode 12.

enter image description here

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

XAMPP - MySQL shutdown unexpectedly

Guys just make sure you dont have MySql Server installed. Because I have MySql server pre-installed and when I start mysql from xampp control panel some port conflicts are happening and its not working.. SO before starting the mysql from xampp control panel make sure mysql server is not installed. I use .net so I have installed mysql server in the Past. Uninstalling it solved my Problem....

How to get the onclick calling object?

The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){
  e = e || window.event;
  var src = e.target || e.srcElement;
  //src element is the eventsource
}

How to hide underbar in EditText

Programmatically use : editText.setBackground(null)

From xml use: android:background="@null"

How to set border's thickness in percentages?

You can use em for percentage instead of pixels,

Example:

border:10PX dotted #c1a9ff; /* In Pixels */
border:0.75em dotted #c1a9ff; /* Exact same as above in Percentage */

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

How to debug a referenced dll (having pdb)

I had the *.pdb files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Run parallel multiple commands at once in the same terminal

Based on comment of @alessandro-pezzato. Run multiples commands by using & between the commands.

Example:

$ sleep 3 & sleep 5 & sleep 2 &

It's will execute the commands in background.

How to efficiently count the number of keys/properties of an object in JavaScript?

To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, Firefox 4+, or Safari 5+:

Object.keys(obj).length

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Wanted to share the actual code as few might still be confused about how to implement it.This is for C# NUNIT implementation. You need to do this because your company might not allow you to change the default security settings for obvious reasons. Good luck!

InternetExplorerOptions options = new InternetExplorerOptions();
            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            options.IgnoreZoomLevel = true;
            driver = new
                InternetExplorerDriver("C:\\Users\\stdd\\Desktop\\SLL\\SLLAutomation" +
                "\\Clysis\\STGSearch\\STGClaSearch\\Driver\\", options);
            driver.Manage().Window.Maximize();

How to check if a symlink exists

If you are testing for file existence you want -e not -L. -L tests for a symlink.

No Spring WebApplicationInitializer types detected on classpath

This turned out to be a stupid error. My log4j wasn't configured to capture my error output. I was throwing configuration errors in the background and once I fixed those I was good to go and my request mappings worked fine.

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

Get names of all keys in the collection

As per the mongoldb documentation, a combination of distinct

Finds the distinct values for a specified field across a single collection or view and returns the results in an array.

and indexes collection operations are what would return all possible values for a given key, or index:

Returns an array that holds a list of documents that identify and describe the existing indexes on the collection

So in a given method one could do use a method like the following one, in order to query a collection for all it's registered indexes, and return, say an object with the indexes for keys (this example uses async/await for NodeJS, but obviously you could use any other asynchronous approach):

async function GetFor(collection, index) {

    let currentIndexes;
    let indexNames = [];
    let final = {};
    let vals = [];

    try {
        currentIndexes = await collection.indexes();
        await ParseIndexes();
        //Check if a specific index was queried, otherwise, iterate for all existing indexes
        if (index && typeof index === "string") return await ParseFor(index, indexNames);
        await ParseDoc(indexNames);
        await Promise.all(vals);
        return final;
    } catch (e) {
        throw e;
    }

    function ParseIndexes() {
        return new Promise(function (result) {
            let err;
            for (let ind in currentIndexes) {
                let index = currentIndexes[ind];
                if (!index) {
                    err = "No Key For Index "+index; break;
                }
                let Name = Object.keys(index.key);
                if (Name.length === 0) {
                    err = "No Name For Index"; break;
                }
                indexNames.push(Name[0]);
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function ParseFor(index, inDoc) {
        if (inDoc.indexOf(index) === -1) throw "No Such Index In Collection";
        try {
            await DistinctFor(index);
            return final;
        } catch (e) {
            throw e
        }
    }
    function ParseDoc(doc) {
        return new Promise(function (result) {
            let err;
            for (let index in doc) {
                let key = doc[index];
                if (!key) {
                    err = "No Key For Index "+index; break;
                }
                vals.push(new Promise(function (pushed) {
                    DistinctFor(key)
                        .then(pushed)
                        .catch(function (err) {
                            return pushed(Promise.resolve());
                        })
                }))
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function DistinctFor(key) {
        if (!key) throw "Key Is Undefined";
        try {
            final[key] = await collection.distinct(key);
        } catch (e) {
            final[key] = 'failed';
            throw e;
        }
    }
}

So querying a collection with the basic _id index, would return the following (test collection only has one document at the time of the test):

Mongo.MongoClient.connect(url, function (err, client) {
    assert.equal(null, err);

    let collection = client.db('my db').collection('the targeted collection');

    GetFor(collection, '_id')
        .then(function () {
            //returns
            // { _id: [ 5ae901e77e322342de1fb701 ] }
        })
        .catch(function (err) {
            //manage your error..
        })
});

Mind you, this uses methods native to the NodeJS Driver. As some other answers have suggested, there are other approaches, such as the aggregate framework. I personally find this approach more flexible, as you can easily create and fine-tune how to return the results. Obviously, this only addresses top-level attributes, not nested ones. Also, to guarantee that all documents are represented should there be secondary indexes (other than the main _id one), those indexes should be set as required.

How to create module-wide variables in Python?

For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name. Add this as the first line of your module:

global __DBNAME__

'tuple' object does not support item assignment

You probably want the next transformation for you pixels:

pixels = map(list, image.getdata())

JAVA_HOME and PATH are set but java -version still shows the old one

check available Java versions on your Linux system by using update-alternatives command:

 $ sudo update-alternatives --display java

Now that there are suitable candidates to change to, you can switch the default Java version among available Java JREs by running the following command:

 $ sudo update-alternatives --config java

When prompted, select the Java version you would like to use.1 or 2 or 3 or etc..

Now you can verify the default Java version changed as follows.

 $ java -version

How to use multiprocessing pool.map with multiple arguments?

Another way is to pass a list of lists to a one-argument routine:

import os
from multiprocessing import Pool

def task(args):
    print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]

pool = Pool()

pool.map(task, [
        [1,2],
        [3,4],
        [5,6],
        [7,8]
    ])

One can than construct a list lists of arguments with one's favorite method.

How can I see the size of a GitHub repository before cloning it?

To do this with curl (sudo apt-get curl) and json pretty (sudo gem install jsonpretty json):

curl -u "YOURGITHUBUSERNAME" http://github.com/api/v2/json/repos/show/OWNER/REPOSITORY |
  jsonpretty

Replace YOURGITHUBUSERNAME with your GitHub username (go figure).

Replace OWNER with the repository owner's Git username. Replace REPOSITORY with the repository name.

Or as a nice Bash script (paste this in a file named gitrepo-info):

#!/bin/bash
if [ $# -ne 3 ]
then
  echo "Usage: gitrepo-info <username> <owner> <repo>"
  exit 65
fi
curl -u "$1" http://github.com/api/v2/json/repos/show/$2/$3|jsonpretty

Use it like so:

gitrepo-info larowlan pisi reel

This will give me information on the pisi/reel repository on GitHub.

SimpleXml to string

You can use casting:

<?php

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

$text = (string)$xml->child;

$text will be 'Hello World'

Hibernate show real SQL

select this_.code from true.employee this_ where this_.code=? is what will be sent to your database.

this_ is an alias for that instance of the employee table.

Android: why is there no maxHeight for a View?

As mentioned above, ConstraintLayout offers maximum height for its children via:

app:layout_constraintHeight_max="300dp"
app:layout_constrainedHeight="true"

Besides, if maximum height for one ConstraintLayout's child is uncertain until App running, there still has a way to make this child automatically adapt a mutable height no matter where it was placed in the vertical chain.

For example, we need to show a bottom dialog with a mutable header TextView, a mutable ScrollView and a mutable footer TextView. The dialog's max height is 320dp,when total height not reach 320dp ScrollView act as wrap_content, when total height exceed ScrollView act as "maxHeight=320dp - header height - footer height".

We can achieve this just through xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="320dp">

    <TextView
        android:id="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black_10"
        android:gravity="center"
        android:padding="10dp"
        app:layout_constraintBottom_toTopOf="@id/scroll_view"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1"
        app:layout_constraintVertical_chainStyle="packed"
        tools:text="header" />

    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black_30"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toTopOf="@id/tv_footer"
        app:layout_constraintHeight_max="300dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_header">

        <LinearLayout
            android:id="@+id/ll_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_sub1"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:gravity="center"
                android:textColor="@color/orange_light"
                tools:text="sub1" />

            <TextView
                android:id="@+id/tv_sub2"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:gravity="center"
                android:textColor="@color/orange_light"
                tools:text="sub2" />

        </LinearLayout>
    </ScrollView>

    <TextView
        android:id="@+id/tv_footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black_50"
        android:gravity="center"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/scroll_view"
        tools:text="footer" />
</android.support.constraint.ConstraintLayout>

Most import code is short:

app:layout_constraintVertical_bias="1"
app:layout_constraintVertical_chainStyle="packed"

app:layout_constrainedHeight="true"

Horizontal maxWidth usage is quite the same.

How do I save a stream to a file in C#?

Another option is to get the stream to a byte[] and use File.WriteAllBytes. This should do:

using (var stream = new MemoryStream())
{
    input.CopyTo(stream);
    File.WriteAllBytes(file, stream.ToArray());
}

Wrapping it in an extension method gives it better naming:

public void WriteTo(this Stream input, string file)
{
    //your fav write method:

    using (var stream = File.Create(file))
    {
        input.CopyTo(stream);
    }

    //or

    using (var stream = new MemoryStream())
    {
        input.CopyTo(stream);
        File.WriteAllBytes(file, stream.ToArray());
    }

    //whatever that fits.
}

How to download file from database/folder using php

You can use html5 tag to download the image directly

<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>

For more information, check this link http://www.w3schools.com/tags/att_a_download.asp

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

How do I check in JavaScript if a value exists at a certain array index?

when you create empty array values ARE NOT undefined, they are EMPTY

var arr = new Array(10); // (10) [empty × 10]

but when you get item by index receive undefined

arr[0]; // undefined

so you can't know by === comparing if they are undefined or empty

we can make it by using JSON.stringify, converting whole array it replaces empty values with null

JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined

so real check for empty value:

arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
  1. compare item with null (should be not equal)
  2. map array removing false instead existing values (ensure stringified structure to be comma-separated without redundant commas)
  3. JSON.stringify array
  4. remove brackets from string
  5. split into array by comma
  6. compare with null

Remove json element

try this

json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)

Custom checkbox image android

Create a drawable checkbox selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/checkbox" 
          android:state_checked="false"/>
    <item android:drawable="@drawable/checkboxselected" 
          android:state_checked="true"/>
    <item android:drawable="@drawable/checkbox"/>    
</selector>

Make sure your checkbox is like this android:button="@drawable/checkbox_selector"

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:button="@drawable/checkbox_selector"
    android:text="CheckBox"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="@color/Black" />

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

simplest method is just the copy the text that you want to paste it in cmd and open cmd goto "properties"---> "option" tab----> check the (give tick mark) "quickEdit mode" and click "ok" .....now you can paste any text from clipboard by doing right click from ur mouse.

Thank you..

Manually map column names with class properties

Before you open the connection to your database, execute this piece of code for each of your poco classes:

// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
    typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
    prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));

Then add the data annotations to your poco classes like this:

public class Section
{
    [Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
    public int Id { get; set; }
    [Column("db_column_name2")]
    public string Title { get; set; }
}

After that, you are all set. Just make a query call, something like:

using (var sqlConnection = new SqlConnection("your_connection_string"))
{
    var sqlStatement = "SELECT " +
                "db_column_name1, " +
                "db_column_name2 " +
                "FROM your_table";

    return sqlConnection.Query<Section>(sqlStatement).AsList();
}

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

How can I tell AngularJS to "refresh"

Why $apply should be called?

TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

git: Your branch is ahead by X commits

The answers that suggest git pull or git fetch are correct.
The message is generated when git status sees a difference between .git/FETCH_HEAD and .git/refs/remotes/<repository>/<branch> (e.g. .git/refs/remotes/origin/master).

The latter file records the HEAD from the last fetch (for the repository/branch). Doing git fetch updates both files to the branch's current HEAD.
Of course if there is nothing to fetch (because the local repository is already up-to-date) then .git/FETCH_HEAD doesn't change.

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

How to iterate through LinkedHashMap with lists as values

// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}

load external URL into modal jquery ui dialog

The following will work out of the box on any site:

_x000D_
_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>_x000D_
 _x000D_
    <div class="dialogBox" style="border:1px solid gray;">_x000D_
        <a href="/" class="exampleLink">Test</a>_x000D_
        <!-- TODO: Change above href -->_x000D_
        <!-- NOTE: Must be a local url, not cross domain -->_x000D_
    </div>_x000D_
    _x000D_
    <script type="text/javascript">_x000D_
         _x000D_
_x000D_
        var $modalDialog = $('<div/>', { _x000D_
          'class': 'exampleModal', _x000D_
          'id': 'exampleModal1' _x000D_
        })_x000D_
        .appendTo('body')_x000D_
        .dialog({_x000D_
            resizable: false,_x000D_
            autoOpen: false,_x000D_
            height: 300,_x000D_
            width: 350,_x000D_
            show: 'fold',_x000D_
            buttons: {_x000D_
                "Close": function () {_x000D_
                    $modalDialog.dialog("close");_x000D_
                }_x000D_
            },_x000D_
            modal: true_x000D_
        });_x000D_
_x000D_
        $(function () {_x000D_
            $('a.exampleLink').on('click', function (e) {_x000D_
                e.preventDefault();_x000D_
                // TODO: Undo comments, below_x000D_
                //var url = $('a.exampleLink:first').attr('href');_x000D_
                //$modalDialog.load(url);_x000D_
                $modalDialog.dialog("open");_x000D_
            });_x000D_
        });_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

launch sms application with an intent

on emulator this work for me

Intent i = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null));
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra("sms_body", remindingReason);

                startActivity(i);

How to generate javadoc comments in Android Studio

I can't find any shortcut to generate javadoc comments. But if you type /** before the method declaration and press Enter, the javadoc comment block will be generated automatically.

Read this for more information.

Output array to CSV in Ruby

If anyone is interested, here are some one-liners (and a note on loss of type information in CSV):

require 'csv'

rows = [[1,2,3],[4,5]]                    # [[1, 2, 3], [4, 5]]

# To CSV string
csv = rows.map(&:to_csv).join             # "1,2,3\n4,5\n"

# ... and back, as String[][]
rows2 = csv.split("\n").map(&:parse_csv)  # [["1", "2", "3"], ["4", "5"]]

# File I/O:
filename = '/tmp/vsc.csv'

# Save to file -- answer to your question
IO.write(filename, rows.map(&:to_csv).join)

# Read from file
# rows3 = IO.read(filename).split("\n").map(&:parse_csv)
rows3 = CSV.read(filename)

rows3 == rows2   # true
rows3 == rows    # false

Note: CSV loses all type information, you can use JSON to preserve basic type information, or go to verbose (but more easily human-editable) YAML to preserve all type information -- for example, if you need date type, which would become strings in CSV & JSON.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.

To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.

Edit: I've copied the steps below - kudos to the original author of the link above.

  1. Log on to the computer as an Administrator (or Any user with administrator privileges)
  2. Open "SQL Server Configuration Manager"
  3. Click "SQL Server Services" on the left pane
  4. Stop "SQL Server" and "SQL Server Agent" instance on the right pane if it is running
  5. Run the SQL Express in single-user mode by right clicking on "SQL Server" instance -> Properties (on the right pane of SQL Server Configuration Manager).
  6. Click Advanced Tab, and look for "Startup Parameters". Change the "Startup Parameters" so that the new value will be -m; (without the <>) example: from: -dc:\Program Files\Microsoft SQL.............(til end of string) to: -m;-dc:\Program Files\Microsoft SQL.............(til end of string)
  7. Start the SQL Server
  8. Open your MS SQL Server Management Studio and log on to the SQL server with "Windows Authentication" as the authentication mode. Since we have the SQL Server running on single user mode, and you are logged on to the computer with Administrator privileges, you will have a "sysadmin" access to the database.
  9. Expand the "Security" node on MS SQL Server Management Studio on the left pane
  10. Expand the "Logins" node
  11. Double-click the 'sa' login
  12. Change the password by entering a complex password if "Enforce password policy" is ticked, otherwise, just enter any password.
  13. Make sure that "sa" Account is "enabled" by clicking on Status on the left pane. Set the radio box under "Login" to "Enabled"
  14. Click "OK"
  15. Back on the main window of MS SQL Server Management Studio, verify if SQL Server Authentication is used by right clicking on the top most node in the left pane (usually ".\SQLEXPRESS (SQL Server )") and choosing properties.
  16. Click "Security" in the left pane and ensure that "SQL Server and Windows Authentication mode" is the one selected under "Server authentication"
  17. Click "OK"
  18. Disconnect from MS SQL Server Management Studio
  19. Open "Sql Server Configuration Manager" again and stop the SQL Server instance.
  20. Right-click on SQL Server instance and click on "Advanced" tab. Again look for "Startup Parameters" and remove the "-m;" that you added earlier.
  21. Click "OK" and start the SQL Server Instance again
  22. You should now be able to log on as "sa" using the new password that you have set in step 12.

JavaFX and OpenJDK

JavaFX is part of OpenJDK

The JavaFX project itself is open source and is part of the OpenJDK project.

Update Dec 2019

For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).

The open source code repository for JavaFX is at https://github.com/openjdk/jfx.

At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).

The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main

If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.

For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).


Older information which may become outdated over time

Building JavaFX from the OpenJDK repository

You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.

Update: Using a JavaFX distribution pre-built from OpenJDK sources

As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:

(currently this only works for Java 8 as far as I know).

Differences between Open JDK and Oracle JDK with respect to JavaFX

The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.

Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.

  1. The ON2 VP6 video codec, which is owned by Google and Google has not open sourced.
  2. The Oracle WebStart/Browser Embedded application deployment technology.

This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.

Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).

The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.

It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.

Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).

Update Dec, 2019:

An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.

Who needs to create Linux OpenJDK Distributions which include JavaFX

It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.

Update, Dec 2019:

Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.

If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.

Advice on Deployment for Substantial Applications

I advise using Java's self-contained application deployment mode.

A description of this deployment mode is:

Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.

You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.

As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).

Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.

Update, April 2018: Information on Oracle's current policy towards future developments

How to use LogonUser properly to impersonate domain user from workgroup client

I have been successfull at impersonating users in another domain, but only with a trust set up between the 2 domains.

var token = IntPtr.Zero;
var result = LogonUser(userID, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (result)
{
    return WindowsIdentity.Impersonate(token);
}

mysql data directory location

If you are using macOS {mine 'High Sierra'} and Installed XAMPP

You can find mysql data files;

Go to : /Applications/XAMPP/xamppfiles/var/mysql/

how to get the host url using javascript from the current page

let path = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;

How to check if a std::string is set or not?

Use empty():

std::string s;

if (s.empty())
    // nothing in s

Facebook Callback appends '#_=_' to Return URL

If you're using vue-router, you can append to the list of routes:

{
  path: '/_=_',
  redirect: '/', // <-- or other default route
},

Accessing inventory host variable in Ansible playbook

Thanks a lot this note was very useful for me! Was able to send the variable defined under /group_var/vars in the ansible playbook as indicated below.

tasks:
- name: check service account password expiry
- command:

sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

The issue is due to OpenSSL package is missing on your PC.

If pip install openpyxl also gives error.

you can fix this by installing OpenSSL(Win64 OpenSSL v1.1.1g) from below site :

slproweb.com/products/Win32OpenSSL.html

Restart the IDE you are using, for changes to be in effect.

Spring Boot Configure and Use Two DataSources

Here is the Complete solution

#First Datasource (DB1)
db1.datasource.url: url
db1.datasource.username:user
db1.datasource.password:password

#Second Datasource (DB2)
db2.datasource.url:url
db2.datasource.username:user
db2.datasource.password:password

Since we are going to get access two different databases (db1, db2), we need to configure each data source configuration separately like:

public class DB1_DataSource {
@Autowired
private Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean db1EntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(db1Datasource());
    em.setPersistenceUnitName("db1EntityManager");
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<string, object=""> properties = new HashMap<>();
    properties.put("hibernate.dialect",
            env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show-sql",
            env.getProperty("jdbc.show-sql"));
    em.setJpaPropertyMap(properties);
    return em;
}

@Primary
@Bean
public DataSource db1Datasource() {

    DriverManagerDataSource dataSource
            = new DriverManagerDataSource();
    dataSource.setDriverClassName(
            env.getProperty("jdbc.driver-class-name"));
    dataSource.setUrl(env.getProperty("db1.datasource.url"));
    dataSource.setUsername(env.getProperty("db1.datasource.username"));
    dataSource.setPassword(env.getProperty("db1.datasource.password"));

    return dataSource;
}

@Primary
@Bean
public PlatformTransactionManager db1TransactionManager() {

    JpaTransactionManager transactionManager
            = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(
            db1EntityManager().getObject());
    return transactionManager;
}
}

Second Datasource :

public class DB2_DataSource {

@Autowired
private Environment env;

@Bean
public LocalContainerEntityManagerFactoryBean db2EntityManager() {
    LocalContainerEntityManagerFactoryBean em
            = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(db2Datasource());
    em.setPersistenceUnitName("db2EntityManager");
    HibernateJpaVendorAdapter vendorAdapter
            = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<string, object=""> properties = new HashMap<>();
    properties.put("hibernate.dialect",
            env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show-sql",
            env.getProperty("jdbc.show-sql"));
    em.setJpaPropertyMap(properties);
    return em;
}

@Bean
public DataSource db2Datasource() {
    DriverManagerDataSource dataSource
            = new DriverManagerDataSource();
    dataSource.setDriverClassName(
            env.getProperty("jdbc.driver-class-name"));
    dataSource.setUrl(env.getProperty("db2.datasource.url"));
    dataSource.setUsername(env.getProperty("db2.datasource.username"));
    dataSource.setPassword(env.getProperty("db2.datasource.password"));

    return dataSource;
}

@Bean
public PlatformTransactionManager db2TransactionManager() {
    JpaTransactionManager transactionManager
            = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(
            db2EntityManager().getObject());
    return transactionManager;
}
}

Here you can find the complete Example on my blog : Spring Boot with Multiple DataSource Configuration

Setting a timeout for socket operations

You can't control the timeout due to UnknownHostException. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.

But I find it hard to believe that you are really getting an UnknownHostException when you specify an IP address rather than a hostname.

EDIT To control Java's DNS timeouts see this answer.

How to return more than one value from a function in Python?

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

How to create a box when mouse over text in pure CSS?

Exactly what they said, it will work.

In the parent element stablish a max-height.

I'm taking sandeep example and adding the max-height and if required you can add max-width property. The text will stay where It should stay (If possible, in some cases you will need to change some values to make it stay in there)

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;
}

span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
     transform:rotate(45deg);
}

p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
    max-height: 10px;
}

p:hover span{
    display:block;
}

max-height in the p paragraph, second to last one, last line.

Test it before rating it useless.

jQuery Change event on an <input> element - any way to retain previous value?

Some points.

Use $.data Instead of $.fn.data

// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);

Then, You can get the previous value through the event object, without complicating your life:

    $('#myInputElement').change(function(event){
        var defaultValue = event.target.defaultValue;
        var newValue = event.target.value;
    });

Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"

I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

Can I use break to exit multiple nested 'for' loops?

Break any number of loops by just one bool variable see below :

bool check = true;

for (unsigned int i = 0; i < 50; i++)
{
    for (unsigned int j = 0; j < 50; j++)
    {
        for (unsigned int k = 0; k < 50; k++)
        {
            //Some statement
            if (condition)
            {
                check = false;
                break;
            }
        }
        if (!check)
        {
            break;
        }
    }
    if (!check)
    {
        break;
    }
}

In this code we break; all the loops.

How to change package name of Android Project in Eclipse?

Goto the Src folder of your Android project, and open the Java file.

Change the package OldName.android.widget to newName.android.widget.

It gives you an error like this

The declared package "newName.android.widget" does not match the expected package "OLDName.android.widget.

To fix this problem, select Move filename.Java to Newname.android.widget and delete the old package folder.

Next step: Go to AndroidManifest.xml and change package="OldName.android.widget" to package="newName.android.widget".

How do I remove duplicates from a C# array?

  private static string[] distinct(string[] inputArray)
        {
            bool alreadyExists;
            string[] outputArray = new string[] {};

            for (int i = 0; i < inputArray.Length; i++)
            {
                alreadyExists = false;
                for (int j = 0; j < outputArray.Length; j++)
                {
                    if (inputArray[i] == outputArray[j])
                        alreadyExists = true;
                }
                        if (alreadyExists==false)
                        {
                            Array.Resize<string>(ref outputArray, outputArray.Length + 1);
                            outputArray[outputArray.Length-1] = inputArray[i];
                        }
            }
            return outputArray;
        }

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Object of class stdClass could not be converted to string

What I was looking for is a way to fetch the data

so I used this $data = $this->db->get('table_name')->result_array();

and then fetched my data just as you operate on array objects.

$data[0]['field_name']

No need to worry about type casting or anything just straight to the point.

So it worked for me.

How to create a HTML Cancel button that redirects to a URL

Here, i am using link in the form of button for CANCEL operation.

<button><a href="main.html">cancel</a></button>

Using Page_Load and Page_PreRender in ASP.Net

The major difference between Page_Load and Page_PreRender is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load() methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender is your last chance to tweak the page before it turns into HTML stream.

PDF Parsing Using Python - extracting formatted and plain texts

That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.

I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.

adding comment in .properties files

Writing the properties file with multiple comments is not supported. Why ?

PropertyFile.java

public class PropertyFile extends Task {

    /* ========================================================================
     *
     * Instance variables.
     */

    // Use this to prepend a message to the properties file
    private String              comment;

    private Properties          properties;

The ant property file task is backed by a java.util.Properties class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties class to save into the file.

The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment> elements.

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

href="javascript:" vs. href="javascript:void(0)"

This method seems ok in all browsers, if you set the onclick with a jQuery event:

<a href="javascript:;">Click me!</a>

As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.

How to convert Blob to String and String to Blob in java

try this (a2 is BLOB col)

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();

it may work even without BLOB, driver will transform types automatically:

   ps1.setBytes(1, str.getBytes);
   ps1.setString(1, str);

Besides if you work with text CLOB seems to be a more natural col type

Set Icon Image in Java

I use this:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class IconImageUtilities
{
    public static void setIconImage(Window window)
    {
        try
        {
            InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
            BufferedImage bufferedImage = ImageIO.read(imageInputStream);
            window.setIconImage(bufferedImage);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }
    }
}

Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:

IconImageUtilities.setIconImage(this);

How to properly use jsPDF library

This is finally what did it for me (and triggers a disposition):

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

C# how to use enum with switch

You should not cast to integer. And for the division, you need to cast left to double first, if not you will be doing an integer divide.

public enum Operator
{
    PLUS, MINUS, MULTIPLY, DIVIDE
}

public double Calculate(int left, int right, Operator op)
{
    double sum = 0.0;

    switch(op)
    {
       case Operator.PLUS:
       sum = left + right;
       return sum;

       case Operator.MINUS:
       sum = left - right;
       return sum;

       case Operator.MULTIPLY:
       sum = left * right;
       return sum;

       case Operator.DIVIDE:
       sum = (double)left / right;
       return sum;

       default:
       return sum;
   }

   return sum;
}

Clear git local cache

To remove cached .idea/ directory. e.g. git rm -r --cached .idea

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

(A lot of theoretical and conceptual explanation has been given above)

Below are some of the practical examples when I used static_cast, dynamic_cast, const_cast, reinterpret_cast.

(Also referes this to understand the explaination : http://www.cplusplus.com/doc/tutorial/typecasting/)

static_cast :

OnEventData(void* pData)

{
  ......

  //  pData is a void* pData, 

  //  EventData is a structure e.g. 
  //  typedef struct _EventData {
  //  std::string id;
  //  std:: string remote_id;
  //  } EventData;

  // On Some Situation a void pointer *pData
  // has been static_casted as 
  // EventData* pointer 

  EventData *evtdata = static_cast<EventData*>(pData);
  .....
}

dynamic_cast :

void DebugLog::OnMessage(Message *msg)
{
    static DebugMsgData *debug;
    static XYZMsgData *xyz;

    if(debug = dynamic_cast<DebugMsgData*>(msg->pdata)){
        // debug message
    }
    else if(xyz = dynamic_cast<XYZMsgData*>(msg->pdata)){
        // xyz message
    }
    else/* if( ... )*/{
        // ...
    }
}

const_cast :

// *Passwd declared as a const

const unsigned char *Passwd


// on some situation it require to remove its constness

const_cast<unsigned char*>(Passwd)

reinterpret_cast :

typedef unsigned short uint16;

// Read Bytes returns that 2 bytes got read. 

bool ByteBuffer::ReadUInt16(uint16& val) {
  return ReadBytes(reinterpret_cast<char*>(&val), 2);
}

Making a WinForms TextBox behave like your browser's address bar

I find this work best, when mouse click and not release immediately:

    private bool SearchBoxInFocusAlready = false;
    private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
    {
        SearchBoxInFocusAlready = false;
    }

    private void SearchBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.ButtonState == MouseButtonState.Released && e.ChangedButton == MouseButton.Left &&
            SearchBox.SelectionLength == 0 && SearchBoxInFocusAlready == false)
        {
            SearchBox.SelectAll();
        }

        SearchBoxInFocusAlready = true;
    }

Android Studio 3.0 Execution failed for task: unable to merge dex

Are you in between SDK or platform updates? If yes complete those completely and then try to continue. I normally update the individual packages that need to be updated as to taking the entire update which could go up to 2.5 GB sometimes. Doing this complete update sometimes fails. I had a number of SDK updates once I upgraded to Android Studio 3.0 and was getting the above error since all packages had not been updated. Once I updated all packages the above error was gone.

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

How to get the list of all printers in computer

If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.

using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;

    public class Miclass
    {
        private void AllViews()
        {
            List<PortClass> ports = new List<PortClass>();
            List<Printersclass> Printersfor = new List<Printersclass>();
            string[] portnames = SerialPort.GetPortNames();
            /*PORTS*/
            for (int i = 0; i < portnames.Count(); i++)
            {
                ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
            }
            /*PRINTER*/
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
            }
        }
    }
    public class PortClass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }
    public class Printersclass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }

Is there a way to set background-image as a base64 encoded image?

This is the correct way to make a pure call. No CSS.

<div style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAFCAYAAABW1IzHAAAAHklEQVQokWNgGPaAkZHxPyMj439sYrSQo51PBgsAALa0ECF30JSdAAAAAElFTkSuQmCC)repeat-x center;'></div>

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

Tomcat: LifecycleException when deploying

I got stuck and problem solved Don't use the path that is "Map Network Drive", but use the \server\folder structure instead

Do you get charged for a 'stopped' instance on EC2?

This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.

If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.

If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.

Select2() is not a function

Put config.assets.debug = false in config/environments/development.rb.

Open soft keyboard programmatically

In your manifest file, try adding the following to the <activity> that you want to show the keyboard when the activity starts:

android:windowSoftInputMode="stateVisible"

This should cause the keyboard to become visible when the activity starts.

For more options, checkout the documentation.

Complex nesting of partials and templates

You may checkout this library for the same purpose also:

http://angular-route-segment.com

It looks like what you are looking for, and it is much simpler to use than ui-router. From the demo site:

JS:

$routeSegmentProvider.

when('/section1',          's1.home').
when('/section1/:id',      's1.itemInfo.overview').
when('/section2',          's2').

segment('s1', {
    templateUrl: 'templates/section1.html',
    controller: MainCtrl}).
within().
    segment('home', {
        templateUrl: 'templates/section1/home.html'}).
    segment('itemInfo', {
        templateUrl: 'templates/section1/item.html',
        controller: Section1ItemCtrl,
        dependencies: ['id']}).
    within().
        segment('overview', {
            templateUrl: 'templates/section1/item/overview.html'}).

Top-level HTML:

<ul>
    <li ng-class="{active: $routeSegment.startsWith('s1')}">
        <a href="/section1">Section 1</a>
    </li>
    <li ng-class="{active: $routeSegment.startsWith('s2')}">
        <a href="/section2">Section 2</a>
    </li>
</ul>
<div id="contents" app-view-segment="0"></div>

Nested HTML:

<h4>Section 1</h4>
Section 1 contents.
<div app-view-segment="1"></div>

Get Time from Getdate()

To get the format you want:

SELECT (substring(CONVERT(VARCHAR,GETDATE(),22),10,8) + ' ' + SUBSTRING(CONVERT(VARCHAR,getdate(),22), 19,2))

Why are you pulling this from sql?

Flex-box: Align last row to grid

Add a ::after which autofills the space. No need to pollute your HTML. Here is a codepen showing it: http://codepen.io/DanAndreasson/pen/ZQXLXj

.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.grid::after {
  content: "";
  flex: auto;
}

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How can I test an AngularJS service from the console?

First of all, a modified version of your service.

a )

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

app.factory('ExampleService',function(){
    return {
        f1 : function(world){
            return 'Hello' + world;
        }
    };
});

This returns an object, nothing to new here.

Now the way to get this from the console is

b )

var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");

c )

One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

app.factory('ExampleService',function(){
        return function(){
            this.f1 = function(world){
                return 'Hello' + world;
            }
        };
    });

This returns an ExampleService constructor which you will next have to do a 'new' on.

Or alternatively,

app.service('ExampleService',function(){
            this.f1 = function(world){
                return 'Hello' + world;
            };
    });

This returns new ExampleService() on injection.

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

For outlook use following setting that is not giving error to me

SMTP server name smtp-mail.outlook.com

SMTP port 587

Replace input type=file by an image

Actually it can be done in pure css and it's pretty easy...

HTML Code

<label class="filebutton">
Browse For File!
<span><input type="file" id="myfile" name="myfile"></span>
</label>

CSS Styles

label.filebutton {
    width:120px;
    height:40px;
    overflow:hidden;
    position:relative;
    background-color:#ccc;
}

label span input {
    z-index: 999;
    line-height: 0;
    font-size: 50px;
    position: absolute;
    top: -2px;
    left: -700px;
    opacity: 0;
    filter: alpha(opacity = 0);
    -ms-filter: "alpha(opacity=0)";
    cursor: pointer;
    _cursor: hand;
    margin: 0;
    padding:0;
}

The idea is to position the input absolutely inside your label. set the font size of the input to something large, which will increase the size of the "browse" button. It then takes some trial and error using the negative left / top properties to position the input browse button behind your label.

When positioning the button, set the alpha to 1. When you've finished set it back to 0 (so you can see what you're doing!)

Make sure you test across browsers because they'll all render the input button a slightly different size.

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

How do I auto-hide placeholder text upon focus using css or jquery?

Using SCSS along with http://bourbon.io/, this solution is simple, elegant, and works on all web browsers:

input:focus {
  @include placeholder() {
    color: transparent;
  }
}

Use Bourbon ! It's good for you !

git clone through ssh

Easy way to do this issue
try this.

Step 1:

ls -al ~/.ssh

enter image description here

Step 2:

ssh-keygen 

(using enter key for default value) enter image description here Step 3: To setup config file

vim /c/Users/Willie/.ssh/config

Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa

Step 4:

git clone [email protected]:<username>/test2.git

enter image description here

Step 5:
When you finished Step 4
1.the test2.git file will be download done
2.you will get the new file(known_hosts) in the ~/.ssh
enter image description here

PS: I create the id_rsa and id_rsa.ub by meself and I deliver it to the Gitlab server. using both keys to any client-sides(windows and Linux).

javac is not recognized as an internal or external command, operable program or batch file

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:\Program Files\Java\jdkxxxx\bin\
  2. Start-menu search for "environment variable" to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:\WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\craig\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPower
Shell\v1.0\;C:\ProgramData\Microsoft\Windows\Start Menu\Programs;C:\Users\craig\AppData\
Roaming\Microsoft\Windows\Start Menu\Programs;C:\msys64\usr\bin;C:\msys64\mingw64\bin;C:\
msys64\mingw32\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Yarn\bin\;C:\Users\
craig\AppData\Local\Yarn\bin;C:\Program Files\Java\jdk-10.0.2\bin;C:\ProgramFiles\Git\cmd;
C:\Program Files\Oracle\VirtualBox;C:\Program Files\7-Zip\;C:\Program Files\PuTTY\;C:\
Program Files\launch4j;C:\Program Files (x86)\NSIS\Bin;C:\Program Files (x86)\Common Files
\Adobe\AGL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\iCLS Client\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
(x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\iCLS
Client\;C:\Users\craig\AppData\Local\Microsoft\WindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package's name includes the words "Development Kit" in it.

Don't use set

(If you weren't planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:\>:: DON'T DO THIS
C:\>set PATH=C:\Program Files\Java\jdk1.7.0_09\bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:\Program Files\Java\jdk1.7.0_09\bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:\>:: DON'T DO THIS EITHER
C:\>set PATH=C:\Program Files\Java\<enter the correct Java folder here>\bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle's installer places versions of Java under C:\Program Files\Java\ (or C:\Program Files (x86)\Java\). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:\Program Files\Java\jdkxxxx\bin\

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won't get in your way; C:\Java\ is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for "environment variable"
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control Panel\System and Security\System » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you're at it, you may as well uninstall old Java versions, too. And remember that you don't need to have both a JDK and a JRE.

If you have C:\ProgramData\Oracle\Java\javapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn't matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn't much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you're at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:\Program Files\Java\jdkxxxx\.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd's environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

Editing the git commit message in GitHub

No, this is not directly possible. The hash for every Git commit is also calculated based on the commit message. When you change the commit message, you change the commit hash. If you want to push that commit, you have to force that push (git push -f). But if already someone pulled your old commit and started a work based on that commit, he would have to rebase his work onto your new commit.

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

What does git rev-parse do?

Just to elaborate on the etymology of the command name rev-parse, Git consistently uses the term rev in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list for example prints a list of 40-char commit hashes for a branch or whatever.

In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.

I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)

Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

How do I get an animated gif to work in WPF?

I have try all the way above, but each one has their shortness, and thanks to all you, I work out my own GifImage:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Controls;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using System.IO;
    using System.Windows.Threading;

    namespace IEXM.Components
    {
    public class GifImage : Image
    {
            #region gif Source, such as "/IEXM;component/Images/Expression/f020.gif"
            public string GifSource
            {
                    get { return (string)GetValue(GifSourceProperty); }
                    set { SetValue(GifSourceProperty, value); }
            }

            public static readonly DependencyProperty GifSourceProperty =
                    DependencyProperty.Register("GifSource", typeof(string),
                    typeof(GifImage), new UIPropertyMetadata(null, GifSourcePropertyChanged));

            private static void GifSourcePropertyChanged(DependencyObject sender,
                    DependencyPropertyChangedEventArgs e)
            {
                    (sender as GifImage).Initialize();
            }
            #endregion

            #region control the animate
            /// <summary>
            /// Defines whether the animation starts on it's own
            /// </summary>
            public bool IsAutoStart
            {
                    get { return (bool)GetValue(AutoStartProperty); }
                    set { SetValue(AutoStartProperty, value); }
            }

            public static readonly DependencyProperty AutoStartProperty =
                    DependencyProperty.Register("IsAutoStart", typeof(bool),
                    typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));

            private static void AutoStartPropertyChanged(DependencyObject sender,
                    DependencyPropertyChangedEventArgs e)
            {
                    if ((bool)e.NewValue)
                            (sender as GifImage).StartAnimation();
                    else
                            (sender as GifImage).StopAnimation();
            }
            #endregion

            private bool _isInitialized = false;
            private System.Drawing.Bitmap _bitmap;
            private BitmapSource _source;

            [System.Runtime.InteropServices.DllImport("gdi32.dll")]
            public static extern bool DeleteObject(IntPtr hObject);

            private BitmapSource GetSource()
            {
                    if (_bitmap == null)
                    {
                            _bitmap = new System.Drawing.Bitmap(Application.GetResourceStream(
                                     new Uri(GifSource, UriKind.RelativeOrAbsolute)).Stream);
                    }

                    IntPtr handle = IntPtr.Zero;
                    handle = _bitmap.GetHbitmap();

                    BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                            handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    DeleteObject(handle);
                    return bs;
            }

            private void Initialize()
            {
            //        Console.WriteLine("Init: " + GifSource);
                    if (GifSource != null)
                            Source = GetSource();
                    _isInitialized = true;
            }

            private void FrameUpdatedCallback()
            {
                    System.Drawing.ImageAnimator.UpdateFrames();

                    if (_source != null)
                    {
                            _source.Freeze();
                    }

               _source = GetSource();

              //  Console.WriteLine("Working: " + GifSource);

                    Source = _source;
                    InvalidateVisual();
            }

            private void OnFrameChanged(object sender, EventArgs e)
            {
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));
            }

            /// <summary>
            /// Starts the animation
            /// </summary>
            public void StartAnimation()
            {
                    if (!_isInitialized)
                            this.Initialize();


             //   Console.WriteLine("Start: " + GifSource);

                    System.Drawing.ImageAnimator.Animate(_bitmap, OnFrameChanged);
            }

            /// <summary>
            /// Stops the animation
            /// </summary>
            public void StopAnimation()
            {
                    _isInitialized = false;
                    if (_bitmap != null)
                    {
                            System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);
                            _bitmap.Dispose();
                            _bitmap = null;
                    }
                    _source = null;
                    Initialize();
                    GC.Collect();
                    GC.WaitForFullGCComplete();

             //   Console.WriteLine("Stop: " + GifSource);
            }

            public void Dispose()
            {
                    _isInitialized = false;
                    if (_bitmap != null)
                    {
                            System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);
                            _bitmap.Dispose();
                            _bitmap = null;
                    }
                    _source = null;
                    GC.Collect();
                    GC.WaitForFullGCComplete();
               // Console.WriteLine("Dispose: " + GifSource);
            }
    }
}

Usage:

<localComponents:GifImage x:Name="gifImage" IsAutoStart="True" GifSource="{Binding Path=value}" />

As it would not cause memory leak and it animated the gif image own time line, you can try it.

How to output git log with the first line only?

Better and easier git log by making an alias. Paste the code below to terminal just once for one session. Paste the code to zshrc or bash profile to make it persistant.

git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Output

git lg

Output changed lines

git lg -p

Alternatively (recommended)
Paste this code to global .gitconfig file

[alias]
  lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

Further Reading.
https://coderwall.com/p/euwpig/a-better-git-log
Advanced Reading.
http://durdn.com/blog/2012/11/22/must-have-git-aliases-advanced-examples/

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

pandas: find percentile stats of a given column

I figured out below would work:

my_df.dropna().quantile([0.0, .9])

Remove a specific string from an array of string

It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:

      String[] n = new String[]{"google","microsoft","apple"};
      final List<String> list =  new ArrayList<String>();
      Collections.addAll(list, n); 
      list.remove("apple");
      n = list.toArray(new String[list.size()]);

I not recommend the following but if you worry about performance:

      String[] n = new String[]{"google","microsoft","apple"};
      final String[] n2 = new String[2]; 
      System.arraycopy(n, 0, n2, 0, n2.length);
      for (int i = 0, j = 0; i < n.length; i++)
      {
        if (!n[i].equals("apple"))
        {
          n2[j] = n[i];
          j++;
        }      
      }

I not recommend it because the code is a lot more difficult to read and maintain.

Simplest way to detect keypresses in javascript

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
    e = e || window.event;
    // use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
    e = e || window.event;
    // use e.keyCode
});

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    } else {
        element["on" + eventName] = callback;
    }
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

With jQuery:

$(document).on("keypress", function (e) {
    // use e.which
});

Reference:

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

How do I wrap text in a pre tag?

The Best Cross Browser Way worked for me to get line breaks and shows exact code or text: (chrome, internet explorer, Firefox)

CSS:

xmp{ white-space:pre-wrap; word-wrap:break-word; }

HTML:

<xmp> your text or code </xmp>

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Convert blob URL to normal URL

As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.

However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.

<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>

Insert this to the page containing blob url and click the button, you get the content.

Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

Calculate a MD5 hash from a string

Depends entirely on what you are trying to achieve. Technically, you could just take the first 12 characters from the result of the MD5 hash, but the specification of MD5 is to generate a 32 char one.

Reducing the size of the hash reduces the security, and increases the chance of collisions and the system being broken.

Perhaps if you let us know more about what you are trying to achieve we may be able to assist more.

Get the item doubleclick event of listview

for me, I do double click of ListView in this code section .

    this.listView.Activation = ItemActivation.TwoClick;

    this.listView.ItemActivate += ListView1_ItemActivate;

ItemActivate specify how user activate with items

When user do double click, ListView1_ItemActivate will be trigger. Property of ListView ItemActivate refers to access the collection of items selected.

    private void ListView1_ItemActivate(Object sender, EventArgs e)
    {

        foreach (ListViewItem item in listView.SelectedItems)
           //do something

    }

it works for me.

Namespace not recognized (even though it is there)

I have a similar problem with references not being recognized in VS2010 and the answers herein were not able to correct it.

The problem in my solution was related to the extension of the path where the project referenced was located. As I am working with SVN, I made a branch of a repository to do some testing and that branch increased two levels in path structure, so the path became too long to be usable in windows. This did not throw any error but did not recognize the namespace of the project reference. When I correct the location of the project to have a smaller path everything went fine.

Disable clipboard prompt in Excel VBA on workbook close

I have hit this problem in the past - from the look of it if you don't actually need the clipboard at the point that you exit, so you can use the same simple solution I had. Just clear the clipboard. :)

ActiveCell.Copy

How to Make A Chevron Arrow Using CSS?

This can be solved much easier than the other suggestions.

Simply draw a square and apply a border property to just 2 joining sides.

Then rotate the square according to the direction you want the arrow to point, for exaple: transform: rotate(<your degree here>)

_x000D_
_x000D_
.triangle {_x000D_
    border-right: 10px solid; _x000D_
    border-bottom: 10px solid;_x000D_
    height: 30px;_x000D_
    width: 30px;_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

How to write asynchronous functions for Node.js

Just passing by callbacks is not enough. You have to use settimer for example, to make function async.

Examples: Not async functions:

function a() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };
  b();
};

function b() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };    
  c();
};

function c() {
  for(i=0; i<10000000; i++) {
  };
  console.log("async finished!");
};

a();
console.log("This should be good");

If you will run above example, This should be good, will have to wait untill those functions will finish to work.

Pseudo multithread (async) functions:

function a() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };
    b();
  }, 0);
};

function b() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };  
    c();
  }, 0);
};

function c() {
  setTimeout ( function() {
    for(i=0; i<10000000; i++) {
    };
    console.log("async finished!");
  }, 0);
};

a();
console.log("This should be good");

This one will be trully async. This should be good will be writen before async finished.

Easiest way to change font and font size

Use this one to change only font size not the name of the font

label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);

Git Pull While Ignoring Local Changes?

If you mean you want the pull to overwrite local changes, doing the merge as if the working tree were clean, well, clean the working tree:

git reset --hard
git pull

If there are untracked local files you could use git clean to remove them. Use git clean -f to remove untracked files, -df to remove untracked files and directories, and -xdf to remove untracked or ignored files or directories.

If on the other hand you want to keep the local modifications somehow, you'd use stash to hide them away before pulling, then reapply them afterwards:

git stash
git pull
git stash pop

I don't think it makes any sense to literally ignore the changes, though - half of pull is merge, and it needs to merge the committed versions of content with the versions it fetched.

Typescript: React event types

I have the following in a types.ts file for html input, select, and textarea:

export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>

Then import them:

import { InputChangeEventHandler } from '../types'

Then use them:


const updateName: InputChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}

Then apply the functions on your markup (replacing ... with other necessary props):

<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
  // ...
</select>

The Eclipse executable launcher was unable to locate its companion launcher jar windows

My issue was much simpler. I had created a shortcut to launch the eclipse executable by dragging it from the folder to the screen. Clicking on the created shortcut icon gave the above error.

Issue: the executable was getting launched from the desktop location instead of the eclipse directory where it had been unzipped.

Solution: Create a new shortcut by right-clicking in the desktop area and providing the target executable from the browse window. This creates the shortcut properly and launches the executable from the right home directory.

Iterate over the lines of a string

Here are three possibilities:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

Measuring gives:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

But the split-based approach still rules.

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

at least, it's a bit less verbose. The need to strip trailing \ns unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('\n'), stri)

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

Compare two List<T> objects for equality, ignoring order

This worked for me:
If you are comparing two lists of objects depend upon single entity like ID, and you want a third list which matches that condition, then you can do the following:

var list3 = List1.Where(n => !List2.select(n1 => n1.Id).Contains(n.Id));

Refer: MSDN - C# Compare Two lists of objects

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

If you are using Spring 3, the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView showResults(final HttpServletRequest request, Principal principal) {

     final String currentUser = principal.getName();

 }

Select columns in PySpark dataframe

First two columns and 5 rows

 df.select(df.columns[:2]).take(5)

How to horizontally center an element

<center>

I am spoiled with the most simple center known?

</center>

How to save to local storage using Flutter?

A late answer but I hope it will help anyone visiting here later too..

I will provide categories to save and their respective best methods...

  1. Shared Preferences Use this when storing simple values on storage e.g Color theme, app language, last scroll position(in reading apps).. these are simple settings that you would want to persist when the app restarts.. You could, however, use this to store large things(Lists, Maps, Images) but that would require serialization and deserialization.. To learn more on this deserialization and serialization go here.
  2. Files This helps a lot when you have data that is defined more by you for example log files, image files and maybe you want to export csv files.. I heard that this type of persistence can be washed by storage cleaners once disk runs out of space.. Am not sure as i have never seen it.. This also can store almost anything but with the help of serialization and deserialization..
  3. Saving to a database This is enormously helpful in data which is a bit complex. And I think this doesn't get washed up by disc cleaners as it is stored in AppData(for android).. In this, your data is stored in an SQLite database. Its plugin is SQFLite. Kinds of data that you might wanna put in here are like everything that can be represented by a database.

Error pushing to GitHub - insufficient permission for adding an object to repository database

I was getting this error because every time a user push some content, the group of the file changed to the user. And then if some other user tried to push into the repository, it caused permission error and the push was rejected. So one need to ask your sysadmin to change the settings of the repository so that group of any file in the repository is not changed for any push by any user.

To avoid such problem, please ensure that when you initialize your git repository, use the command "git init --shared=group".

How to replace all spaces in a string

I came across this as well, for me this has worked (covers most browsers):

myString.replace(/[\s\uFEFF\xA0]/g, ';');

Inspired by this trim polyfill after hitting some bumps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill

How to check a string against null in java?

Of course user351809, stringname.equalsignorecase(null) will throw NullPointerException.
See, you have a string object stringname, which follows 2 possible conditions:-

  1. stringname has a some non-null string value (say "computer"):
    Your code will work fine as it takes the form
    "computer".equalsignorecase(null)
    and you get the expected response as false.
  2. stringname has a null value:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, null is not an object that can execute the equalsignorecase() method.

Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null

What is the best algorithm for overriding GetHashCode?

Here is my simplistic approach. I am using the classic builder pattern for this. It is typesafe (no boxing/unboxing) and also compatbile with .NET 2.0 (no extension methods etc.).

It is used like this:

public override int GetHashCode()
{
    HashBuilder b = new HashBuilder();
    b.AddItems(this.member1, this.member2, this.member3);
    return b.Result;
} 

And here is the acutal builder class:

internal class HashBuilder
{
    private const int Prime1 = 17;
    private const int Prime2 = 23;
    private int result = Prime1;

    public HashBuilder()
    {
    }

    public HashBuilder(int startHash)
    {
        this.result = startHash;
    }

    public int Result
    {
        get
        {
            return this.result;
        }
    }

    public void AddItem<T>(T item)
    {
        unchecked
        {
            this.result = this.result * Prime2 + item.GetHashCode();
        }
    }

    public void AddItems<T1, T2>(T1 item1, T2 item2)
    {
        this.AddItem(item1);
        this.AddItem(item2);
    }

    public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
    }

    public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, 
        T4 item4)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
    }

    public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, 
        T4 item4, T5 item5)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
        this.AddItem(item5);
    }        

    public void AddItems<T>(params T[] items)
    {
        foreach (T item in items)
        {
            this.AddItem(item);
        }
    }
}

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Converting newline formatting from Mac to Windows

This is an improved version of Anne's answer -- if you use perl, you can do the edit on the file 'in-place' rather than generating a new file:

perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert  # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g'   file-to-convert  # Convert to UNIX

Pandas index column title or name

df.index.name should do the trick.

Python has a dir function that let's you query object attributes. dir(df.index) was helpful here.

Class constructor type in typescript?

Solution from typescript interfaces reference:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {
    new (): Animal;
}

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'

    constructor(AnimalClass: AnimalConstructor) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

console.log showing contents of array object

It's simple to print an object to console in Javascript. Just use the following syntax:

console.log( object );

or

console.log('object: %O', object );

A relatively unknown method is following which prints an object or array to the console as table:

console.table( object );

I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.

Make a UIButton programmatically in Swift

In iOS 12, Swift 4.2 & XCode 10.1

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//        button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties like this also
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

How to get the index of an element in an IEnumerable?

The way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:

 var index = haystack.ToList().IndexOf(needle);

It's a bit clunky, but it does the job and is fairly concise.

Dynamically add item to jQuery Select2 control that uses AJAX

This provided a simple solution: Set data in Select2 after insert with AJAX

$("#select2").select2('data', {id: newID, text: newText});      

Runtime vs. Compile time

Following from previous similar answer of question What is the difference between run-time error and compiler error?

Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int as Int.

Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn't exist, will result in a runtime error.

Read more about all programming errors here

How to make a div fill a remaining horizontal space?

Use display:flex

<div style="width:500px; display:flex">
   <div style="width:150px; height:30px; background:red">fixed width</div>

   <div style="width:100%; height:30px; background:green">remaining</div>
</div>

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

How to find the type of an object in Go?

You can use: interface{}..(type) as in this playground

package main
import "fmt"
func main(){
    types := []interface{} {"a",6,6.0,true}
    for _,v := range types{
        fmt.Printf("%T\n",v)
        switch v.(type) {
        case int:
           fmt.Printf("Twice %v is %v\n", v, v.(int) * 2)
        case string:
           fmt.Printf("%q is %v bytes long\n", v, len(v.(string)))
       default:
          fmt.Printf("I don't know about type %T!\n", v)
      }
    }
}

GridView sorting: SortDirection always Ascending

Old string, but maybe my answer will help somebody.

First get your SqlDataSource as a DataView:

Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As DataGridSortCommandEventArgs) Handles grid1.SortCommand
    Dim dataView As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    dataView.Sort = e.SortExpression + dataView.FieldSortDirection(Session, e.SortExpression)

    grid1.DataSourceID = Nothing
    grid1.DataSource = dataView
    grid1.DataBind()

End Sub

Then use an extension method for the sort (kind of a cheep shot, but a good start):

public static class DataViewExtensions
{
    public static string FieldSortDirection(this DataView dataView, HttpSessionState session, string sortExpression)
    {
        const string SORT_DIRECTION = "SortDirection";
        var identifier = SORT_DIRECTION + sortExpression;

        if (session[identifier] != null)
        {
            if ((string) session[identifier] == " ASC")
                session[identifier] = " DESC";
            else if ((string) session[identifier] == " DESC")
                session[identifier] = " ASC";
        }
        else
            session[identifier] = " ASC";

        return (string) session[identifier];
    }
}

convert NSDictionary to NSString

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222

Get city name using geolocation

You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {
            console.log(position.coords.latitude)
            console.log(position.coords.longitude)

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                console.log(location)
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

and to display this data on the page using jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>

    <p>Country: <span id="country"></span></p>
    <p>State: <span id="state"></span></p>
    <p>City: <span id="city"></span></p>
    <p>Address: <span id="address"></span></p>

    <p>Latitude: <span id="latitude"></span></p>
    <p>Longitude: <span id="longitude"></span></p>

    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

Is there a Subversion command to reset the working copy?

Delete the working copy from the OS and check it out again is simplest, but obviously not a single command.

How to write specific CSS for mozilla, chrome and IE

You could use php to echo the browser name as a body class, e.g.

<body class="mozilla">

Then, your conditional CSS would look like

.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}

How to input matrix (2D list) in Python?

a = []
b = []

m=input("enter no of rows: ")
n=input("enter no of coloumns: ")

for i in range(n):
     a = []
     for j in range(m):
         a.append(input())
     b.append(a)

Input : 1 2 3 4 5 6 7 8 9

Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]

This view is not constrained

Right Click in then designing part on that component in which you got error and follow these steps:

  • [for ex. if error occur in Plain Text]

[1]

Plain Text Constraint Layout > Infer Constraints:

finally error has gone

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

I am actually quite surprised that this solution has not been presented yet, and I feel like it is the easiest solution.

Go to GitHub, find the version of the brewfile that matches the version of icu4c that you need and get the raw version of the file (follow the links above and click View File then Raw).

Then just have brew reinstall from that url.

For example, version 62.1:

brew reinstall https://raw.githubusercontent.com/Homebrew/homebrew-core/575eb4bbef683551e19f329f60456b13a558132f/Formula/icu4c.rb

For example, version 64.2:

brew reinstall https://raw.githubusercontent.com/Homebrew/homebrew-core/a806a621ed3722fb580a58000fb274a2f2d86a6d/Formula/icu4c.rb

PHP array printing using a loop

If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Just set these in php.ini:

upload_max_filesize = 1000M;
post_max_size = 1000M;

How to redirect to an external URL in Angular2?

You can use this-> window.location.href = '...';

This would change the page to whatever you want..

Which is faster: multiple single INSERTs or one multiple-row INSERT?

A major factor will be whether you're using a transactional engine and whether you have autocommit on.

Autocommit is on by default and you probably want to leave it on; therefore, each insert that you do does its own transaction. This means that if you do one insert per row, you're going to be committing a transaction for each row.

Assuming a single thread, that means that the server needs to sync some data to disc for EVERY ROW. It needs to wait for the data to reach a persistent storage location (hopefully the battery-backed ram in your RAID controller). This is inherently rather slow and will probably become the limiting factor in these cases.

I'm of course assuming that you're using a transactional engine (usually innodb) AND that you haven't tweaked the settings to reduce durability.

I'm also assuming that you're using a single thread to do these inserts. Using multiple threads muddies things a bit because some versions of MySQL have working group-commit in innodb - this means that multiple threads doing their own commits can share a single write to the transaction log, which is good because it means fewer syncs to persistent storage.

On the other hand, the upshot is, that you REALLY WANT TO USE multi-row inserts.

There is a limit over which it gets counter-productive, but in most cases it's at least 10,000 rows. So if you batch them up to 1,000 rows, you're probably safe.

If you're using MyISAM, there's a whole other load of things, but I'll not bore you with those. Peace.

Closing a Userform with Unload Me doesn't work

Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.

I hope its helps

Angular update object in object array

I have created this Plunker based on your example that updates the object equal to newItem.id

Here's the snippet of my functions:

showUpdatedItem(newItem){
    let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);

    let index = this.itemArray.items.indexOf(updateItem);


    this.itemArray.items[index] = newItem;

  }

  findIndexToUpdate(newItem) { 
        return newItem.id === this;
  }

Hope this helps.

Response Content type as CSV

For C# MVC 4.5 you need to do like this:

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".csv\"");
Response.Write(dataNeedToPrint);
Response.End();
return new EmptyResult();  //this line is important else it will not work.

How to join entries in a set into one string?

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
        set_size = len(set_to_convert)
        if not set_size:
            return ""
        elif set_size == 1:
            (element,) = set_to_convert
            return str(element)
        else:
            return separator.join(map(str, set_to_convert))

'dependencies.dependency.version' is missing error, but version is managed in parent

I had the same problem and I rename the "repository" folder on ".m2" (something like repositoryBkp the name is not important is just in case something goes wrong) and create a new "repository" folder, then I re run maven and all the project compile successfully

How to remove entry from $PATH on mac

Close the terminal(End the current session). Open it again.

Browser: Identifier X has already been declared

Remember that window is the global namespace. These two lines attempt to declare the same variable:

window.APP = { ... }
const APP = window.APP

The second definition is not allowed in strict mode (enabled with 'use strict' at the top of your file).

To fix the problem, simply remove the const APP = declaration. The variable will still be accessible, as it belongs to the global namespace.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

I couldn't properly follow the other answers, here's more of a dummies guide...

You can do this either way round to go trunk -> branch or branch -> trunk. I always first do trunk -> branch fix any conflicts there and then merge branch -> trunk.

Merge trunk into a branch / tag

  1. Checkout the branch / tag
  2. Right-click on the root of the branch | Tortoise SVN | Merge ...
  3. Merge Type: Merge a range of revisions | Click 'Next' enter image description here
  4. Merge revision range: Select the URL of the trunk directory that you copied to the branch / tag. Enter the revisions to merge or leave the field empty to merge all revisions | click 'Next' enter image description here
  5. Merge options: I just left these as default | click 'Merge' enter image description here
  6. This will merge the revisions into the checked out branch / tag
  7. Then commit the merged changes to the branch / tag

Output data with no column headings using PowerShell

The -expandproperty does not work with more than 1 object. You can use this one :

Select-Object Name | ForEach-Object {$_.Name}

If there is more than one value then :

Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}

C++ Pass A String

You can write your function to take a const std::string&:

void print(const std::string& input)
{
    cout << input << endl;
}

or a const char*:

void print(const char* input)
{
    cout << input << endl;
}

Both ways allow you to call it like this:

print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made

The second version does require c_str() to be called for std::strings:

print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made

How to create javascript delay function

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

Hide/Show components in react native

i am just using below method to hide or view a button. hope it will help you. just updating status and adding hide css is enough for me

constructor(props) {
   super(props);
      this.state = {
      visibleStatus: false
   };
}
updateStatusOfVisibility () {
   this.setStatus({
      visibleStatus: true
   });
}
hideCancel() {
   this.setStatus({visibleStatus: false});
}

render(){
   return(
    <View>
        <TextInput
            onFocus={this.showCancel()}
            onChangeText={(text) => {this.doSearch({input: text}); this.updateStatusOfVisibility()}} />

         <TouchableHighlight style={this.state.visibleStatus ? null : { display: "none" }}
             onPress={this.hideCancel()}>
            <View>
                <Text style={styles.cancelButtonText}>Cancel</Text>
            </View>
        </TouchableHighlight>
     </View>)
}

Converting EditText to int? (Android)

You can use like this

 EditText dollar=(EditText) findViewById(R.id.money);
 int rupees=Integer.parseInt( dollar.getText().toString());

how to access parent window object using jquery?

If you are in a po-up and you want to access the opening window, use window.opener. The easiest would be if you could load JQuery in the parent window as well:

window.opener.$("#serverMsg").html // this uses JQuery in the parent window

or you could use plain old document.getElementById to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):

element = window.opener.document.getElementById("serverMsg");
element = $(element);

If you are in an iframe or frameset and want to access the parent frame, use window.parent instead of window.opener.

According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.

How to change onClick handler dynamically?

I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:

document.getElementById("foo").onclick = function (event){alert('foo');};

or in jQuery:

$('#foo').click(function(event) { alert('foo'); }

How to store printStackTrace into a string

call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

nil? can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:

return my_string.nil? || my_string.empty?

git: fatal: I don't handle protocol '??http'

Use backspace to delete whatever there is between git clone and the url and then use spacebar to add a clean space between them. Simple as that.

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

My favorite no-conflict-friendly construct:

jQuery(function($) {
  // ...
});

Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

Or as we say in coffeescript:

jQuery ($) ->
  # code here

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

SQL Server loop - how do I loop through a set of records

By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;

SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')

OPEN @BusinessCursor;
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msg = '{
              "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
              "Customer": {
                "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
              }
            }|'
        print @msg
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END

HashMap - getting First Key value

Remember that the insertion order isn't respected in a map generally speaking. Try this :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1 .

How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

Difference between onLoad and ng-init in angular

Works for me.

<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.

The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.

So the solution is to recompile Projectname1.lib with VS2012.

What is the most efficient way to get first and last line of a text file?

Getting the first line is trivially easy. For the last line, presuming you know an approximate upper bound on the line length, os.lseek some amount from SEEK_END find the second to last line ending and then readline() the last line.

Best cross-browser method to capture CTRL+S with JQuery?

$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});

Key codes can differ between browsers, so you may need to check for more than just 115.

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

MySQL JOIN with LIMIT 1 on joined table

Assuming you want product with MIN()imial value in sort column, it would look something like this.

SELECT 
  c.id, c.title, p.id AS product_id, p.title
FROM 
  categories AS c
INNER JOIN (
  SELECT
    p.id, p.category_id, p.title
  FROM
    products AS p
  CROSS JOIN (
    SELECT p.category_id, MIN(sort) AS sort
    FROM products
    GROUP BY category_id
  ) AS sq USING (category_id)
) AS p ON c.id = p.category_id

How to get the containing form of an input?

Every input has a form property which points to the form the input belongs to, so simply:

function doSomething(element) {
  var form = element.form;
}