Programs & Examples On #Mark of the web

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Composer update memory limit

In my case none of the answers helped. Finally it turned out, that changing to a 64 bit version of PHP (M$ Windows) fixed the problem immediately. I did not change any settings - it just worked.

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

Sending commands and strings to Terminal.app with Applescript

Kinda related, you might want to look at Shuttle (http://fitztrev.github.io/shuttle/), it's a SSH shortcut menu for OSX.

Assign a variable inside a Block to a variable outside a Block

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

Insert Data Into Temp Table with Query

Try this:

SELECT *
INTO #Temp
FROM 
(select * from tblorders where busidate ='2016-11-24' and locationID=12
) as X

Please use alias with x so it will not failed the script and result.

Cannot delete directory with Directory.Delete(path, true)

It appears that having the path or subfolder selected in Windows Explorer is enough to block a single execution of Directory.Delete(path, true), throwing an IOException as described above and dying instead of booting Windows Explorer out to a parent folder and proceding as expected.

How to run a C# console application with the console hidden

Based on Adam Markowitz's answer above, following worked for me:

process = new Process();
process.StartInfo = new ProcessStartInfo("cmd.exe", "/k \"" + CmdFilePath + "\"");
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//process.StartInfo.UseShellExecute = false;
//process.StartInfo.CreateNoWindow = true;
process.Start();

How to make a Python script run like a service or daemon in Linux

You can also make the python script run as a service using a shell script. First create a shell script to run the python script like this (scriptname arbitary name)

#!/bin/sh
script='/home/.. full path to script'
/usr/bin/python $script &

now make a file in /etc/init.d/scriptname

#! /bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/home/.. path to shell script scriptname created to run python script
PIDFILE=/var/run/scriptname.pid

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

case "$1" in
  start)
     log_daemon_msg "Starting feedparser"
     start_daemon -p $PIDFILE $DAEMON
     log_end_msg $?
   ;;
  stop)
     log_daemon_msg "Stopping feedparser"
     killproc -p $PIDFILE $DAEMON
     PID=`ps x |grep feed | head -1 | awk '{print $1}'`
     kill -9 $PID       
     log_end_msg $?
   ;;
  force-reload|restart)
     $0 stop
     $0 start
   ;;
  status)
     status_of_proc -p $PIDFILE $DAEMON atd && exit 0 || exit $?
   ;;
 *)
   echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload|status}"
   exit 1
  ;;
esac

exit 0

Now you can start and stop your python script using the command /etc/init.d/scriptname start or stop.

Change icon on click (toggle)

If your icon is based on the text in the block (ligatures) rather the class of the block then the following will work. This example uses the Google Material Icons '+' and '-' icons as part of MaterializeCSS.

<a class="btn-class"><i class="material-icons">add</i></a>

$('.btn-class').on('click',function(){
    if ($(this).find('i').text() == 'add'){
        $(this).find('i').text('remove');
    } else {
        $(this).find('i').text('add');
    }
});

Edit: Added missing ); needed for this to function properly.

It also works for JQuery post 1.9 where toggling of functions was deprecated.

SyntaxError: Unexpected token function - Async Await Nodejs

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.

install

npm install --save asyncawait

helloz.js

var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));
}))();

How to export iTerm2 Profiles

Caveats: this answer only allows exports color settings.

iTerm => Preferences => Profiles => Colors => Load Presets => Export

Import shall be similar.

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

I was able to get it to work in IE and FF with jQuery's:

$(window).bind('beforeunload', function(){

});

instead of: unload, onunload, or onbeforeunload

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();

Linq select object from list depending on objects attribute

Answers = Answers.GroupBy(a => a.id).Select(x => x.First());

This will select each unique object by email

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Extract regression coefficient values

Just pass your regression model into the following function:

    plot_coeffs <- function(mlr_model) {
      coeffs <- coefficients(mlr_model)
      mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
      lablist <- names(coeffs)
      text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
    }

Use as follows:

model <- lm(Petal.Width ~ ., data = iris)

plot_coeffs(model)

enter image description here

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

How to do a GitHub pull request

The Simplest GitHub Pull Request is from the web interface without using git.

  1. Register a GitHub account, login then go to the page in the repository you want to change.
  2. Click the pencil icon,

    search for text near the location, make any edits you want then preview them to confirm. Give the proposed change a description up to 50 characters and optionally an extended description then click the Propose file Change button.

  3. If you're reading this you won't have write access to the repository (project folders) so GitHub will create a copy of the repository (actually a branch) in your account. Click the Create pull request button.

  4. Give the Pull Request a description and add any comments then click Create pull request button.

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

Javascript Equivalent to C# LINQ Select

Take a look at fluent, it supports almost everything LINQ does and based on iterables - so it works with maps, generator functions, arrays, everything iterable.

How do you kill a Thread in Java?

In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.

Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.

I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

Certain blocking library methods support interruption.

Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

public void run() {
   try {
      while (!interrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)
      /* Allow thread to exit */
   }
}

public void cancel() { interrupt(); }

Source code adapted from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

What is the difference between "::" "." and "->" in c++

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

Invert match with regexp

Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').

^((?!foo).)*$

This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.

Listing all extras of an Intent

The get(String key) method of Bundle returns an Object. Your best bet is to spin over the key set calling get(String) on each key and using toString() on the Object to output them. This will work best for primitives, but you may run into issues with Objects that do not implement a toString().

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Difference between variable declaration syntaxes in Javascript (including global variables)?

Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window)

This is an example of his idea:

Html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>    
</html>

init.js (Based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

Security of REST authentication schemes

Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).

Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:

XML encryption (W3C standard)

XML Security

How to find minimum value from vector?

template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
    ForwardIterator lowest = first;
    if (first == last) return last;
    while (++first != last)
    if (*first < *lowest) 
        lowest = first;
    return lowest;
}

Convert string to Boolean in javascript

You can try this:

var myBoolean = Boolean.parse(boolString);

What is the difference between concurrency and parallelism?

Concurrency is when two or more tasks can start, run, and complete in overlapping time periods. It doesn't necessarily mean they'll ever both be running at the same instant. For example, multitasking on a single-core machine.

Parallelism is when tasks literally run at the same time, e.g., on a multicore processor.


Quoting Sun's Multithreaded Programming Guide:

  • Concurrency: A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism.

  • Parallelism: A condition that arises when at least two threads are executing simultaneously.

How to determine whether a given Linux is 32 bit or 64 bit?

That system is 32bit. iX86 in uname means it is a 32-bit architecture. If it was 64 bit, it would return

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux

Unit testing with mockito for constructors

Mockito can now mock constructors (since version 3.5.0) https://javadoc.io/static/org.mockito/mockito-core/3.5.13/org/mockito/Mockito.html#mocked_construction

try (MockedConstruction mocked = mockConstruction(Foo.class)) {
   Foo foo = new Foo();
   when(foo.method()).thenReturn("bar");
   assertEquals("bar", foo.method());
   verify(foo).method();
 }

How to check if an NSDictionary or NSMutableDictionary contains a key?

Because nil cannot be stored in Foundation data structures NSNull is sometimes to represent a nil. Because NSNull is a singleton object you can check to see if NSNull is the value stored in dictionary by using direct pointer comparison:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

libaio.so.1: cannot open shared object file

I had the same problem, and it turned out I hadn't installed the library.

this link was super usefull.

http://help.directadmin.com/item.php?id=368

How I can print to stderr in C?

#include<stdio.h>

int main ( ) {
    printf( "hello " );
    fprintf( stderr, "HELP!" );
    printf( " world\n" );
    return 0;
}

