Programs & Examples On #Magickwand

Run a batch file with Windows task scheduler

Try run the task with high privileges.

put a \ at the end of path in "start in folder" such as c:\temp\

I do not know why , but this works for me sometimes.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Refreshing page on click of a button

<button type="button" onClick="refreshPage()">Close</button>

<script>
function refreshPage(){
    window.location.reload();
} 
</script>

or

<button type="button" onClick="window.location.reload();">Close</button>

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Another way to avoid the error is to use the cast like this:

let secondValue: string = (<any>someObject)[key]; (Note the parenthesis)

The only problem is that this isn't type-safe anymore, as you are casting to any. But you can always cast back to the correct type.

ps: I'm using typescript 1.7, not sure about previous versions.

How can I see what has changed in a file before committing to git?

For some paths, the other answers will return an error of the form fatal: ambiguous argument.

In these cases diff needs a separator to differentiate filename arguments from commit strings. For example to answer the question asked you'd need to execute:

$ git diff --cached -- <path-to-file>

This will display the changes between the modified files and the last commit.

On the other hand:

git diff --cached HEAD~3 <path-to-file>

will display the changes between the local version of and the version three commits ago.

Merge/flatten an array of arrays

Just to add to the great solutions. I used recursion to solve this.

            const flattenArray = () => {
                let result = [];
                return function flatten(arr) {
                    for (let i = 0; i < arr.length; i++) {
                        if (!Array.isArray(arr[i])) {
                            result.push(arr[i]);
                        } else {
                            flatten(arr[i])
                        }
                    }
                    return result;
                }
            }

Test results: https://codepen.io/ashermike/pen/mKZrWK

What does functools.wraps do?

When you use a decorator, you're replacing one function with another. In other words, if you have a decorator

def logged(func):
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

then when you say

@logged
def f(x):
   """does some math"""
   return x + x * x

it's exactly the same as saying

def f(x):
    """does some math"""
    return x + x * x
f = logged(f)

and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say

print(f.__name__)

it will print with_logging because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x; instead it'll be listed as taking *args and **kwargs because that's what with_logging takes.

If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator, the following code does the correct thing:

from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

print(f.__name__)  # prints 'f'
print(f.__doc__)   # prints 'does some math'

How do I fix the multiple-step OLE DB operation errors in SSIS?

I had a similar issue when i was transferring data from an old database to a new database, I got the error above. I then ran the following script

SELECT * FROM [source].INFORMATION_SCHEMA.COLUMNS src INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst ON dst.COLUMN_NAME = src.COLUMN_NAME WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH

and found that my columns where slightly different in terms of character sizes etc. I then tried to alter the table to the new table structure which did not work. I then transferred the data from the old database into Excel and imported the data from excel to the new DB which worked 100%.

The SQL OVER() clause - when and why is it useful?

The OVER clause is powerful in that you can have aggregates over different ranges ("windowing"), whether you use a GROUP BY or not

Example: get count per SalesOrderID and count of all

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) AS 'Count'
    ,COUNT(*) OVER () AS 'CountAll'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)
GROUP BY
     SalesOrderID, ProductID, OrderQty

Get different COUNTs, no GROUP BY

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'CountQtyPerOrder'
    ,COUNT(OrderQty) OVER(PARTITION BY ProductID) AS 'CountQtyPerProduct',
    ,COUNT(*) OVER () AS 'CountAllAgain'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)

What is the meaning of <> in mysql query?

<> is standard ANSI SQL and stands for not equal or !=.

Convert List<T> to ObservableCollection<T> in WP7

Use this:

List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);

Filter object properties by key in ES6

A simpler solution without using filter can be achieved with Object.entries() instead of Object.keys()

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

const filtered = Object.entries(raw).reduce((acc,elm)=>{
  const [k,v] = elm
  if (allowed.includes(k)) {
    acc[k] = v 
  }
  return acc
},{})

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

In Mac OS -moz-appearance: window; will remove the arrow accrding to the MDN docs here: https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance. Tested on Firefox 13 on Mac OS X 10.8.2. Also see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c21.

Iterate through a C++ Vector using a 'for' loop

I was surprised nobody mentioned that iterating through an array with an integer index makes it easy for you to write faulty code by subscripting an array with the wrong index. For example, if you have nested loops using i and j as indices, you might incorrectly subscript an array with j rather than i and thus introduce a fault into the program.

In contrast, the other forms listed here, namely the range based for loop, and iterators, are a lot less error prone. The language's semantics and the compiler's type checking mechanism will prevent you from accidentally accessing an array using the wrong index.

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

With Validation

In this example I used two controls,ddl and txtbox, have a happy coding

 asp:ScriptManager ID="script1" runat="server" /asp:ScriptManager

    asp:UpdatePanel ID="Panel1" runat="server"
       ContentTemplate

// ASP BUTTON
asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-success" OnClientClick="return Valid()" OnClick="btnSave_Click"


   /ContentTemplate    
    /asp:UpdatePanel    

  <script type="text/javascript">
        function Valid() {

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val() == 0) {
                alert("Please select YOUR TEXT");
                $("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val().length == 0) {
                alert("Please Type YOUR TEXT");
                $("ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }
            return true;
        }
</script>

Send file using POST from a Python script

def visit_v2(device_code, camera_code):
    image1 = MultipartParam.from_file("files", "/home/yuzx/1.txt")
    image2 = MultipartParam.from_file("files", "/home/yuzx/2.txt")
    datagen, headers = multipart_encode([('device_code', device_code), ('position', 3), ('person_data', person_data), image1, image2])
    print "".join(datagen)
    if server_port == 80:
        port_str = ""
    else:
        port_str = ":%s" % (server_port,)
    url_str = "http://" + server_ip + port_str + "/adopen/device/visit_v2"
    headers['nothing'] = 'nothing'
    request = urllib2.Request(url_str, datagen, headers)
    try:
        response = urllib2.urlopen(request)
        resp = response.read()
        print "http_status =", response.code
        result = json.loads(resp)
        print resp
        return result
    except urllib2.HTTPError, e:
        print "http_status =", e.code
        print e.read()

How to do a logical OR operation for integer comparison in shell scripting?

If you are using the bash exit code status $? as variable, it's better to do this:

if [ $? -eq 4 -o $? -eq 8 ] ; then  
   echo "..."
fi

Because if you do:

if [ $? -eq 4 ] || [ $? -eq 8 ] ; then  

The left part of the OR alters the $? variable, so the right part of the OR doesn't have the original $? value.

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How do I run a bat file in the background from another bat file?

Actually is quite easy with this option at the end:

c:\start BATCH.bat -WindowStyle Hidden

Convert Little Endian to Big Endian

You could do this:

int x = 0x12345678;

x = ( x >> 24 ) | (( x << 8) & 0x00ff0000 )| ((x >> 8) & 0x0000ff00) | ( x << 24)  ; 

printf("value = %x", x);  // x will be printed as 0x78563412

How to Define Callbacks in Android?

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

public interface NewInterface {
    void callback();
}

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }

    public void calledFromMain(){
        //Do somthing...

        //call back main
        mainClass.callback();
    }
}

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {

        System.out.println("test...");

        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }

    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}

How can you speed up Eclipse?

Go to Windows -> Preferences -> Validation and uncheck any validators you don't want or need.

For Eclipse 3.7, you use Windows -> Preferences -> General -> Startup and Shutdown.

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

is there a css hack for safari only NOT chrome?

This hack 100% work only for safari 5.1-6.0. I've just tested it with success.

@media only screen and (-webkit-min-device-pixel-ratio: 1) {
     ::i-block-chrome, .yourcssrule {
        your css property
    }
}

How to set NODE_ENV to production/development in OS X

In order to have multiple environments you need all of the answers before (NODE_ENV parameter and export it), but I use a very simple approach without the need of installing anything. In your package.json just put a script for each env you need, like this:

...
"scripts": {
    "start-dev": "export NODE_ENV=dev && ts-node-dev --respawn --transpileOnly ./src/app.ts",
    "start-prod": "export NODE_ENV=prod && ts-node-dev --respawn --transpileOnly ./src/app.ts"
  }
 ...

Then, to start the app instead of using npm start use npm run script-prod.

In the code you can access the current environment with process.env.NODE_ENV.

Voila.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Here are the functions I used for this end:

function localToGMTStingTime(localTime = null) {
    var date = localTime ? new Date(localTime) : new Date();
    return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};