$ ./a.exe
HELP!hello  world
$ ./a.exe 2> tmp1
hello  world
$ ./a.exe 1> tmp1
HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.

Convert UTC dates to local time in PHP

Here I am sharing the script, convert UTC timestamp to Indian timestamp:-

    // create a $utc object with the UTC timezone
    $IST = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));

    // change the timezone of the object without changing it's time
    $IST->setTimezone(new DateTimeZone('Asia/Kolkata'));

    // format the datetime
   echo $IST->format('Y-m-d H:i:s T');

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

I had this problem because we where using a DNS name from an old server, ponting to a new server. Using the newserver\inst1 address, worked. both newserver\inst1 and oldserver\inst1 pointed to the same IP.

Java - Including variables within strings?

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

"First foo, then bar"

What is the max size of localStorage values?

I wrote this simple code that is testing localStorage size in bytes.

https://github.com/gkucmierz/Test-of-localStorage-limits-quota

const check = bytes => {
  try {
    localStorage.clear();
    localStorage.setItem('a', '0'.repeat(bytes));
    localStorage.clear();
    return true;
  } catch(e) {
    localStorage.clear();
    return false;
  }
};

Github pages:

https://gkucmierz.github.io/Test-of-localStorage-limits-quota/

I have the same results on desktop chrome, opera, firefox, brave and mobile chrome which is ~5Mbytes

enter image description here

And half smaller result in safari ~2Mbytes

enter image description here

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Count number of matches of a regex in Javascript

('my string'.match(/\s/g) || []).length;

How can I show line numbers in Eclipse?

the eclipse changes the perferences's position

to eclipse -> perferences

How to redirect the output of the time command to a file in Linux?

#!/bin/bash

set -e

_onexit() {
    [[ $TMPD ]] && rm -rf "$TMPD"
}

TMPD="$(mktemp -d)"
trap _onexit EXIT

_time_2() {
    "$@" 2>&3
}

_time_1() {
    time _time_2 "$@"
}

_time() {
    declare time_label="$1"
    shift
    exec 3>&2
    _time_1 "$@" 2>"$TMPD/timing.$time_label"
    echo "time[$time_label]"
    cat "$TMPD/timing.$time_label"
}

_time a _do_something
_time b _do_another_thing
_time c _finish_up

This has the benefit of not spawning sub shells, and the final pipeline has it's stderr restored to the real stderr.

Read lines from a text file but skip the first two lines

Open sFileName For Input As iFileNum

Dim LineNum As Long
LineNum = 0

Do While Not EOF(iFileNum)
  LineNum = LineNum + 1
  Line Input #iFileNum, Fields
  If LineNum > 2 Then
    DoStuffWith(Fields)
  End If
Loop

JQuery Ajax - How to Detect Network Connection error when making Ajax call

here's what I did to alert user in case their network went down or upon page update failure:

  1. I have a div-tag on the page where I put current time and update this tag every 10 seconds. It looks something like this: <div id="reloadthis">22:09:10</div>

  2. At the end of the javascript function that updates the time in the div-tag, I put this (after time is updated with AJAX):

    var new_value = document.getElementById('reloadthis').innerHTML;
    var new_length = new_value.length;
    if(new_length<1){
        alert("NETWORK ERROR!");
    }
    

That's it! You can replace the alert-part with anything you want, of course. Hope this helps.

How do I find the caller of a method using stacktrace or reflection?

This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).

sun.reflect.Reflection

    /** Returns the class of the method <code>realFramesToSkip</code>
        frames up the stack (zero-based), ignoring frames associated
        with java.lang.reflect.Method.invoke() and its implementation.
        The first frame is that associated with this method, so
        <code>getCallerClass(0)</code> returns the Class object for
        sun.reflect.Reflection. Frames associated with
        java.lang.reflect.Method.invoke() and its implementation are
        completely ignored and do not count toward the number of "real"
        frames skipped. */
    public static native Class getCallerClass(int realFramesToSkip);

As far as what the realFramesToSkip value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3), but in my helper utility class I used 4 since there is the added frame of the helper class invocation.

Clear form after submission with jQuery

Just add this to your Action file in some div or td, so that it comes with incoming XML object

    <script type="text/javascript">
    $("#formname").resetForm();
    </script>

Where "formname" is the id of form you want to edit

Angular2: child component access parent class variable/function

You can do this In the parent component declare:

get self(): ParenComponentClass {
        return this;
    }

In the child component,after include the import of ParenComponentClass, declare:

private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
    this._parent = value;
}

get parent(): ParenComponentClass {
    return this._parent;
}

Then in the template of the parent you can do

<childselector [parent]="self"></childselector>

Now from the child you can access public properties and methods of parent using

this.parent

How do I convert a String to a BigInteger?

For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}

Connecting to local SQL Server database using C#

I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.

Hope that helps.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

start/play embedded (iframe) youtube-video on click of an image

This should work perfect just copy this div code

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&amp;hl=en_US&amp;autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>

Syntax for async arrow function

Async arrow functions look like this:

const foo = async () => {
  // do something
}

Async arrow functions look like this for a single argument passed to it:

const foo = async evt => {
  // do something with evt
}

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

The anonymous form works as well:

const foo = async function() {
  // do something
}

An async function declaration looks like this:

async function foo() {
  // do something
}

Using async function in a callback:

const foo = event.onCall(async () => {
  // do something
})

CMake unable to determine linker language with C++

A bit unrelated answer to OP but for people like me with a somewhat similar problem.

Use Case: Ubuntu (C, Clion, Auto-completion):

I had the same error,

CMake Error: Cannot determine link language for target "hello".

set_target_properties(hello PROPERTIES LINKER_LANGUAGE C) help fixes that problem but the headers aren't included to the project and the autocompletion wont work.

This is what i had

cmake_minimum_required(VERSION 3.5)

project(hello)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES ./)

add_executable(hello ${SOURCE_FILES})

set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)

No errors but not what i needed, i realized including a single file as source will get me autocompletion as well as it will set the linker to C.

cmake_minimum_required(VERSION 3.5)

project(hello)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES ./1_helloworld.c)

add_executable(hello ${SOURCE_FILES})

Text Progress Bar in the Console

Try the click library written by the Mozart of Python, Armin Ronacher.

$ pip install click # both 2 and 3 compatible

To create a simple progress bar:

import click

with click.progressbar(range(1000000)) as bar:
    for i in bar:
        pass 

This is what it looks like:

# [###-------------------------------]    9%  00:01:14

Customize to your hearts content:

import click, sys

with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
    for i in bar:
        pass

Custom look:

(_(_)===================================D(_(_| 100000/100000 00:00:02

There are even more options, see the API docs:

 click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)

How to get the index of a maximum element in a NumPy array along one axis

There is argmin() and argmax() provided by numpy that returns the index of the min and max of a numpy array respectively.

Say e.g for 1-D array you'll do something like this

_x000D_
_x000D_
import numpy as np

a = np.array([50,1,0,2])

print(a.argmax()) # returns 0
print(a.argmin()) # returns 2
_x000D_
_x000D_
_x000D_

And similarly for multi-dimensional array

_x000D_
_x000D_
import numpy as np

a = np.array([[0,2,3],[4,30,1]])

print(a.argmax()) # returns 4
print(a.argmin()) # returns 0
_x000D_
_x000D_
_x000D_

Note that these will only return the index of the first occurrence.

How to select distinct rows in a datatable and store into an array

Following single line of code will avoid the duplicate rows of a DataTable:

dataTable.DefaultView.ToTable(true, "employeeid");

Where:

  • first parameter in ToTable() is a boolean which indicates whether you want distinct rows or not.

  • second parameter in the ToTable() is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.

The same can be done from a DataSet, by accessing a specific DataTable:

dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid");

How to assign string to bytes array

Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16([]byte, uint16).

func byte16PutString(s string) [16]byte {
    var a [16]byte
    if len(s) > 16 {
        copy(a[:], s)
    } else {
        copy(a[16-len(s):], s)
    }
    return a
}

var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%v\n", b)

Output:

[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]

Notice how I wanted padding on the left, not the right.

http://play.golang.org/p/7tNumnJaiN

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

Using sed and grep/egrep to search and replace

Another way to do this

find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;

Some help regarding the above command

The find will do the find for you on the current directory indicated by .

-name the name of the file in my case its pom.xml can give wild cards.

-exec execute

sed stream editor

-i ignore case

s is for substitute

/4.6.0.../ String to be searched

/5.0.0.../ String to be replaced

VS 2017 Metadata file '.dll could not be found

I have build 10 projects out of 25 projects in solution individually one by one based on dependencies. Then build the solution. It fixed for me

Adding image inside table cell in HTML

Sould look like:

<td colspan ='4'><img src="\Pics\H.gif" alt="" border='3' height='100' width='100' /></td>

.

<td> need to be closed with </td> <img /> is (in most case) an empty tag. The closing tag is replacede by /> instead... like for br's

<br/>

Your html structure is plain worng (sorry), but this will probably turn into a really bad cross-brwoser compatibility. Also, Encapsulate the value of your attributes with quotes and avoid using upercase in tags.

How to uninstall a Windows Service when there is no executable for it left on the system?

My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.

Get the directory from a file path in java (android)

A better way, use getParent() from File Class..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null

http://developer.android.com/reference/java/io/File.html#getParent%28%29

Set database from SINGLE USER mode to MULTI USER

The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the ALTER query again.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Custom "confirm" dialog in JavaScript?

To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.

This will allow you to follow the same pattern you have in other parts of your code with code such as...

  const confirm = await ui.confirm('Are you sure you want to do this?');

  if(confirm){
    alert('yes clicked');
  } else{
    alert('no clicked');
  }

See codepen for example, or run the snippet below.

https://codepen.io/larnott/pen/rNNQoNp

enter image description here

_x000D_
_x000D_
const ui = {_x000D_
  confirm: async (message) => createConfirm(message)_x000D_
}_x000D_
_x000D_
const createConfirm = (message) => {_x000D_
  return new Promise((complete, failed)=>{_x000D_
    $('#confirmMessage').text(message)_x000D_
_x000D_
    $('#confirmYes').off('click');_x000D_
    $('#confirmNo').off('click');_x000D_
    _x000D_
    $('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });_x000D_
    $('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });_x000D_
    _x000D_
    $('.confirm').show();_x000D_
  });_x000D_
}_x000D_
                     _x000D_
const saveForm = async () => {_x000D_
  const confirm = await ui.confirm('Are you sure you want to do this?');_x000D_
  _x000D_
  if(confirm){_x000D_
    alert('yes clicked');_x000D_
  } else{_x000D_
    alert('no clicked');_x000D_
  }_x000D_
}
_x000D_
body {_x000D_
  margin: 0px;_x000D_
  font-family: "Arial";_x000D_
}_x000D_
_x000D_
.example {_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
input[type=button] {_x000D_
  padding: 5px 10px;_x000D_
  margin: 10px 5px;_x000D_
  border-radius: 5px;_x000D_
  cursor: pointer;_x000D_
  background: #ddd;_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
input[type=button]:hover {_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.confirm {_x000D_
  display: none;_x000D_
}_x000D_
.confirm > div:first-of-type {_x000D_
  position: fixed;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
}_x000D_
.confirm > div:last-of-type {_x000D_
  padding: 10px 20px;_x000D_
  background: white;_x000D_
  position: absolute;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  border-radius: 5px;_x000D_
  border: 1px solid #333;_x000D_
}_x000D_
.confirm > div:last-of-type div:first-of-type {_x000D_
  min-width: 150px;_x000D_
  padding: 10px;_x000D_
}_x000D_
.confirm > div:last-of-type div:last-of-type {_x000D_
  text-align: right;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="example">_x000D_
  <input type="button" onclick="saveForm()" value="Save" />_x000D_
</div>_x000D_
_x000D_
<!-- Hidden confirm markup somewhere at the bottom of page -->_x000D_
_x000D_
<div class="confirm">_x000D_
  <div></div>_x000D_
  <div>_x000D_
    <div id="confirmMessage"></div>_x000D_
    <div>_x000D_
      <input id="confirmYes" type="button" value="Yes" />_x000D_
      <input id="confirmNo" type="button" value="No" />_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making an svg image object clickable with onclick, avoiding absolute positioning

You could use following code:

<style>
    .svgwrapper {
        position: relative;
    }
    .svgwrapper {
        position: absolute;
        z-index: -1;
    }
</style>

<div class="svgwrapper" onClick="function();">
    <object src="blah" />
</div>

b3ng0 wrote similar code but it does not work. z-index of parent must be auto.

Algorithm: efficient way to remove duplicate integers from an array

I've posted this once before on SO, but I'll reproduce it here because it's pretty cool. It uses hashing, building something like a hash set in place. It's guaranteed to be O(1) in axillary space (the recursion is a tail call), and is typically O(N) time complexity. The algorithm is as follows:

  1. Take the first element of the array, this will be the sentinel.
  2. Reorder the rest of the array, as much as possible, such that each element is in the position corresponding to its hash. As this step is completed, duplicates will be discovered. Set them equal to sentinel.
  3. Move all elements for which the index is equal to the hash to the beginning of the array.
  4. Move all elements that are equal to sentinel, except the first element of the array, to the end of the array.
  5. What's left between the properly hashed elements and the duplicate elements will be the elements that couldn't be placed in the index corresponding to their hash because of a collision. Recurse to deal with these elements.

This can be shown to be O(N) provided no pathological scenario in the hashing: Even if there are no duplicates, approximately 2/3 of the elements will be eliminated at each recursion. Each level of recursion is O(n) where small n is the amount of elements left. The only problem is that, in practice, it's slower than a quick sort when there are few duplicates, i.e. lots of collisions. However, when there are huge amounts of duplicates, it's amazingly fast.

Edit: In current implementations of D, hash_t is 32 bits. Everything about this algorithm assumes that there will be very few, if any, hash collisions in full 32-bit space. Collisions may, however, occur frequently in the modulus space. However, this assumption will in all likelihood be true for any reasonably sized data set. If the key is less than or equal to 32 bits, it can be its own hash, meaning that a collision in full 32-bit space is impossible. If it is larger, you simply can't fit enough of them into 32-bit memory address space for it to be a problem. I assume hash_t will be increased to 64 bits in 64-bit implementations of D, where datasets can be larger. Furthermore, if this ever did prove to be a problem, one could change the hash function at each level of recursion.

Here's an implementation in the D programming language:

void uniqueInPlace(T)(ref T[] dataIn) {
    uniqueInPlaceImpl(dataIn, 0);
}

void uniqueInPlaceImpl(T)(ref T[] dataIn, size_t start) {
    if(dataIn.length - start < 2)
        return;

    invariant T sentinel = dataIn[start];
    T[] data = dataIn[start + 1..$];

    static hash_t getHash(T elem) {
        static if(is(T == uint) || is(T == int)) {
            return cast(hash_t) elem;
        } else static if(__traits(compiles, elem.toHash)) {
            return elem.toHash;
        } else {
            static auto ti = typeid(typeof(elem));
            return ti.getHash(&elem);
        }
    }

    for(size_t index = 0; index < data.length;) {
        if(data[index] == sentinel) {
            index++;
            continue;
        }

        auto hash = getHash(data[index]) % data.length;
        if(index == hash) {
            index++;
            continue;
        }

        if(data[index] == data[hash]) {
            data[index] = sentinel;
            index++;
            continue;
        }

        if(data[hash] == sentinel) {
            swap(data[hash], data[index]);
            index++;
            continue;
        }

        auto hashHash = getHash(data[hash]) % data.length;
        if(hashHash != hash) {
            swap(data[index], data[hash]);
            if(hash < index)
                index++;
        } else {
            index++;
        }
    }


    size_t swapPos = 0;
    foreach(i; 0..data.length) {
        if(data[i] != sentinel && i == getHash(data[i]) % data.length) {
            swap(data[i], data[swapPos++]);
        }
    }

    size_t sentinelPos = data.length;
    for(size_t i = swapPos; i < sentinelPos;) {
        if(data[i] == sentinel) {
            swap(data[i], data[--sentinelPos]);
        } else {
            i++;
        }
    }

    dataIn = dataIn[0..sentinelPos + start + 1];
    uniqueInPlaceImpl(dataIn, start + swapPos + 1);
}

How can I remove all objects but one from the workspace in R?

I just spent several hours hunting for the answer to a similar but slightly different question - I needed to be able to delete all objects in R (including functions) except a handful of vectors.

One way to do this:

rm(list=ls()[! ls() %in% c("a","c")])

Where the vectors that I want to keep are named 'a' and 'c'.

Hope this helps anyone searching for the same solution!

How to mount a host directory in a Docker container

Using command-line :

docker run -it --name <WHATEVER> -p <LOCAL_PORT>:<CONTAINER_PORT> -v <LOCAL_PATH>:<CONTAINER_PATH> -d <IMAGE>:<TAG>

Using docker-compose.yaml :

version: '2'
  services:
    cms:
       image: <IMAGE>:<TAG>
       ports:
       - <LOCAL_PORT>:<CONTAINER_PORT>
       volumes:
       - <LOCAL_PATH>:<CONTAINER_PATH>

Assume :

  • IMAGE: k3_s3
  • TAG: latest
  • LOCAL_PORT: 8080
  • CONTAINER_PORT: 8080
  • LOCAL_PATH: /volume-to-mount
  • CONTAINER_PATH: /mnt

Examples :

  1. First create /volume-to-mount. (Skip if exist)
$ mkdir -p /volume-to-mount
  1. docker-compose -f docker-compose.yaml up -d
version: '2'
  services:
    cms:
       image: ghost-cms:latest
       ports:
       - 8080:8080
       volumes:
       - /volume-to-mount:/mnt
  1. Verify your container :
docker exec -it CONTAINER_ID ls -la /mnt

How to get the primary IP address of the local machine on Linux and OS X?

The following will work on Linux but not OSX.

This doesn't rely on DNS at all, and it works even if /etc/hosts is not set correctly (1 is shorthand for 1.0.0.0):

ip route get 1 | awk '{print $NF;exit}'

or avoiding awk and using Google's public DNS at 8.8.8.8 for obviousness:

ip route get 8.8.8.8 | head -1 | cut -d' ' -f8

A less reliable way: (see comment below)

hostname -I | cut -d' ' -f1

Count specific character occurrences in a string

Here is the direct code that solves the OP's problem:

        Dim str As String = "the little red hen"

        Dim total As Int32

        Dim Target As String = "e"
        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = str.IndexOf(Target, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        End If

        MessageBox.Show(CStr(total))

Now, this is a handy function to solve the OP's problem:

    Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
        Dim total As Int32

        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        Else
            Return total
        End If
    End Function

Example of using the function:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim str As String = "the little red hen"

    MessageBox.Show(CStr(CountOccurrence(str, "e")))
    ' It will return 4
End Sub

How to Select Every Row Where Column Value is NOT Distinct

The thing that is incorrect with your query is that you are grouping by email and name, that forms a group of each unique set of email and name combined together and hence

aaron and [email protected]
christy and [email protected]
john and [email protected]

are treated as 3 different groups rather all belonging to 1 single group.

Please use the query as given below :

select emailaddress,customername from customers where emailaddress in
(select emailaddress from customers group by emailaddress having count(*) > 1)

POST Content-Length exceeds the limit

I disagree, but the solution to increase the file size in php.ini or .htaccess won't work if the user sends a file larger than allowed by the server application.

I suggest validating this on the front end. For example:

_x000D_
_x000D_
$(document).ready(function() {
    $ ('#your_input_file_id').bind('change', function() {
        var fileSize = this.files[0].size/1024/1024;
        if (fileSize > 2) { // 2M
            alert('Your custom message for max file size exceeded');
            $('#your_input_file_id').val('');
        }
    });
});
_x000D_
_x000D_
_x000D_

Insert if not exists Oracle

The statement is called MERGE. Look it up, I'm too lazy.

Beware, though, that MERGE is not atomic, which could cause the following effect (thanks, Marius):

SESS1:

create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;

SESS2: insert into t1 values(2, 2);

SESS1:

MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);

SESS2: commit;

SESS1: ORA-00001

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

After perusing this myself (Using the Text Color Classes in Connor Leech's answer)

Be warned to pay careful attention to the "navbar-text" class.

To get green text on the navbar for example, you might be tempted to do this:

<p class="navbar-text text-success">Some Text Here</p>

This will NOT work!! "navbar-text" overrides the color and replaces it with the standard navbar text color.

The correct way to do it is to nest the text in a second element, EG:

<p class="navbar-text"><span class="text-success">Some Text Here</span></p>

or in my case (as I wanted emphasized text)

<p class="navbar-text"><strong class="text-success">Some Text Here</strong></p>

When you do it this way, you get properly aligned text with the height of the navbar and you get to change the color too.

What's the regular expression that matches a square bracket?

In general, when you need a character that is "special" in regexes, just prefix it with a \. So a literal [ would be \[.

How can I determine the status of a job?

The tasks above work but I have seen many records in the msdb.dbo.sysjobactivity where run_Requested_date is not null and stop_execution_date is null ---- and the job is not currently running.

I would recommend running the following script to clear out all of the bogus entries (make sure no jobs are running at the time).

SQL2008:

    delete activity
    from msdb.dbo.sysjobs_view job  
    inner join msdb.dbo.sysjobactivity activity on job.job_id = activity.job_id 
    where  
        activity.run_Requested_date is not null  
    and activity.stop_execution_date is null  

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I got the same error, on debian6, when I had not yet installed php5-mysql.

So I installed it, then restarted apache2

apt-get install php5-mysql
/etc/init.d/apache2 restart

Then the error went away.

If you have the same error on Ubuntu, instead of:

/etc/init.d/apache2 restart  

Type:

service apache2 restart

Maven does not find JUnit tests to run

junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...

<dependency>
    <groupId>org.eclipse.orbit</groupId>
    <artifactId>org.junit</artifactId>
    <version>4.11.0</version>
    <type>bundle</type>
    <scope>test</scope>
</dependency>

Absolute vs relative URLs

In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can use this for the Width of your DataTemplate:

Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"

Make sure your DataTemplate root has Margin="0" (you can use some panel as the root and set the Margin to the children of that root)

String to HashMap JAVA

try

 String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    HashMap<String,Integer> hm =new HashMap<String,Integer>();
    for(String s1:s.split(",")){
       String[] s2 = s1.split(":");
        hm.put(s2[0], Integer.parseInt(s2[1]));
    }

What is the Windows equivalent of the diff command?

DiffUtils is probably your best bet. It's the Windows equivalent of diff.

To my knowledge there are no built-in equivalents.

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

Delete from a table based on date

You could use:

DELETE FROM tableName
where your_date_column < '2009-01-01';

but Keep in mind that the above is really

DELETE FROM tableName
    where your_date_column < '2009-01-01 00:00:00';

Not

 DELETE FROM tableName
        where your_date_column < '2009-01-01 11:59';

TextFX menu is missing in Notepad++

It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)

If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll) inside the plugins folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.

Passing parameters to click() & bind() event in jquery?

An alternative for the bind() method.

Use the click() method, do something like this:

commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

commentbtn.click({id: 10, name: "João"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

Id = 10, Name = João

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

How can I delete a file from a Git repository?

go to your project dir and type:

git filter-branch --tree-filter 'rm -f <deleted-file>' HEAD

after that push --force for delete file from all commits.

git push origin --force --all

How to get the fields in an Object via reflection?

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

<%: DateTime.Today.ToShortDateString() %>

How to verify CuDNN installation?

On Ubuntu 20.04LTS:

cat /usr/local/cuda/include/cudnn_version.h | grep CUDNN_MAJOR

returned the expected results

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

Install redis on your system first -

brew install redis

then start the redis server -

redis-server

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

$("#form1").validate is not a function

I had the same issue, and yes I had my jquery included first followed by the jquery validate script. I had no idea what was wrong. Turns out I was using a validate url that had moved. I figured this out by doing the following:

  1. Open firefox
  2. Open firebug
  3. Click the NET tab in firebug. This will show you all the resources that get loaded.
  4. Load your page.
  5. Check the loaded resources and see if both your jquery & jquery.validate.js loaded.

In my situation I had a 403 Forbidden error when trying to obtain (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js which is used in the example on http://rocketsquared.com/wiki/Plugins/Validation ).

Turns out the that link (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js) had moved to http://view.jquery.com/trunk/plugins/validate/jquery.validate.js (Firebug told me this when I loaded the file locally as opposed to on my web server).

NOTE: I tried using microsoft's CDN link also but it failed when I tried to load the javascript file in the browser with the correct url, there was some odd issue going on with the CDN site.

Latest jQuery version on Google's CDN

Here's an updated link.

There are updated now and then, just keep checking for the latest version.

How to configure log4j.properties for SpringJUnit4ClassRunner?

I have the log4j.properties configured properly. That's not the problem. After a while I discovered that the problem was in Eclipse IDE which had an old build in "cache" and didn't create a new one (Maven dependecy problem). I had to build the project manually and now it works.

Why use deflate instead of gzip for text files served by Apache?

mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.

If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.

less than 10 add 0 to number

$('#detect').html( toGeo(apX, screenX)  + latT +', '+ toGeo(apY, screenY) + lonT  );

function toGeo(d, max) {
   var c = '';

   var r = d/max * 180;
   var deg = Math.floor(r);
   if(deg < 10) deg = '0' + deg;
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   if(min < 10) min = '0' + min;
   c += min + "' ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   if(sec < 10) sec = '0' + sec;
   c += sec + """;

   return c;
}

True/False vs 0/1 in MySQL

Bit is also an option if tinyint isn't to your liking. A few links:

Not surprisingly, more info about numeric types is available in the manual.

One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/

And a quote from the comment section of the article above:

  • TINYINT(1) isn’t a synonym for bit(1).
  • TINYINT(1) can store -9 to 9.
  • TINYINT(1) UNSIGNED: 0-9
  • BIT(1): 0, 1. (Bit, literally).

Edit: This edit (and answer) is only remotely related to the original question...

Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).

Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)

True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)

Multi-Column Join in Hibernate/JPA Annotations

Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:

Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)

So if you are unwilling to make AnEmbeddableObject the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.

Visual Studio 2015 is very slow

My Visual Studio 2015 RTM was also very slow using ReSharper 9.1.2, but it has worked fine since I upgraded to 9.1.3 (see ReSharper 9.1.3 to the Rescue). Perhaps a cue.

One more cue. A ReSharper 9.2 version was made available to:

refines integration with Visual Studio 2015 RTM, addressing issues discovered in versions 9.1.2 and 9.1.3

Deserialize JSON with C#

If you're using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.

The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.

Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu EditPaste SpecialPaste JSON as classes).

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Response
{
    public List<Person> Data { get; set; }
}

Then you can deserialize using:

var people = JsonSerializer.Deserialize<Response>(json);

If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:

var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

How to deal with a slow SecureRandom generator?

It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.

If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with Dan Dyer's response about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.

I would think that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's eStream project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.

Edit: here's some cryptographic course notes on RNG I found on the 'net that look very relevant to this topic.

Python class input argument

Python Classes

class name:
    def __init__(self, name):
        self.name = name
        print("name: "+name)

Somewhere else:

john = name("john")

Output:
name: john

How to remove a field completely from a MongoDB document?

you can also do this in aggregation by using project at 3.4

{$project: {"tags.words": 0} }

Convert DataSet to List

var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
    Name = r.Field<string>("Name"),
    Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable

Display image at 50% of its "native" size

It's somewhat weird, but it seems that Webkit, at least in newest stable version of Chrome, supports Microsoft's zoom property. The good news is that its behaviour is closer to what you want.

Unfortunately DOM clientWidth and similar properties still return the original values as if the image was not resized.

_x000D_
_x000D_
// hack: wait a moment for img to load_x000D_
setTimeout(function() {_x000D_
   var img = document.getElementsByTagName("img")[0];_x000D_
   document.getElementById("c").innerHTML = "clientWidth, clientHeight = " + img.clientWidth + ", " +_x000D_
      img.clientHeight;_x000D_
}, 1000);
_x000D_
img {_x000D_
  zoom: 50%;_x000D_
}_x000D_
/* -- not important below -- */_x000D_
#t {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
  background-color: #F88;_x000D_
}_x000D_
#s {_x000D_
  width: 200px;_x000D_
  height: 150px;_x000D_
  background-color: #8F8;_x000D_
}
_x000D_
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAIAAABi1XKVAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKuGlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjarZZnVFPZHsX/9970QktAQEroTZAiXXoNIEQ6iEpIKIEQY0hAERWVwREcUVREsAzgKIiCjSJjQSzYBsUC9gEZFJRxsCAqKu8DQ3jvrfc+vLXe/6671m/tdc4++9z7ZQPQHnDFYiGqBJApkkrCA7xZsXHxLOLvgAMKqAIFlLi8LLEXhxMC/3kQgI89gAAA3LXkisVC+N9GmZ+cxQNAOACQxM/iZQIgpwCQdp5YIgXApABgkCMVSwGwcgBgSmLj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AAB2LFhQLACAjYAYFgAAXUIAAIBgAQAgWAAAYO0ghgUAsCEPCy4WAABdQgAAQJcQAAAPCwAAIFgAAIAuIQDA3jwsuFgAAHQJAQAAXUIAADwsAACAYAEAALqEAAB787DgYgEA4GEBAIC5PSzYAAAAwQIAAHQJAQD262HBxwIAwMMCAAAze1hwsAAAttMlBAAAdAkBAAAeFgAAHhYAAMDDAgAAeFgAADvzsOBiAQDgYQEAgLk9LNgAAAAPCwAA4GEBAOBhAQAAPCwAAICHBQCwNw8LLhYAAB4WAACY28OCDQAANsL/DwAPm8TOXgqx/AAAAABJRU5ErkJggg==" />_x000D_
<div id="s">div with explicit size for comparison 200px by 150px</div>_x000D_
<div id="t">div with explicit size for comparison 400px by 300px</div>_x000D_
<div id="c"></div>
_x000D_
_x000D_
_x000D_

Position absolute but relative to parent

Incase someone wants to postion a child div directly under a parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen

HQL Hibernate INNER JOIN

You can do it without having to create a real Hibernate mapping. Try this:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team

Python AttributeError: 'module' object has no attribute 'Serial'

I accidentally installed 'serial' (sudo python -m pip install serial) instead of 'pySerial' (sudo python -m pip install pyserial), which lead to the same error.

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

How to comment a block in Eclipse?

for java code

if you want comments single line then put double forward slash before code of single line manually or by pressing Ctrl +/ example: //System.Out.println("HELLO");

and for multi-line comments, Select code how much you want to comments and then press

Shift+CTRL+/

Now for XML code comments use Select code first and then press Shift+CTRL+/ for both single line and multi-line comments

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Since Docker 17.05 COPY is used with the --from flag in multi-stage builds to copy artifacts from previous build stages to the current build stage.

from the documentation

Optionally COPY accepts a flag --from=<name|index> that can be used to set the source location to a previous build stage (created with FROM .. AS ) that will be used instead of a build context sent by the user.

How to change DatePicker dialog color for Android 5.0

For Changing Year list item text color (SPECIFIC FOR ANDROID 5.0)

Just set certain text color in your date picker dialog style. For some reason setting flag yearListItemTextAppearance doesn't reflect any change on year list.

<item name="android:textColor">@android:color/black</item>

Why use argparse rather than optparse?

There are also new kids on the block!

  • Besides the already mentioned deprecated optparse. [DO NOT USE]
  • argparse was also mentioned, which is a solution for people not willing to include external libs.
  • docopt is an external lib worth looking at, which uses a documentation string as the parser for your input.
  • click is also external lib and uses decorators for defining arguments. (My source recommends: Why Click)
  • python-inquirer For selection focused tools and based on Inquirer.js (repo)

If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!

How do I use Maven through a proxy?

Also note that some plugins (remote-resources comes to mind) use a really old library that only accepts proxy configuration through MAVEN_OPTS;

-Dhttp.proxyHost=<host> -Dhttp.proxyPort=<port> -Dhttps.proxyHost=<host> -Dhttps.proxyPort=<port>

You might be stuck on auth for this one.

How to fix corrupted git repository?

If you have a remote configured and you have / don't care about losing some unpushed code, you can do :

git fetch && git reset --hard

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

First some code, then the explanaition. The official docs describing this are here.

import { trigger, transition, animate, style } from '@angular/animations'

@Component({
  ...
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

In your template:

<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>

I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.

The animations part in human language:

  • We're naming this animation 'slideInOut'.
  • When the element is added (:enter), we do the following:
  • ->Immediately move the element 100% up (from itself), to appear off screen.
  • ->then animate the translateY value until we are at 0%, where the element would naturally be.

  • When the element is removed, animate the translateY value (currently 0), to -100% (off screen).

The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.

Hope this helps!

iPhone App Icons - Exact Radius?

When designing my app icons with Photoshop, I have found that no integer corner radius fits the device's mask exactly.

What I do now is create an empty project with Xcode, set a completely white PNG file as the icon, and turn off the preset bevel & gloss. Then, I run the app and take a screenshot of the home screen. Now, you can easily create a mask from that image, which you can use in Photoshop. This will get you perfectly rounded corners.

How to get the name of a class without the package?

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

It is actually stripping the package information from the name, but this is hidden from you.

Best data type to store money values in MySQL

I prefer to use BIGINT, and store the values in by multiply with 100, so that it will become integer.

For e.g., to represent a currency value of 93.49, the value shall be stored as 9349, while displaying the value we can divide by 100 and display. This will occupy less storage space.

Caution:
Mostly we don't perform currency * currency multiplication, in case if we are doing it then divide the result with 100 and store, so that it returns to proper precision.

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

pandas: How do I split text in a column into multiple rows?

Differently from Dan, I consider his answer quite elegant... but unfortunately it is also very very inefficient. So, since the question mentioned "a large csv file", let me suggest to try in a shell Dan's solution:

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df['col'].apply(lambda x : pd.Series(x.split(' '))).head()"

... compared to this alternative:

time python -c "import pandas as pd;
from scipy import array, concatenate;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(concatenate(df['col'].apply( lambda x : [x.split(' ')]))).head()"

... and this:

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(dict(zip(range(3), [df['col'].apply(lambda x : x.split(' ')[i]) for i in range(3)]))).head()"

The second simply refrains from allocating 100 000 Series, and this is enough to make it around 10 times faster. But the third solution, which somewhat ironically wastes a lot of calls to str.split() (it is called once per column per row, so three times more than for the others two solutions), is around 40 times faster than the first, because it even avoids to instance the 100 000 lists. And yes, it is certainly a little ugly...

EDIT: this answer suggests how to use "to_list()" and to avoid the need for a lambda. The result is something like

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(df.col.str.split().tolist()).head()"

which is even more efficient than the third solution, and certainly much more elegant.

EDIT: the even simpler

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(list(df.col.str.split())).head()"

works too, and is almost as efficient.

EDIT: even simpler! And handles NaNs (but less efficient):

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df.col.str.split(expand=True).head()"

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

Get host domain from URL?

 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

INPUT = "https://stackoverflow.com/questions/";

OUTPUT = "https://stackoverflow.com/";

Using a RegEx to match IP addresses in Python

str = "255.255.255.255"
print(str.split('.'))

list1 = str.split('.')

condition=0

if len(list1)==4:
    for i in list1:
        if int(i)>=0 and int(i)<=255:
            condition=condition+1

if condition!=4:
    print("Given number is not IP address")
else:
    print("Given number is valid IP address")

How to change line width in IntelliJ (from 120 character)

It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore.

Intellij 2018.3:

hard wrap - idea will automatically wrap the line as you type, this is not what the OP was asking for

visual guide - just a vertical line indicating a characters limit, default is 120


If you just want to change the visual guide from the default 120 to lets say 80 in my example:

enter image description here

Also you can change the color or the visual guide by clicking on the Foreground:

enter image description here

Lastly, you can also set the visual guide for all file types (unless specified) here:

enter image description here

How do I convert NSInteger to NSString datatype?

Modern Objective-C

An NSInteger has the method stringValue that can be used even with a literal

NSString *integerAsString1 = [@12 stringValue];

NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];

Very simple. Isn't it?

Swift

var integerAsString = String(integer)

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

What's the difference between a mock & stub?

A fake is a generic term that can be used to describe either a stub or a mock object (handwritten or otherwise), because they both look like the real object.

Whether a fake is a stub or a mock depends on how it’s used in the current test. If it’s used to check an interaction (asserted against), it’s a mock object. Otherwise, it’s a stub.

Fakes makes sure test runs smoothly. It means that reader of your future test will understand what will be the behavior of the fake object, without needing to read its source code (without needing to depend on external resource).

What does test run smoothly mean?
Forexample in below code:

 public void Analyze(string filename)
        {
            if(filename.Length<8)
            {
                try
                {
                    errorService.LogError("long file entered named:" + filename);
                }
                catch (Exception e)
                {
                    mailService.SendEMail("[email protected]", "ErrorOnWebService", "someerror");
                }
            }
        }

You want to test mailService.SendEMail() method, to do that you need to simulate an Exception in you test method, so you just need to create a Fake Stub errorService class to simulate that result, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another External Dependency ErrorService class.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

How to parse date string to Date?

I had this issue, and I set the Locale to US, then it work.

static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);

for String "Sun Jul 08 00:06:30 UTC 2012"

how to mysqldump remote db from local machine

As I haven't seen it at serverfault yet, and the answer is quite simple:

Change:

ssh -f -L3310:remote.server:3306 [email protected] -N

To:

ssh -f -L3310:localhost:3306 [email protected] -N

And change:

mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name

To:

mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name

(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)

edit: well, to elaborate: if host is set to localhost, a configured (or default) --socket option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.

Retrieve the commit log for a specific line in a file?

An extremely easy way to do this is by using vim-fugitive. Just open the file in vim, select the line(s) you're interested in using V, then enter

:Glog

Now you can use :cnext and :cprev to see all the revisions of the file where that line is modified. At any point, enter :Gblame to see the sha, author, and date info.

Set port for php artisan.php serve

Laravel 5.8 to 8.0 and above

The SERVER_PORT environment variable will be picked up and used by Laravel. Either do:

export SERVER_PORT="8080"
php artisan serve

Or set SERVER_PORT=8080 in your .env file.

Earlier versions of Laravel:

For port 8080:

 php artisan serve --port=8080

And if you want to run it on port 80, you probably need to sudo:

sudo php artisan serve --port=80

Permutations in JavaScript?

Here's a very short solution, that only works for 1 or 2 long strings. It's a oneliner, and it's blazing fast, using ES6 and not depending on jQuery. Enjoy:

var p = l => l.length<2 ? [l] : l.length==2 ? [l[0]+l[1],l[1]+l[0]] : Function('throw Error("unimplemented")')();

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

Execute PHP script in cron job

You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser (man runuser). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.

I provide a detailed answer how to use cron in this stackoverflow post.

How to write a cron that will run a script every day at midnight?

Android: TextView: Remove spacing and padding on top and bottom

See this:

Align ImageView with EditText horizontally

It seems that the background image of EditText has some transparent pixels which also add padding.

A solution is to change the default background of EditText to something else (or nothing, but no background for a EditText is probably not acceptable). That's can be made setting android:background XML attribute.

android:background="@drawable/myEditBackground"

Finding multiple occurrences of a string within a string in Python

The following function finds all the occurrences of a string inside another while informing the position where each occurrence is found.

You can call the function using the test cases in the table below. You can try with words, spaces and numbers all mixed up.

The function works well with overlaping characteres.

|         theString          | aString |
| -------------------------- | ------- |
| "661444444423666455678966" |  "55"   |
| "661444444423666455678966" |  "44"   |
| "6123666455678966"         |  "666"  |
| "66123666455678966"        |  "66"   |

Calling examples:
1. print("Number of occurrences: ", find_all("123666455556785555966", "5555"))
   
   output:
           Found in position:  7
           Found in position:  14
           Number of occurrences:  2
   
2. print("Number of occorrences: ", find_all("Allowed Hello Hollow", "ll "))

   output:
          Found in position:  1
          Found in position:  10
          Found in position:  16
          Number of occurrences:  3

3. print("Number of occorrences: ", find_all("Aaa bbbcd$#@@abWebbrbbbbrr 123", "bbb"))

   output:
         Found in position:  4
         Found in position:  21
         Number of occurrences:  2
         

def find_all(theString, aString):
    count = 0
    i = len(aString)
    x = 0

    while x < len(theString) - (i-1): 
        if theString[x:x+i] == aString:        
            print("Found in position: ", x)
            x=x+i
            count=count+1
        else:
            x=x+1
    return count

Best way to remove items from a collection

@smaclell asked why reverse iteration was more efficient in in a comment to @sambo99.

Sometimes it's more efficient. Consider you have a list of people, and you want to remove or filter all customers with a credit rating < 1000;

We have the following data

"Bob" 999
"Mary" 999
"Ted" 1000

If we were to iterate forward, we'd soon get into trouble

for( int idx = 0; idx < list.Count ; idx++ )
{
    if( list[idx].Rating < 1000 )
    {
        list.RemoveAt(idx); // whoops!
    }
}

At idx = 0 we remove Bob, which then shifts all remaining elements left. The next time through the loop idx = 1, but list[1] is now Ted instead of Mary. We end up skipping Mary by mistake. We could use a while loop, and we could introduce more variables.

Or, we just reverse iterate:

for (int idx = list.Count-1; idx >= 0; idx--)
{
    if (list[idx].Rating < 1000)
    {
        list.RemoveAt(idx);
    }
}

All the indexes to the left of the removed item stay the same, so you don't skip any items.

The same principle applies if you're given a list of indexes to remove from an array. In order to keep things straight you need to sort the list and then remove the items from highest index to lowest.

Now you can just use Linq and declare what you're doing in a straightforward manner.

list.RemoveAll(o => o.Rating < 1000);

For this case of removing a single item, it's no more efficient iterating forwards or backwards. You could also use Linq for this.

int removeIndex = list.FindIndex(o => o.Name == "Ted");
if( removeIndex != -1 )
{
    list.RemoveAt(removeIndex);
}

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

ImportError: No module named PyQt4.QtCore

I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run

from PyQt4.QtCore import SIGNAL

from a python interpreter but only without activating my virtualenv.

The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?

Sorting dictionary keys in python

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

error, string or binary data would be truncated when trying to insert

A 2016/2017 update will show you the bad value and column.

enter image description here

A new trace flag will swap the old error for a new 2628 error and will print out the column and offending value. Traceflag 460 is available in the latest cumulative update for 2016 and 2017:

https://support.microsoft.com/en-sg/help/4468101/optional-replacement-for-string-or-binary-data-would-be-truncated

Just make sure that after you've installed the CU that you enable the trace flag, either globally/permanently on the server: enter image description here

...or with DBCC TRACEON:

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql?view=sql-server-ver15

How to measure elapsed time

Per the Android docs SystemClock.elapsedRealtime() is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.

The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.

  • SystemClock.elapsedRealtime() and SystemClock.elapsedRealtimeNanos() are the best bet for calculating general purpose elapsed time.
  • SystemClock.uptimeMillis() and System.nanoTime() are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime().
  • Stay away from System.currentTimeMillis() as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis() to not always be accurate.

When the game starts:

long startTime = SystemClock.elapsedRealtime();

When the game ends:

long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;

Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis() as the basis of the time sent to setText(...).

Also, instead of using Timer, you might want to look into using TimerTask, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

how to query LIST using linq

I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.

Example:
enter image description here

How to acces external json file objects in vue.js app

Just assign the import to a data property

<script>
      import json from './json/data.json'
      export default{
          data(){
              return{
                  myJson: json
              }
          }
      }
</script>

then loop through the myJson property in your template using v-for

<template>
    <div>
        <div v-for="data in myJson">{{data}}</div>
    </div>
</template>

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>
          import MY_JSON from './json/data.json'
          export default{
              //custom option named myJson
                 myJson: MY_JSON
          }
    </script>

then loop through the custom option in your template using $options:

<template>
        <div>
            <div v-for="data in $options.myJson">{{data}}</div>
        </div>
    </template>

What's a quick way to comment/uncomment lines in Vim?

I mark the first and last lines (ma and mb), and then do :'a,'bs/^# //

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

In my case, when I run df -i it shows me that my number of inodes are full and then I have to delete some of the small files or folder. Otherwise it will not allow us to create files or folders once inodes get full.

All you have to do is delete files or folder that has not taken up full space but is responsible for filling inodes.

Example to use shared_ptr?

The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!

typedef std::shared_ptr<gate> Ptr   
vector<Ptr> myConatiner; 
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);

for (auto& element : myConatiner)
    element->run();

Get random integer in range (x, y]?

Random generator = new Random(); 
int i = generator.nextInt(10) + 1;

Java SimpleDateFormat for time zone with a colon separator?

if you used the java 7, you could have used the following Date Time Pattern. Seems like this pattern is not supported in the Earlier version of java.

String dateTimeString  = "2010-03-01T00:00:00-08:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = df.parse(dateTimeString);

For More information refer to the SimpleDateFormat documentation.

How to override the path of PHP to use the MAMP path?

Probably too late to comment but here's what I did when I ran into issues with setting php PATH for my XAMPP installation on Mac OSX

  1. Open up the file .bash_profile (found under current user folder) using the available text editor.
  2. Add the path as below:

export PATH=/path/to/your/php/installation/bin:leave/rest/of/the/stuff/untouched/:$PATH

  1. Save your .bash_profile and re-start your Mac.

Explanation: Terminal / Mac tries to run a search on the PATHS it knows about, in a hope of finding the program, when user initiates a program from the "Terminal", hence the trick here is to make the terminal find the php, the user intends to, by pointing it to the user's version of PHP at some bin folder, installed by the user.

Worked for me :)

P.S I'm still a lost sheep around my new Computer ;)

Calculate distance between two latitude-longitude points? (Haversine formula)

The haversine is definitely a good formula for probably most cases, other answers already include it so I am not going to take the space. But it is important to note that no matter what formula is used (yes not just one). Because of the huge range of accuracy possible as well as the computation time required. The choice of formula requires a bit more thought than a simple no brainer answer.

This posting from a person at nasa, is the best one I found at discussing the options

http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html

For example, if you are just sorting rows by distance in a 100 miles radius. The flat earth formula will be much faster than the haversine.

HalfPi = 1.5707963;
R = 3956; /* the radius gives you the measurement unit*/

a = HalfPi - latoriginrad;
b = HalfPi - latdestrad;
u = a * a + b * b;
v = - 2 * a * b * cos(longdestrad - longoriginrad);
c = sqrt(abs(u + v));
return R * c;

Notice there is just one cosine and one square root. Vs 9 of them on the Haversine formula.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

Bytes of a string in Java

According to How to convert Strings to and from UTF8 byte arrays in Java:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked

Mocking member variables of a class using Mockito

Lots of others have already advised you to rethink your code to make it more testable - good advice and usually simpler than what I'm about to suggest.

If you can't change the code to make it more testable, PowerMock: https://code.google.com/p/powermock/

PowerMock extends Mockito (so you don't have to learn a new mock framework), providing additional functionality. This includes the ability to have a constructor return a mock. Powerful, but a little complicated - so use it judiciously.

You use a different Mock runner. And you need to prepare the class that is going to invoke the constructor. (Note that this is a common gotcha - prepare the class that calls the constructor, not the constructed class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class})

Then in your test set-up, you can use the whenNew method to have the constructor return a mock

whenNew(Second.class).withAnyArguments().thenReturn(mock(Second.class));

Create Hyperlink in Slack

Recently it became possible (but with an odd workaround).

To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).

Message in Slack

On Mac

I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.

Link creation in Pages

On Windows

I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.

Universal

Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.

enter image description here

Getting Data from Android Play Store

I've coded a small Node.js module to scrape app and list data from Google Play: google-play-scraper

var gplay = require('google-play-scrapper');

gplay.List({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    num: 2
  }).then(console.log);

Results:

 [ { url: 'https://play.google.com/store/apps/details?id=com.playappking.busrush',
    appId: 'com.playappking.busrush',
    title: 'Bus Rush',
    developer: 'Play App King',
    icon: 'https://lh3.googleusercontent.com/R6hmyJ6ls6wskk5hHFoW02yEyJpSG36il4JBkVf-Aojb1q4ZJ9nrGsx6lwsRtnTqfA=w340',
    score: 3.9,
    price: '0',
    free: false },
  { url: 'https://play.google.com/store/apps/details?id=com.yodo1.crossyroad',
    appId: 'com.yodo1.crossyroad',
    title: 'Crossy Road',
    developer: 'Yodo1 Games',
    icon: 'https://lh3.googleusercontent.com/doHqbSPNekdR694M-4rAu9P2B3V6ivff76fqItheZGJiN4NBw6TrxhIxCEpqgO3jKVg=w340',
    score: 4.5,
    price: '0',
    free: false } ]

How to get a user's time zone?

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let gmtAbbreviation = (localTimeZoneAbbreviation / 60)
        return "\(gmtAbbreviation)"
}

You can get current time zone abbreviation.

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.

I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).

Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.

TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

Remove duplicated rows using dplyr

For completeness’ sake, the following also works:

df %>% group_by(x) %>% filter (! duplicated(y))

However, I prefer the solution using distinct, and I suspect it’s faster, too.

Getting "cannot find Symbol" in Java project in Intellij

I know this thread is old but, another solution was to run

$ mvn clean install -Dmaven.test.skip=true

And on IntelliJ do CMD + Shift + A (mac os) -> type "Reimport all Maven projects".

If that doesn't work, try forcing maven dependencies to be re-downloaded

$ mvn clean -U install -Dmaven.test.skip=true

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

Open popup and refresh parent page on close popup

You can access parent window using 'window.opener', so, write something like the following in the child window:

<script>
    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Python idiom to return first item or None

Several people have suggested doing something like this:

list = get_list()
return list and list[0] or None

That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.

I've created this bug in my own code one too many times !

How can a add a row to a data frame in R?

Not terribly elegant, but:

data.frame(rbind(as.matrix(df), as.matrix(de)))

From documentation of the rbind function:

For rbind column names are taken from the first argument with appropriate names: colnames for a matrix...

How to set a default value for an existing column

ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn

Exporting PDF with jspdf not rendering CSS

jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.

include these two files in script on your page :

<script type="text/javascript" src="html2canvas.js"></script>
  <script type="text/javascript" src="jspdf.min.js"></script>
  <script type="text/javascript">
  function genPDF()
  {
   html2canvas(document.body,{
   onrendered:function(canvas){

   var img=canvas.toDataURL("image/png");
   var doc = new jsPDF();
   doc.addImage(img,'JPEG',20,20);
   doc.save('test.pdf');
   }

   });

  }
  </script>

You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf

make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.

<a href="javascript:genPDF()">Download PDF</a>  

It will work perfectly.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How do you fade in/out a background color using jquery?

Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'}) to change the color.

As others have written, some of this can be done using the jQuery UI library as well.

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

How do I set up a private Git repository on GitHub? Is it even possible?

Since January 7th, 2019, it is possible: unlimited free private repositories on GitHub!
... But for up to three collaborators per private repository.

Nat Friedman just announced it by twitter:

Today(!) we’re thrilled to announce unlimited free private repos for all GitHub users, and a new simplified Enterprise offering:

"New year, new GitHub: Announcing unlimited free private repos and unified Enterprise offering"

For the first time, developers can use GitHub for their private projects with up to three collaborators per repository for free.

Many developers want to use private repos to apply for a job, work on a side project, or try something out in private before releasing it publicly.
Starting today, those scenarios, and many more, are possible on GitHub at no cost.

Public repositories are still free (of course—no changes there) and include unlimited collaborators.