function GMTToLocalStingTime(GMTTime = null) {
    var date = GMTTime ? new Date(GMTTime) : new Date();;
    return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};

How to convert date to timestamp?

Try this function, it uses the Date.parse() method and doesn't require any custom logic:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));

How do I read and parse an XML file in C#?

Linq to XML.

Also, VB.NET has much better xml parsing support via the compiler than C#. If you have the option and the desire, check it out.

How to select from subquery using Laravel Query Builder?

I like doing something like this:

Message::select('*')
->from(DB::raw("( SELECT * FROM `messages`
                  WHERE `to_id` = ".Auth::id()." AND `isseen` = 0
                  GROUP BY `from_id` asc) as `sub`"))
->count();

It's not very elegant, but it's simple.

How to get the groups of a user in Active Directory? (c#, asp.net)

In case Translate works locally but not remotly e.i group.Translate(typeof(NTAccount)

If you want to have the application code executes using the LOGGED IN USER identity, then enable impersonation. Impersonation can be enabled thru IIS or by adding the following element in the web.config.

<system.web>
<identity impersonate="true"/>

If impersonation is enabled, the application executes using the permissions found in your user account. So if the logged in user has access, to a specific network resource, only then will he be able to access that resource thru the application.

Thank PRAGIM tech for this information from his diligent video

Windows authentication in asp.net Part 87:

https://www.youtube.com/watch?v=zftmaZ3ySMc

But impersonation creates a lot of overhead on the server

The best solution to allow users of certain network groups is to deny anonymous in the web config <authorization><deny users="?"/><authentication mode="Windows"/>

and in your code behind, preferably in the global.asax, use the HttpContext.Current.User.IsInRole :

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If

NOTE: The Group must be written with a backslash \ i.e. "TheDomain\TheGroup"

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

Change values of select box of "show 10 entries" of jquery datatable

Don't forget to change the iDisplayLength as well:

$(document).ready(function() {
    $('#tbl_id').dataTable({
        "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
        "iDisplayLength": 25
    });
} );

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just make regular link look like button :)

<a href="#" role="button" class="btn btn-success btn-large">Click here!</a>

"role" inside a href code makes it look like button, ofc you can add more variables such as class.

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

How do I use itertools.groupby()?

How do I use Python's itertools.groupby()?

You can use groupby to group things to iterate over. You give groupby an iterable, and a optional key function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:

groupby(iterable[, keyfunc]) -> create an iterator which returns
(key, sub-iterator) grouped by each value of key(value).

Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, coroutine.send) to just spit out the count for however many iterations and a grouped sub-iterator of elements:

import itertools


def grouper(iterable, n):
    def coroutine(n):
        yield # queue up coroutine
        for i in itertools.count():
            for j in range(n):
                yield i
    groups = coroutine(n)
    next(groups) # queue up coroutine

    for c, objs in itertools.groupby(iterable, groups.send):
        yield c, list(objs)
    # or instead of materializing a list of objs, just:
    # return itertools.groupby(iterable, groups.send)

list(grouper(range(10), 3))

prints

[(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]

read string from .resx file in C#

The Simplest Way to get value from resource file. Add Resource file in the project. Now get the string where you want to add like in my case it was text block(SilverLight). No need to add any namespace also.Its working fine in my case

txtStatus.Text = Constants.RefractionUpdateMessage;

Constants is my resource file name in the project.Here how my resource file look like

How to convert datatype:object to float64 in python?

I had this problem in a DataFrame (df) created from an Excel-sheet with several internal header rows.

After cleaning out the internal header rows from df, the columns' values were of "non-null object" type (DataFrame.info()).

This code converted all numerical values of multiple columns to int64 and float64 in one go:

for i in range(0, len(df.columns)):
    df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
    # errors='ignore' lets strings remain as 'non-null objects'

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

Type the following command using your username and repository name:

git clone https://github.com/{user name}/{repo name}

in Ubuntu this works perfectly.

Display a view from another controller in ASP.NET MVC

Yes its possible. Return a RedirectToAction() method like this:

return RedirectToAction("ActionOrViewName", "ControllerName");

How to get the selected index of a RadioGroup in Android

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

Java2D: Increase the line width

What is Stroke:

The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

Note that the Stroke setting:

Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));

is setting the line width,since BasicStroke(float width):

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2) and Graphics2D.drawRect(int x, int y, int width, int height):

The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

'MOD' is not a recognized built-in function name

The MOD keyword only exists in the DAX language (tabular dimensional queries), not TSQL

Use % instead.

Ref: Modulo

How to merge every two lines into one from the command line?

A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

Using a comma:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string,1
KEY 4192:1349 string,1
KEY 7329:2407 string,2
KEY 0:1774 string,1

and the dollar sign:

$ paste -s -d '$\n' infile
KEY 4048:1736 string$3
KEY 0:1772 string$1
KEY 4192:1349 string$1
KEY 7329:2407 string$2
KEY 0:1774 string$1

What this cannot do is use a separator consisting of multiple characters.

As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

KEY 4048:1736 string
3
KEY 0:1772 string

paste won't tack on the separation character on the last line:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string

Java Multithreading concept and join() method

See the concept is very simple.

1) All threads are started in the constructor and thus are in ready to run state. Main is already the running thread.

2) Now you called the t1.join(). Here what happens is that the main thread gets knotted behind the t1 thread. So you can imagine a longer thread with main attached to the lower end of t1.

3) Now there are three threads which could run: t2, t3 and combined thread(t1 + main).

4)Now since till t1 is finished main can't run. so the execution of the other two join statements has been stopped.

5) So the scheduler now decides which of the above mentioned(in point 3) threads run which explains the output.

Seaborn plots not showing up

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

Please note: In Python 2, you can also use sns.plt.show(), but not in Python 3.

Complete Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

Gives

enter image description here

Google Maps: How to create a custom InfoWindow?

EDIT After some hunting around, this seems to be the best option:

https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html

You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:


There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.

Casting string to enum

Have a look at using something like

Enum.TryParse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

or

Enum.Parse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Cannot find Dumpbin.exe

In Visual Studio Professional 2017 Version 15.9.13:

  • First, either:

    • launch the "Visual Studio Installer" from the start menu, select your Visual Studio product, and click "Modify",

    or

    • from within Visual Studio go to "Tools" -> "Get Tools and Features..."
  • Then, wait for it while it is "getting things ready..." and being "almost there..."

  • Switch to the "Individual components" tab

  • Scroll down to the "Compilers, build tools, and runtimes" section

  • Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"

like this:

enter image description here

After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe

How to use the TextWatcher class in Android?

For Kotlin use KTX extension function: (It uses TextWatcher as previous answers)

yourEditText.doOnTextChanged { text, start, count, after -> 
        // action which will be invoked when the text is changing
    }


import core-KTX:

implementation "androidx.core:core-ktx:1.2.0"

Split text file into smaller multiple text file using command line

This "File Splitter" Windows command line program works nicely: https://github.com/dubasdey/File-Splitter

It's open source, simple, documented, proven, and worked for me.

Example:

fsplit -split 50 mb mylargefile.txt

How to retrieve data from sqlite database in android and display it in TextView

You may use this following code actually it is rough but plz check it out

db = openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cc = db.rawQuery("SELECT * FROM datatable", null);
final ArrayList<String> row1 = new ArrayList<String>();
final ArrayList<String> row2 = new ArrayList<String>();

if(cc!=null) {
    cc.moveToFirst();   
    startManagingCursor(cc);
    for (int i=0; i<cc.getCount(); i++) {

    String number  = cc.getString(0);
    String message = cc.getString(1);
    row1.add(number);
    row2.add(message);

    final EditText et3 = (EditText) findViewById(R.id.editText3);
    final EditText et4 = (EditText) findViewById(R.id.editText4);
    Button bt1 = (Button) findViewById(R.id.button1);
    bt1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            switch (v.getId()) {
                case R.id.button1:
                    et3.setText(row1.get(count));
                    et4.setText(row2.get(count));
                    count++;
                    break;
                default:
                    break;
            }

        }
    });

cc.moveToNext();
}

Use mysql_fetch_array() with foreach() instead of while()

To use foreach would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all function that provides an appropriate array but I could not find one for mysql (however the mysqli extension does) . You could of course write your own, like so

function mysql_fetch_all($result) {
   $rows = array();
   while ($row = mysql_fetch_array($result)) {
     $rows[] = $row;
   }
   return $rows;
}

However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?

foreach (mysql_fetch_all($result) as $row)

vs

while ($row = mysql_fetch_array($result))

while is just as concise and IMO more readable.

EDIT There is another option, but it is pretty absurd. You could use the Iterator Interface

class MysqlResult implements Iterator {
  private $rownum = 0;
  private $numrows = 0;
  private $result;

  public function __construct($result) {
    $this->result = $result;
    $this->numrows = mysql_num_rows($result);
  }

  public function rewind() {
    $this->rownum = 0;
  }

  public function current() {
    mysql_data_seek($this->result, $this->rownum);
    return mysql_fetch_array($this->result);
  }

  public function key() {
    return $this->rownum;
  }

  public function next() {
    $this->rownum++;
  }

  public function valid() {
    return $this->rownum < $this->numrows ? true : false;
  }
}

$rows = new MysqlResult(mysql_query($query_select));

foreach ($rows as $row) {
  //code...
}

In this case, the MysqlResult instance fetches rows only on request just like with while, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.

But you asked if it could be done without using while (or for I imagine). Well it can be done, just like that. Whether it should be done is up to you.

Double decimal formatting in Java

Using String.format, you can do this:

double price = 52000;
String.format("$%,.2f", price);

Notice the comma which makes this different from @Vincent's answer

Output:

$52,000.00

A good resource for formatting is the official java page on the subject

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Yes, It should be alright to have both versions installed. It's actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.

Find all matches in workbook using Excel VBA

Below code avoids creating infinite loop. Assume XYZ is the string which we are looking for in the workbook.

   Private Sub CommandButton1_Click()
   Dim Sh As Worksheet, myCounter
   Dim Loc As Range

   For Each Sh In ThisWorkbook.Worksheets
   With Sh.UsedRange
   Set Loc = .Cells.Find(What:="XYZ")

    If Not Loc Is Nothing Then

           MsgBox ("Value is found  in " & Sh.Name)
           myCounter = 1
            Set Loc = .FindNext(Loc)

    End If
End With
Next
If myCounter = 0 Then
MsgBox ("Value not present in this worrkbook")
End If

End Sub

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;
   }
}

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;
   }
}

http://www.codeply.com/go/0TU586QNlV


Bootstrap 4 Breakpoints demo

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

How do I get currency exchange rates via an API such as Google Finance?

I got this content from http://www.scriptarticle.com/2012/05/03/get-live-currency-rates-and-currency-conversion-using-php-and-apis/

<?php

function get_currency($from_Currency, $to_Currency, $amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);

    $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";

    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($ch, CURLOPT_USERAGENT,
                 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('bld>', $rawdata);
    $data = explode($to_Currency, $data[1]);

    return round($data[0], 2);
}

// Call the function to get the currency converted
echo get_currency('USD', 'INR', 1);

?>

How to copy file from host to container using Dockerfile

I was able to copy a file from my host to the container within a dockerfile as such:

  1. Created a folder on my c driver --> c:\docker
  2. Create a test file in the same folder --> c:\docker\test.txt
  3. Create a docker file in the same folder --> c:\docker\dockerfile
  4. The contents of the docker file as follows,to copy a file from local host to the root of the container: FROM ubuntu:16.04

    COPY test.txt /

  5. Pull a copy of ubuntu from docker hub --> docker pull ubuntu:16.04
  6. Build the image from the dockerfile --> docker build -t myubuntu c:\docker\
  7. Build the container from your new image myubuntu --> docker run -d -it --name myubuntucontainer myubuntu "/sbin/init"
  8. Connect to the newly created container -->docker exec -it myubuntucontainer bash
  9. Check if the text.txt file is in the root --> ls

You should see the file.

Regex for quoted string with escaping quotes

Most of the solutions provided here use alternative repetition paths i.e. (A|B)*.

You may encounter stack overflows on large inputs since some pattern compiler implements this using recursion.

Java for instance: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6337993

Something like this: "(?:[^"\\]*(?:\\.)?)*", or the one provided by Guy Bedford will reduce the amount of parsing steps avoiding most stack overflows.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

My issue is resolved when I use the below code:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:1521/servicename","userName","Password");

Open multiple Eclipse workspaces on the Mac

You can run multiple instances of Eclipse by creating a pseudonym for Eclipse application in it's folder and using it for running new Eclipse instance

How to access a RowDataPacket object

I also met the same problem recently, when I use waterline in express project for complex queries ,use the SQL statement to query.

this is my solution: first transform the return value(RowDataPacket object) into string, and then convert this string into the json object.

The following is code :

//select all user (??????)
find: function(req, res, next){
    console.log("i am in user find list");
    var sql="select * from tb_user";

    req.models.tb_user.query(sql,function(err, results) {
        console.log('>> results: ', results );
        var string=JSON.stringify(results);
        console.log('>> string: ', string );
        var json =  JSON.parse(string);
        console.log('>> json: ', json);
        console.log('>> user.name: ', json[0].name);
        req.list = json;
        next();
    });
}

The following is console:

    >> results:  [ RowDataPacket {
    user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
    name: 'wuwanyu',
    psw: '123',
    school: 'Northeastern university',                                                                                                                                           
    major: 'Communication engineering',                                                                                                                                            
    points: '10',
    datems: '1450514441486',
    createdAt: Sat Dec 19 2015 16:42:31 GMT+0800 (??????),                                                                                                  
    updatedAt: Sat Dec 19 2015 16:42:31 GMT+0800 (??????),                                                                                                  
    ID: 3,
    phone: 2147483647 } ]
>> string:  [{"user_id":"2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5","name":"wuwanyu","psw":"123","school":"Northeastern university","major":"Communication engineering","points":"10","datems":"1450514
441486","createdAt":"2015-12-19T08:42:31.000Z","updatedAt":"2015-12-19T08:42:31.000Z","ID":3,"phone":2147483647}]
>> json:  [ { user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
    name: 'wuwanyu',
    psw: '123',
    school: 'Northeastern university',                                                                                                                                           
    major: 'Communication engineering',                                                                                                                                            
    points: '10',
    datems: '1450514441486',
    createdAt: '2015-12-19T08:42:31.000Z',
    updatedAt: '2015-12-19T08:42:31.000Z',
    ID: 3,
    phone: 2147483647 } ]
>> user.name:  wuwanyu

How do I create a folder in VB if it doesn't exist?

VB.NET? System.IO.Directory.Exists(string path)

Unix command-line JSON parser?

I prefer python -m json.tool which seems to be available per default on most *nix operating systems per default.

$ echo '{"foo":1, "bar":2}' | python -m json.tool
{
    "bar": 2, 
    "foo": 1
}

Note: Depending on your version of python, all keys might get sorted alphabetically, which can or can not be a good thing. With python 2 it was the default to sort the keys, while in python 3.5+ they are no longer sorted automatically, but you have the option to sort by key explicitly:

$ echo '{"foo":1, "bar":2}' | python3 -m json.tool --sort-keys
{
    "bar": 2, 
    "foo": 1
}

Best way to store chat messages in a database?

If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.

Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure

Here's a simplified view of the file structure:

chat-1-bob.txt
        201101011029, hi
        201101011030, fine thanks.

chat-1-jen.txt
        201101011030, how are you?
        201101011035, have you spoken to bill recently?

chat-2-bob.txt
        201101021200, hi
        201101021222, about 12:22
chat-2-bill.txt
        201101021201, Hey Bob,
        201101021203, what time do you call this?

You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.

I think you will find it hard to get a more simple scaleable solution.

You can use LOAD_FILE to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

PHP multidimensional array search by value

for( $i =0; $i < sizeof($allUsers); $i++)
    {   
    $NEEDLE1='firstname';
    $NEEDLE2='emailAddress';
    $sterm='Tofind';
     if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
        {
            $Fname= $allUsers[$i][$NEEDLE1];
            $Lname= $allUsers[$i][$NEEDLE2];

            $pos1 = stripos($Fname, $sterm);
            $pos2=stripos($Lname, $sterm);//not case sensitive 

            if($pos1 !== false ||$pos2 !== false)
            {$resultsMatched[] =$allUsers[$i];}
            else
            {   continue;}              
        }

}
Print_r($resultsMatched); //will give array for matched values even partially matched

With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.

Javascript equivalent of php's strtotime()?

_x000D_
_x000D_
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

What's the difference between JPA and Hibernate?

JPA is just a specification which needs concrete implementation. The default implementation oracle provide is "Eclipselink" now. (Toplink is donated by Oracle to Eclipse foundation to merge with eclipselink)

(Reference : http://www.oracle.com/technetwork/middleware/toplink/index-085257.html http://www.eclipse.org/org/press-release/20080317_Eclipselink.php )

Using Eclipselink, one can be sure that the code is portable to any implementation if need arises. Hibernate is also a full JPA implementation + MORE ( Sort of JPA Plus). Hibernate is super set of JPA with some extra Hibernate specific functionality. So app developed in Hibernate may not be compatible when switched to other implementation. Still hibernate is choice of majority of developers as JPA implementation and widely used.

Another JPA implementation is OpenJPA (openjpa.apache.org) which is an extension of Kodo implementation.

How do I install Python packages on Windows?

pip is the package installer for python, update it first, then download what you need

python -m pip install --upgrade pip

Then:

python -m pip install <package_name>

The remote certificate is invalid according to the validation procedure

Try put this before send e-mail

ServicePointManager.ServerCertificateValidationCallback = 
        delegate(object s, X509Certificate certificate, X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; };

Remenber to add the using libs!

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

How do I update Anaconda?

root is the old (pre-conda 4.4) name for the main environment; after conda 4.4, it was renamed to be base. source

What 95% of people actually want

In most cases what you want to do when you say that you want to update Anaconda is to execute the command:

conda update --all

(But this should be preceeded by conda update -n base conda so you have the latest conda version installed)

This will update all packages in the current environment to the latest version -- with the small print being that it may use an older version of some packages in order to satisfy dependency constraints (often this won't be necessary and when it is necessary the package plan solver will do its best to minimize the impact).

This needs to be executed from the command line, and the best way to get there is from Anaconda Navigator, then the "Environments" tab, then click on the triangle beside the base environment, selecting "Open Terminal":

Open terminal from Navigator

This operation will only update the one selected environment (in this case, the base environment). If you have other environments you'd like to update you can repeat the process above, but first click on the environment. When it is selected there is a triangular marker on the right (see image above, step 3). Or from the command line you can provide the environment name (-n envname) or path (-p /path/to/env), for example to update your dspyr environment from the screenshot above:

conda update -n dspyr --all

Update individual packages

If you are only interested in updating an individual package then simply click on the blue arrow or blue version number in Navigator, e.g. for astroid or astropy in the screenshot above, and this will tag those packages for an upgrade. When you are done you need to click the "Apply" button:

Apply to update individual packages

Or from the command line:

conda update astroid astropy

Updating just the packages in the standard Anaconda Distribution

If you don't care about package versions and just want "the latest set of all packages in the standard Anaconda Distribution, so long as they work together", then you should take a look at this gist.

Why updating the Anaconda package is almost always a bad idea

In most cases updating the Anaconda package in the package list will have a surprising result: you may actually downgrade many packages (in fact, this is likely if it indicates the version as custom). The gist above provides details.

Leverage conda environments

Your base environment is probably not a good place to try and manage an exact set of packages: it is going to be a dynamic working space with new packages installed and packages randomly updated. If you need an exact set of packages then create a conda environment to hold them. Thanks to the conda package cache and the way file linking is used doing this is typically i) fast and ii) consumes very little additional disk space. E.g.

conda create -n myspecialenv -c bioconda -c conda-forge python=3.5 pandas beautifulsoup seaborn nltk

The conda documentation has more details and examples.

pip, PyPI, and setuptools?

None of this is going to help with updating packages that have been installed from PyPI via pip or any packages installed using python setup.py install. conda list will give you some hints about the pip-based Python packages you have in an environment, but it won't do anything special to update them.

Commercial use of Anaconda or Anaconda Enterprise

It is pretty much exactly the same story, with the exception that you may not be able to update the base environment if it was installed by someone else (say to /opt/anaconda/latest). If you're not able to update the environments you are using you should be able to clone and then update:

conda create -n myenv --clone base
conda update -n myenv --all

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

It is a security issue, so to fix it simply do the following:

  1. Go to the Oracle Client folder.
  2. Right Click on the folder.
  3. On security Tab, Add "Authenticated Users" and give this account Read & Execute permission.
  4. Apply this security for all folders, Subfolders and Files (IMPORTANT).
  5. Don't Forget to REBOOT your Machine; if you forgot to do this you will still face the same problem unless you restart your machine.

http://blogs.msdn.com/b/fabdulwahab/archive/2011/11/13/system-data-oracleclient-requires-oracle-client-software-version-8-1-7-or-greater.aspx

How to select the first row of each group?

Here you can do like this -

   val data = df.groupBy("Hour").agg(first("Hour").as("_1"),first("Category").as("Category"),first("TotalValue").as("TotalValue")).drop("Hour")

data.withColumnRenamed("_1","Hour").show

How can I sort an ArrayList of Strings in Java?

Check Collections#sort method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList method.

private List<String> teamsName = new ArrayList<String>();
List<String> subList = teamsName.subList(1, teamsName.size());
Collections.sort(subList);

Retrieve specific commit from a remote Git repository

In a project we had a problem so that we had to revert back to a certain commit. We made it with the following command successfully:

git reset --hard <commitID>

Python non-greedy regexes

Would not \\(.*?\\) work? That is the non-greedy syntax.

Missing visible-** and hidden-** in Bootstrap v4

Bootstrap 4 to hide whole content use this class '.d-none' it will be hide everything regardless of breakpoints same like previous bootstrap version class '.hidden'

Maximum execution time in phpMyadmin

Go to xampp/php/php.ini

Find this line:

max_execution_time=30

And change its value to any number you want. Restart Apache.

How to print Unicode character in C++?

In Linux, I can just do:

std::cout << "?";

I just copy-pasted characters from here and it didn't fail for at least the random sample that I tried on.

How do I get the HTTP status code with jQuery?

I encapsulate the jQuery Ajax to a method:

var http_util = function (type, url, params, success_handler, error_handler, base_url) {

    if(base_url) {
        url = base_url + url;
    }

    var success = arguments[3]?arguments[3]:function(){};
    var error = arguments[4]?arguments[4]:function(){};



    $.ajax({
        type: type,
        url: url,
        dataType: 'json',
        data: params,
        success: function (data, textStatus, xhr) {

            if(textStatus === 'success'){
                success(xhr.code, data);   // there returns the status code
            }
        },
        error: function (xhr, error_text, statusText) {

            error(xhr.code, xhr);  // there returns the status code
        }
    })

}

Usage:

http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
    console(status_code, data)
}, function(status_code, err){
    console(status_code, err)
})

Extracting numbers from vectors of strings

After the post from Gabor Grothendieck post at the r-help mailing list

years<-c("20 years old", "1 years old")

library(gsubfn)
pat <- "[-+.e0-9]*\\d"
sapply(years, function(x) strapply(x, pat, as.numeric)[[1]])

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How to solve time out in phpmyadmin?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Reference

how to convert JSONArray to List of Object using camel-jackson

The problem is not in your code but in your json:

{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}

this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:

class EmployeList{
    private List<Employe> compemployes;
    (with getter an setter)
}

and to deserialize the json simply do:

EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);

If your json should directly represent a list of employees it should look like:

[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]

Last remark:

List<Employee> list2 = mapper.readValue(jsonString, 
TypeFactory.collectionType(List.class, Employee.class));

TypeFactory.collectionType is deprecated you should now use something like:

List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,  
   Employee.class));

window.close() doesn't work - Scripts may close only the windows that were opened by it

The windows object has a windows field in which it is cloned and stores the date of the open window, close should be called on this field:

window.open("", '_self').window.close();

How to add Active Directory user group as login in SQL Server

In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins and right-click New Login:

enter image description here

Then in the dialog box that pops up, pick the types of objects you want to see (Groups is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory) and then find your AD group.

enter image description here

You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!

Any member of that AD group can now login to SQL Server and use your database.

How to call a function, PostgreSQL

We can have two ways of calling the functions written in pgadmin for postgre sql database.

Suppose we have defined the function as below:

CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
DECLARE
BEGIN
    RAISE LOG 'Hello, %', name;
END;
$helloWorld$ LANGUAGE plpgsql;

We can call the function helloworld in one of the following way:

SELECT "helloworld"('myname');

SELECT public.helloworld('myname')

VBA - Select columns using numbers?

I was looking for a similar thing. My problem was to find the last column based on row 5 and then select 3 columns before including the last column.

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn - 3), Columns(lColumn)).Select

Message box is optional as it is more of a control check. If you want to select the columns after the last column then you simply reverse the range selection

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn), Columns(lColumn + 3)).Select

UTF-8 byte[] to String

To convert utf-8 data, you can't assume a 1-1 correspondence between bytes and characters. Try this:

String file_string = new String(bytes, "UTF-8");

(Bah. I see I'm way to slow in hitting the Post Your Answer button.)

To read an entire file as a String, do something like this:

public String openFileToString(String fileName) throws IOException
{
    InputStream is = new BufferedInputStream(new FileInputStream(fileName));

    try {
        InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
        StringBuilder contents = new StringBuilder();
        char[] buff = new char[4096];
        int len = rdr.read(buff);
        while (len >= 0) {
            contents.append(buff, 0, len);
        }
        return buff.toString();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // log error in closing the file
        }
    }
}

C++ - struct vs. class

1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD

PHP reindex array?

Use array_values.

$myarray = array_values($myarray);

Copy a table from one database to another in Postgres

To move a table from database A to database B at your local setup, use the following command:

pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2

How to rename with prefix/suffix?

You could use the rename(1) command:

rename 's/(.*)$/new.$1/' original.filename

Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

If nothing works from above solutions follow these steps

From Targets select appnameTests Under "Info"

Change following

Bundle Identifier: com.ProjectName.$(PRODUCT_NAME:rfc1034identifier)

to com.ProjectName.appname

Bundle name: $(PRODUCT_NAME)

Bundle name: appname

Compile & execute

Is there a common Java utility to break a list into batches?

Check out Lists.partition(java.util.List, int) from Google Guava:

Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

Get all validation errors from Angular 2 FormGroup

I met the same problem and for finding all validation errors and displaying them, I wrote next method:

getFormValidationErrors() {
  Object.keys(this.productForm.controls).forEach(key => {

  const controlErrors: ValidationErrors = this.productForm.get(key).errors;
  if (controlErrors != null) {
        Object.keys(controlErrors).forEach(keyError => {
          console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
        });
      }
    });
  }

Form name productForm should be changed to yours.

It works in next way: we get all our controls from form in format {[p: string]: AbstractControl} and iterate by each error key, for get details of error. It skips null error values.

It also can be changed for displaying validation errors on the template view, just replace console.log(..) to what you need.

Sharing link on WhatsApp from mobile website (not application) for Android

Try to make it this way:

<a href="https://wa.me/(phone)?text=(text URL encoded)">Link</a>

Even you can send messages without enter the phone number in the link:

<a href="https://wa.me/?text=Hello%20world!">Say hello</a>

After clicking on the link, you will be shown a list of contacts you can send your message to.

More info in https://faq.whatsapp.com/en/general/26000030.

Good luck!

How to recognize vehicle license / number plate (ANPR) from an image?

It maybe work looking at Character recoqnition software as there are many libraries out there that perform the same thing. I reading an image and storing it. Micrsoft office is able to read tiff files and return alphanumerics

Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site: https://brendandahl.github.io/trapeze-reader/demos/

Github page: https://github.com/brendandahl/trapeze-reader

Disclaimer: I'm the author.

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

Get a pixel from HTML Canvas?

Fast and handy

Use following class which implement fast method described in this article and contains all you need: readPixel, putPixel, get width/height. Class update canvas after calling refresh() method. Example solve simple case of 2d wave equation

_x000D_
_x000D_
class Screen{
  constructor(canvasSelector) {
    this.canvas = document.querySelector(canvasSelector);
    this.width  = this.canvas.width;
    this.height = this.canvas.height;
    this.ctx = this.canvas.getContext('2d');
    this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
    this.buf = new ArrayBuffer(this.imageData.data.length);
    this.buf8 = new Uint8ClampedArray(this.buf);
    this.data = new Uint32Array(this.buf);  
  }
  
  // r,g,b,a - red, gren, blue, alpha components in range 0-255
  putPixel(x,y,r,g,b,a=255) {
    this.data[y * this.width + x] = (a << 24) | (b << 16) | (g <<  8) | r;
  }
  
  readPixel(x,y) {
    let p= this.data[y * this.width + x]
    return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
  }

  refresh() {
    this.imageData.data.set(this.buf8);
    this.ctx.putImageData(this.imageData, 0, 0);
  }
}




// --------
// TEST
// --------

let s=new Screen('#canvas');

function draw() {

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {      
      let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=> 
        a+= s.readPixel(x+xp,y+yp)[0]
      ,0);
      let v=a/2-tmp[x][y];
      tmp[x][y]=v<0 ? 0:v;
    }
  }

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {  
      let v=tmp[x][y];
      tmp[x][y]= s.readPixel(x,y)[0];
      s.putPixel(x,y, v,v,v);
    }
  }

  s.refresh();
  window.requestAnimationFrame(draw)
}

// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));

function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}

draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black box</div>
_x000D_
_x000D_
_x000D_

How can I use the python HTMLParser library to extract data from a specific div tag?

This works perfectly:

print (soup.find('the tag').text)

Can I use git diff on untracked files?

usually when i work with remote location teams it is important for me that i have prior knowledge what change done by other teams in same file, before i follow git stages untrack-->staged-->commit for that i wrote an bash script which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on main branch

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | grep "modified" | awk "{print $2}" `
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool FETCH_HEAD $file ;
done

in above script i fetch remote main branch (not necessary its master branch)to FETCH_HEAD them make a list of my modified file only and compare modified files to git difftool

here many difftool supported by git, i configure 'Meld Diff Viewer' for good GUI comparison .

Post-increment and Pre-increment concept?

All four answers so far are incorrect, in that they assert a specific order of events.

Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.

So.

For the built-in C++ prefix operator,

++x

increments x and produces (as the expression's result) x as an lvalue, while

x++

increments x and produces (as the expression's result) the original value of x.

In particular, for x++ there is no no time ordering implied for the increment and production of original value of x. The compiler is free to emit machine code that produces the original value of x, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).

Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.

log4j vs logback

Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).

SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).

SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.

Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.

Obtain form input fields using jQuery?

If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following:

$('#contentform').find('input, textarea, select').each(function(x, field) {
    if (field.name) {
        if (field.name.indexOf('[]')>0) {
            if (!$.isArray(data[field.name])) {
               data[field.name]=new Array();
            }
            data[field.name].push(field.value);
        } else {
            data[field.name]=field.value;
        }
    }                   
});

Stack, Static, and Heap in C++

I'm sure one of the pedants will come up with a better answer shortly, but the main difference is speed and size.

Stack

Dramatically faster to allocate. It is done in O(1) since it is allocated when setting up the stack frame so it is essentially free. The drawback is that if you run out of stack space you are boned. You can adjust the stack size, but IIRC you have ~2MB to play with. Also, as soon as you exit the function everything on the stack is cleared. So it can be problematic to refer to it later. (Pointers to stack allocated objects leads to bugs.)

Heap

Dramatically slower to allocate. But you have GB to play with, and point to.

Garbage Collector

The garbage collector is some code that runs in the background and frees memory. When you allocate memory on the heap it is very easy to forget to free it, which is known as a memory leak. Over time, the memory your application consumes grows and grows until it crashes. Having a garbage collector periodically free the memory you no longer need helps eliminate this class of bugs. Of course this comes at a price, as the garbage collector slows things down.

Recursively looping through an object to build a property list

I'll provide a solution too, using recursion. Commented lines to clarify things.

It works well for its purpose right now.

_x000D_
_x000D_
// works only if the value is a dictionary or something specified below, and adds all keys in nested objects and outputs them

const example = {
  city: "foo",
  year: 2020,
  person: {
    name: "foo",
    age: 20,
    deeper: {
      even_deeper: {
        key: "value", 
        arr: [1, 2, {
          a: 1,
          b: 2
        }]
      }
    }
  },
};

var flat  =  [];    // store keys
var depth =  0;     // depth, used later
var path  =  "obj"; // base path to be added onto, specified using the second parameter of flatKeys 

let flatKeys = (t, name) => {
  path = name ? name : path;  // if specified, set the path 
  for (const k in t) {
    const v = t[k];
    let type = typeof v;      // store the type value's type
    switch (type) {  
      case "string":          // these are the specified cases for which a key will be added,
      case "number":          // specify more if you want
      case "array" :
        flat.push(path + "." + k);  // add the complete path to the array
        break;
      case "object":
        flat.push(path + "." + k)
        path += "." + k;
        flatKeys(v);
        break;
    }
  }
  return flat;
};

let flattened = flatKeys(example, "example"); // the second argument is what the root path should be (for convenience)
console.log(flattened, "keys: " + flattened.length);
_x000D_
_x000D_
_x000D_

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

How do I format a date with Dart?

import 'package:intl/intl.dart';

main() {
  var formattedDate = new DateTime.Format('yyyy-MM-dd').DateTime.now();
  print(formattedDate); // something like 2020-04-16
}

For more details can refer DateFormat Documentation

Python != operation vs "is not"

None is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via .__eq__().

Get string between two strings in a string

As I always say nothing is impossible:

string value =  "super exemple of string key : text I want to keep - end of my string";
Regex regex = new Regex(@"(key \: (.*?) _ )");
Match match = regex.Match(value);
if (match.Success)
{
    Messagebox.Show(match.Value);
}

Remeber that should add reference of System.Text.RegularExpressions

Hope That I Helped.

m2eclipse error

In this particular case, the solution was the right proxy configuration of eclipse (Window -> Preferences -> Network Connection), the company possessed a strict security system. I will leave the question, because there are answers that can help the community. Thank you very much for the answers above.

Java Immutable Collections

The difference is that you can't have a reference to an immutable collection which allows changes. Unmodifiable collections are unmodifiable through that reference, but some other object may point to the same data through which it can be changed.

e.g.

List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);

Apply jQuery datepicker to multiple instances

To change use of class instead of ID

<script type="text/javascript"> 
    $(function() { 
        $('.my_date1').datepicker(); 
        $('.my_date2').datepicker(); 
        $('.my_date3').datepicker(); 
        ... 
    }); 
</script>

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

Better you update your eclipse by clicking it on help >> check for updates, also you can start eclipse by entering command in command prompt eclipse -clean.
Hope this will help you.

How get an apostrophe in a string in javascript

You can try the following:

theAnchorText = "I'm home";

OR

theAnchorText = 'I\'m home';

JavaScript get element by name

document.getElementsByName("myInput")[0].value;

How to set thymeleaf th:field value from other variable

If you don't have to come back on the page with keeping form's value, you can do that :

<form method="post" th:action="@{''}" th:object="${form}">
    <input class="form-control"
           type="text"
           th:field="${client.name}"/>

It's some kind of magic :

  • it will set the value = client.name
  • it will send back the value in the form, as 'name' field. So you would have to change your form field, 'clientName' to 'name'

If you matter keeping you form's input values, like a back on the page with an user input mistake, then you will have to do that :

<form method="post" th:action="@{''}" th:object="${form}">
    <input class="form-control"
           type="text"
           th:name="name"
           th:value="${form.name != null} ? ${form.name} : ${client.name}"/>

That means :

  • The form field name is 'name'
  • The value is taken from the form if it exists, else from the client bean. Which matches the first arrival on the page with initial value, then the forms input values if there is an error.

Without having to map your client bean to your form bean. And it works because once you submitted the form, the value arn't null but "" (empty)

How do I implement JQuery.noConflict() ?

The noConflict() method releases the $ shortcut identifier, so that other scripts can use it for next time.

Default jquery $ as:

// Actin  with $
$(function(){
    $(".add").hide();
    $(".add2").show();
});

Or as custom:

var j = jQuery.noConflict();
 // Action with j
j(function(){
    j(".edit").hide();
    j(".add2").show();
});

How to delete a character from a string using Python

To delete a char or a sub-string once (only the first occurrence):

main_string = main_string.replace(sub_str, replace_with, 1)

NOTE: Here 1 can be replaced with any int for the number of occurrence you want to replace.

C# winforms combobox dynamic autocomplete

I Also come across these kind of requirements recently.I set the below properties with out writing the code it works.see if this helps you.

enter image description here

Count characters in textarea

substring() needs to become substr().

Example: jsfiddle.net/xqyWV

using BETWEEN in WHERE condition

Sounds correct but some issues maybe creates executing this query: I would suggest:

$this->db->where( "$accommodation BETWEEN $minvalue AND $maxvalue", NULL, FALSE );

How to initailize byte array of 100 bytes in java with all 0's

The default element value of any array of primitives is already zero: false for booleans.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

My solution inspired here goes as follows:

<form>
    <input type="text" style="position: absolute !important; left: -10000px !important; top: -10000px !important;">
    <input type="password" style="position: absolute !important; left: -10000px !important; top: -10000px !important;">
    Username: <input type="text">
    Password: <input type="password">
    <input type="submit">
</form>

It sure is ugly, feels misplaced in 2017, but it works and protects the username and password field from autofilling. Note that in Firefox (version 51 at the time of writing) it does not matter a bit what combination of name, id or autocomplete is used, be it on form or input fields. Without the first two dummy fields, autofilling will take place any time domain is matched and it will ruin your day.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

Meaning of ${project.basedir} in pom.xml

There are a set of available properties to all Maven projects.

From Introduction to the POM:

project.basedir: The directory that the current project resides in.

This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml file. If your POM is located inside /path/to/project/pom.xml then this property will evaluate to /path/to/project.

Some properties are also inherited from the Super POM, which is the case for project.build.directory. It is the value inside the <project><build><directory> element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory, it is:

The directory where all files generated by the build are placed. The default value is target.

This is the directory that will hold every generated file by the build.

How many bytes in a JavaScript string?

I'm working with an embedded version of the V8 Engine. I've tested a single string. Pushing each step 1000 characters. UTF-8.

First test with single byte (8bit, ANSI) Character "A" (hex: 41). Second test with two byte character (16bit) "O" (hex: CE A9) and the third test with three byte character (24bit) "?" (hex: E2 98 BA).

In all three cases the device prints out of memory at 888 000 characters and using ca. 26 348 kb in RAM.

Result: The characters are not dynamically stored. And not with only 16bit. - Ok, perhaps only for my case (Embedded 128 MB RAM Device, V8 Engine C++/QT) - The character encoding has nothing to do with the size in ram of the javascript engine. E.g. encodingURI, etc. is only useful for highlevel data transmission and storage.

Embedded or not, fact is that the characters are not only stored in 16bit. Unfortunally I've no 100% answer, what Javascript do at low level area. Btw. I've tested the same (first test above) with an array of character "A". Pushed 1000 items every step. (Exactly the same test. Just replaced string to array) And the system bringt out of memory (wanted) after 10 416 KB using and array length of 1 337 000. So, the javascript engine is not simple restricted. It's a kind more complex.

export html table to csv

I found there is a library for this. See example here:

https://editor.datatables.net/examples/extensions/exportButtons.html

In addition to the above code, the following Javascript library files are loaded for use in this example:

In HTML, include following scripts:

jquery.dataTables.min.js   
dataTables.editor.min.js   
dataTables.select.min.js
dataTables.buttons.min.js  
jszip.min.js    
pdfmake.min.js
vfs_fonts.js  
buttons.html5.min.js    
buttons.print.min.js

Enable buttons by adding scripts like:

<script>
$(document).ready( function () {
    $('#table-arrays').DataTable({
        dom: '<"top"Blf>rt<"bottom"ip>',
        buttons: ['copy', 'excel', 'csv', 'pdf', 'print'],
        select: true,
    });
} );
</script>

For some reason, the excel export results in corrupted file, but can be repaired. Alternatively, disable excel and use csv export.

Jquery mouseenter() vs mouseover()

The mouseenter event differs from mouseover in the way it handles event bubbling. The mouseenter event, only triggers its handler when the mouse enters the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseenter/

The mouseleave event differs from mouseout in the way it handles event bubbling. The mouseleave event, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseleave/

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

addEventListener not working in IE8

I've opted for a quick Polyfill based on the above answers:

//# Polyfill
window.addEventListener = window.addEventListener || function (e, f) { window.attachEvent('on' + e, f); };

//# Standard usage
window.addEventListener("message", function(){ /*...*/ }, false);

Of course, like the answers above this doesn't ensure that window.attachEvent exists, which may or may not be an issue.

PDF Editing in PHP?

Zend Framework can load and edit existing PDF files. I think it supports revisions too.

I use it to create docs in a project, and it works great. Never edited one though.

Check out the doc here

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

Google Maps API 3 - Custom marker color for default (dot) marker

These are custom Circular markers

small_red:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NUlH5v9rF5f+ZoCAwHaig8B8oPhOmKC1NU/P//7Q0DByrqgpSGAtSdOCAry9WRXt9fECK9oIUPXwYFYVV0e2ICJCi20SbFAuyG5uiECUlkKIQmOPng3y30d0d7Lt1bm4w301jQAOgcNoIDad1yOEEAFm9fSv/VqtJAAAAAElFTkSuQmCC

small_yellow:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NijL7v3p1+v8zZ6rAdGCg4X+g+EyYorS0NNv////PxMCxsRYghbEgRQcOHCjGqmjv3kKQor0gRQ8fPmzHquj27WaQottEmxQLshubopAQI5CiEJjj54N8t3FjFth369ZlwHw3jQENgMJpIzSc1iGHEwB8p5qDBbsHtAAAAABJRU5ErkJggg==

small_green:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiElEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81izL7n746/X/VmSowbRho+B8oPhOmKM02zfb/TCzQItYCpDAWpOhA8YFirIoK9xaCFO0FKXrY/rAdq6Lm280gRbeJNikWZDc2RUYhRiBFITDHzwf5LmtjFth3GesyYL6bxoAGQOG0ERpO65DDCQDX7ovT++K9KQAAAABJRU5ErkJggg==

small_blue:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81M4v6n56++n9V1RkwbWgY+B8oPhOmKM3WNu3/zJn/MbCFRSxIYSxI0YHi4gNYFRUW7gUp2gtS9LC9/SFWRc3Nt0GKbhNtUizIbmyKjIxCQIpCYI6fD/JdVtZGsO8yMtbBfDeNAQ2AwmkjNJzWIYcTAMk+i9OhipcQAAAAAElFTkSuQmCC

small_purple:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NMov6vzp99f8zVWfAdKBh4H+g+EyYorQ027T//2f+x8CxFrEghbEgRQcOFB/Aqmhv4V6Qor0gRQ8ftj/Equh2822QottEmxQLshubohCjEJCiEJjj54N8tzFrI9h36zLWwXw3jQENgMJpIzSc1iGHEwBt95qDejjnKAAAAABJRU5ErkJggg==

They are 9x9 png images.

Once they're on your page you can just drag them off and you'll have the actual png file.

Getting raw SQL query string from PDO prepared statements

Added a little bit more to the code by Mike - walk the values to add single quotes

/**
 * Replaces any parameter placeholders in a query with the value of that
 * parameter. Useful for debugging. Assumes anonymous parameters from 
 * $params are are in the same order as specified in $query
 *
 * @param string $query The sql query with parameter placeholders
 * @param array $params The array of substitution parameters
 * @return string The interpolated query
 */
public function interpolateQuery($query, $params) {
    $keys = array();
    $values = $params;

    # build a regular expression for each parameter
    foreach ($params as $key => $value) {
        if (is_string($key)) {
            $keys[] = '/:'.$key.'/';
        } else {
            $keys[] = '/[?]/';
        }

        if (is_array($value))
            $values[$key] = implode(',', $value);

        if (is_null($value))
            $values[$key] = 'NULL';
    }
    // Walk the array to see if we can add single-quotes to strings
    array_walk($values, create_function('&$v, $k', 'if (!is_numeric($v) && $v!="NULL") $v = "\'".$v."\'";'));

    $query = preg_replace($keys, $values, $query, 1, $count);

    return $query;
}

What's the difference between interface and @interface in java?

interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:

@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}

This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.

Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.

To use the above annotation, you could use code like this:

@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}

Reference - http://tutorials.jenkov.com/java/annotations.html

UIView frame, bounds and center

This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.

To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)

To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)

Like the frame, view.center is also in the coordinates of the superview.

Frame vs Bounds - Example 1

The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.

Frame
    origin = (0, 0)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 2

Frame
    origin = (40, 60)  // That is, x=40 and y=60
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 3

Frame
    origin = (20, 52)  // These are just rough estimates.
    width = 118
    height = 187

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 4

This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 5

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (280, 70)
    width = 80
    height = 130

enter image description here

Again, see here for my answer with more details.

How should strace be used?

strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.

Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

How do I kill background processes / jobs when my shell script exits?

function cleanup_func {
    sleep 0.5
    echo cleanup
}

trap "exit \$exit_code" INT TERM
trap "exit_code=\$?; cleanup_func; kill 0" EXIT

# exit 1
# exit 0

Like https://stackoverflow.com/a/22644006/10082476, but with added exit-code

How do you import a large MS SQL .sql file?

I had similar problem. My file with sql script was over 150MB of size (with almost 900k of very simple INSERTs). I used solution advised by Takuro (as the answer in this question) but I still got error with message saying that there was not enough memory ("There is insufficient system memory in resource pool 'internal' to run this query").

What helped me was that I put GO command after every 50k INSERTs.

(It's not directly addressing the question (file size) but I believe it resolves problem that is indirectly connected with large size of sql script itself. In my case many insert commands)

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

Follow below steps:

    1. Ensure to delete all the contents of the jar folder located in your local except the jar that you want to keep.
      For example files like .repositories, .pom, .sha1, .lastUpdated etc.
    1. Execute mvn clean install -o command

This will help to use local repository jar files rather than connecting to any repository.

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

jQuery append() - return appended elements

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);

How to get week number of the month from the date in sql server 2008

Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -

select (DATEPART(wk,@date_given)-DATEPART(wk,dateadd(d,1-day(@date_given),@date_given)))+1

above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month

Select a date from date picker using Selenium webdriver

I think there will be different ways to select a Date for different Date picker formats. For a Date Picker where you need to select a year and month from a dropdown and then pick/click a Date, I wrote the following code.

private void setupDate(WebDriver driver, String csvRow) throws Exception {
    String date[] = (csvRow).split("-");
    driver.findElement(By.id("flddateanchor")).click();
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-year")))
            .selectByVisibleText(date[0]);
    Thread.sleep(1000);
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-month")))
            .selectByVisibleText(date[1]);
    Thread.sleep(1000);
    driver.findElement(By.linkText(date[2])).click();
    Thread.sleep(1000);
}

I got the cssSelector part by the Selenium Firefox IDE. Also, my Date(csvRow) is in (2015-03-31) format.

Hope it helps.

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

How to assign a select result to a variable?

DECLARE @tmp_key int
DECLARE @get_invckey cursor 

SET @get_invckey = CURSOR FOR 
    SELECT invckey FROM tarinvoice WHERE confirmtocntctkey IS NULL AND tranno LIKE '%115876'

OPEN @get_invckey 

FETCH NEXT FROM @get_invckey INTO @tmp_key

DECLARE @PrimaryContactKey int --or whatever datatype it is

WHILE (@@FETCH_STATUS = 0) 
BEGIN 
    SELECT @PrimaryContactKey=c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey AND i.invckey = @tmp_key

    UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey WHERE invckey = @tmp_key
    FETCH NEXT FROM @get_invckey INTO @tmp_key
END 

CLOSE @get_invckey
DEALLOCATE @get_invckey

EDIT:
This question has gotten a lot more traction than I would have anticipated. Do note that I'm not advocating the use of the cursor in my answer, but rather showing how to assign the value based on the question.

Extract column values of Dataframe as List in Apache Spark

sqlContext.sql(" select filename from tempTable").rdd.map(r => r(0)).collect.toList.foreach(out_streamfn.println) //remove brackets

it works perfectly

How do I use .toLocaleTimeString() without displaying seconds?

I think the original question can easily be answered with something being overlooked so far: a simple string split. The time being returned is a text string, just split it on the ":" delimiter and reassemble the string the way you want. No plug ins, no complicated scripting. and here ya go:

var myVar=setInterval(function(){myTimer()},1000);

function myTimer() {
    var d = new Date();
    currentNow = d.toLocaleTimeString();
    nowArray = currentNow.split(':');
    filteredNow = nowArray[0]+':'+nowArray[1];
    document.getElementById("demo").innerHTML = filteredNow;
}

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

Because the second element is null after you clear the list.

Use:

String s = myList.get(0);

And remember, index 0 is the first element.

Finding local IP addresses using Python's stdlib

Note: This is not using the standard library, but quite simple.

$ pip install pif

from pif import get_public_ip
get_public_ip()

Java image resize, maintain aspect ratio

I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):

public static Point scaleFit(Point src, Point bounds) {
  int newWidth = src.x;
  int newHeight = src.y;
  double boundsAspectRatio = bounds.y / (double) bounds.x;
  double srcAspectRatio = src.y / (double) src.x;

  // first check if we need to scale width
  if (boundsAspectRatio < srcAspectRatio) {
    // scale width to fit
    newWidth = bounds.x;
    //scale height to maintain aspect ratio
    newHeight = (newWidth * src.y) / src.x;
  } else {
    //scale height to fit instead
    newHeight = bounds.y;
    //scale width to maintain aspect ratio
    newWidth = (newHeight * src.x) / src.y;
  }

  return new Point(newWidth, newHeight);
}

Written in Android terminology :-)

as for the tests:

@Test public void scaleFit() throws Exception {
  final Point displaySize = new Point(1080, 1920);
  assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
  assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}

Netbeans - Error: Could not find or load main class

Sometimes due to out of memory space error, NetBeans does not load or find main class.

If you have tried setting the properties and still it is not working then try

  1. Select the project from the project explorer
  2. Click on Run in the Menu Bar
  3. Click on Compile

It worked for me.

How to generate XML file dynamically using PHP?

$query=mysql_query("select * from tablename")or die(mysql_error()); 
$xml="<libraray>\n\t\t";
while($data=mysql_fetch_array($query))
{

    $xml .="<mail_address>\n\t\t";
    $xml .= "<id>".$data['id']."</id>\n\t\t";
    $xml .= "<email>".$data['email_address']."</email>\n\t\t";
    $xml .= "<verify_code>".$data['verify']."</verify_code>\n\t\t";
    $xml .= "<status>".$data['status']."</status>\n\t\t";
    $xml.="</mail_address>\n\t";
}
$xml.="</libraray>\n\r";
$xmlobj=new SimpleXMLElement($xml);
$xmlobj->asXML("text.xml");

Its simple just connect with your database it will create test.xml file in your project folder

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

How can I view a git log of just one user's commits?

cat | git log --author="authorName" > author_commits_details.txt

This gives your commits in text format.

HTML5 canvas ctx.fillText won't do line breaks?

I happened across this due to having the same problem. I'm working with variable font size, so this takes that into account:

var texts=($(this).find('.noteContent').html()).split("<br>");
for (var k in texts) {
    ctx.fillText(texts[k], left, (top+((parseInt(ctx.font)+2)*k)));
}

where .noteContent is the contenteditable div the user edited (this is nested in a jQuery each function), and ctx.font is "14px Arial" (notice that the pixel size comes first)

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

Display image at 50% of its "native" size

Maybe one of the easiest solutions would be to use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

If file = open(filename, encoding="utf8") doesn't work, try
file = open(filename, errors="ignore"), if you want to remove unneeded characters.

Responsive bootstrap 3 timepicker?

Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.

Bootstrap-3 Clock-Picker

CSS

<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">

HTML

<div class="input-group clockpicker">
    <input type="text" class="form-control" value="09:30">
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-time"></span>
    </span>
</div>

JAVASCRIPT

<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
    $('.clockpicker').clockpicker();
</script>

As simple as that! Find more examples on the link above.

Update 18/04/2018

If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.

Bootstrap-4 Tempus Dominus

Excel VBA - How to Redim a 2D array?

here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)

Option explicit
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
    Dim nFirst As Long
    Dim nLast As Long
    Dim nOldFirstUBound As Long
    Dim nOldLastUBound As Long

    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then
        'create new array
        ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = UBound(aArrayToPreserve, 1)
        nOldLastUBound = UBound(aArrayToPreserve, 2)
        'loop through first
        For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
            For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
                End If
            Next
        Next
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

Changing the sign of a number in PHP?

A trivial

$num = $num <= 0 ? $num : -$num ;

or, the better solution, IMHO:

$num = -1 * abs($num)

As @VegardLarsen has posted,

the explicit multiplication can be avoided for shortness but I prefer readability over shortness

I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.

"If the float is a negative, make it a positive."

In order to change the sign of a number you can simply do:

$num = 0 - $num;

or, multiply it by -1, of course :)

Removing double quotes from variables in batch file creates problems with CMD environment

This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.

Alter user defined type in SQL Server

As devio says there is no way to simply edit a UDT if it's in use.

A work-round through SMS that worked for me was to generate a create script and make the appropriate changes; rename the existing UDT; run the create script; recompile the related sprocs and drop the renamed version.

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

Datagridview full row selection but get single cell value

dataGridView1.SelectedRows[0].Cells[0].Value;

How do I prevent DIV tag starting a new line?

Add style="display: inline" to your div.

Command line .cmd/.bat script, how to get directory of running script

Raymond Chen has a few ideas:

https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

Quoted here in full because MSDN archives tend to be somewhat unreliable:

The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory

(Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args

(I like to use %_% as my scratch environment variable.)

Type SET /? to see the other pseudo-variables provided by the command processor.

Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

This covers the use of %~dp0:

If you want to know where the batch file lives: %~dp0

%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

html5 input for money/currency

Using javascript's Number.prototype.toLocaleString:

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = (value || value === 0) 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Here's a very simple demo illustrating the above method (HTML-only)


I've made a tiny React component if anyone's interested

Javascript Src Path

src="/clock.js"

be careful it's root of the domain.

P.S. and please use lowercase for attribute names.

Read text from response

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();

Checking if a double (or float) is NaN in C++

nan prevention

My answer to this question is don't use retroactive checks for nan. Use preventive checks for divisions of the form 0.0/0.0 instead.

#include <float.h>
float x=0.f ;             // I'm gonna divide by x!
if( !x )                  // Wait! Let me check if x is 0
  x = FLT_MIN ;           // oh, since x was 0, i'll just make it really small instead.
float y = 0.f / x ;       // whew, `nan` didn't appear.

nan results from the operation 0.f/0.f, or 0.0/0.0. nan is a terrible nemesis to the stability of your code that must be detected and prevented very carefully1. The properties of nan that are different from normal numbers:

  • nan is toxic, (5*nan=nan)
  • nan is not equal to anything, not even itself (nan != nan)
  • nan not greater than anything (nan !> 0)
  • nan is not less than anything (nan !< 0)

The last 2 properties listed are counter-logical and will result in odd behavior of code that relies on comparisons with a nan number (the 3rd last property is odd too but you're probably not ever going to see x != x ? in your code (unless you are checking for nan (unreliably))).

In my own code, I noticed that nan values tend to produce difficult to find bugs. (Note how this is not the case for inf or -inf. (-inf < 0) returns TRUE, ( 0 < inf ) returns TRUE, and even (-inf < inf) returns TRUE. So, in my experience, the behavior of the code is often still as desired).

what to do under nan

What you want to happen under 0.0/0.0 must be handled as a special case, but what you do must depend on the numbers you expect to come out of the code.

In the example above, the result of (0.f/FLT_MIN) will be 0, basically. You may want 0.0/0.0 to generate HUGE instead. So,

float x=0.f, y=0.f, z;
if( !x && !y )    // 0.f/0.f case
  z = FLT_MAX ;   // biggest float possible
else
  z = y/x ;       // regular division.

So in the above, if x were 0.f, inf would result (which has pretty good/nondestructive behavior as mentioned above actually).

Remember, integer division by 0 causes a runtime exception. So you must always check for integer division by 0. Just because 0.0/0.0 quietly evaluates to nan doesn't mean you can be lazy and not check for 0.0/0.0 before it happens.

1 Checks for nan via x != x are sometimes unreliable (x != x being stripped out by some optimizing compilers that break IEEE compliance, specifically when the -ffast-math switch is enabled).

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
  • Here is an example of request execution process in its simplest form:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {
        response.close();
    }

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {
        httpclient.close();
    }

see the Reference to learn fundamentals.


@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something
    }

    //do something else with httpclient here
}

Is it possible in Java to catch two exceptions in the same catch block?

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Populating a ComboBox using C#

Set the ValueMember/DisplayMember properties to the name of the properties of your Language objects.

class Language
{
    string text;
    string value;

    public string Text
    {
        get 
        {
            return text;
        }
    }

    public string Value
    {
        get
        {
            return value;
        }
    }

    public Language(string text, string value)
    {
        this.text = text;
        this.value = value;
    }
}

...

combo.DisplayMember= "Text";
combo.ValueMember = "Value";
combo.Items.Add(new Language("English", "en"));

How to view DB2 Table structure

Use the below to check the table description for a single table

DESCRIBE TABLE Schema Name.Table Name

join the below tables to check the table description for a multiple tables, join with the table id syscat.tables and syscat.columns

You can also check the details of indexes on the table using the below command describe indexes for table . show detail

Using Exit button to close a winform program

The FormClosed Event is an Event that fires when the form closes. It is not used to actually close the form. You'll need to remove anything you've added there.

All you should have to do is add the following line to your button's event handler:

this.Close();