Programs & Examples On #Website deployment

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

Preferred way of getting the selected item of a JComboBox

Don't cast unless you must. There's nothign wrong with calling toString().

Bootstrap tab activation with JQuery

Add an id attribute to a html tag

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Then using JQuery

$("#tab_aaa").tab('show');

How to change default install location for pip

Open Terminal and type:

pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages

except instead of

/Users/Bob/Library/Python/3.8/lib/python/site-packages

you would use whatever directory you want.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

UIImage is a wrapper the bytes are CGImage or CIImage

According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage with a CGImage (explicitly or implicitly), it will return NULL if the UIImage is backed by a CIImage and vice-versa.

Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.

Common tricks to getting around this issue

As stated your options are

  • UIImagePNGRepresentation or JPEG
  • Determine if image has CGImage or CIImage backing data and get it there

Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.

My recommendation, try CIImage

While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling

- render:toBitmap:rowBytes:bounds:format:colorSpace:

As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.

Selecting data frame rows based on partial string match in a column

Another option would be to simply use grepl function:

df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]

df <- data.frame(name = c('bob','robert','peter'),
                 id = c(1,2,3)
                 )

# name id
# 2 robert  2
# 3  peter  3

error: ‘NULL’ was not declared in this scope

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

Good Linux (Ubuntu) SVN client

Generally I just use the command line for svn, it's the fastest and easiest way to do it to be honest, I'd recommend you try it.
Before you dismiss this, you should probably ask yourself if there is really any feature that you need a GUI for, and whether you would prefer to open up a GUI app and download the files, or just type svn co svn://site-goes-here.org/trunk

You can easily add, remove, move, commit, copy or update files with simple commands given with svn help, so for most users it is more than enough.

What is the difference between a stored procedure and a view?

@Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.

Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using @tmpTable1. Depending on what you want to tell it to do.

A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.

Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

C# Version Of SQL LIKE

myString.Contain("someString");  // equal with myString LIKE '%someString%'
myString.EndWith("someString");  // equal with myString LIKE '%someString'
myString.StartWith("someString");  // equal with myString LIKE 'someString%'

How can I control Chromedriver open window size?

Use this for your custom size:

driver.manage().window().setSize(new Dimension(1024,768));

you can change your dimensions as per your requirements.

Spring Boot not serving static content

Given resources under src/main/resources/static, if you add this code, then all static content from src/main/resources/static will be available under "/":

@Configuration
public class StaticResourcesConfigurer implements WebMvcConfigurer {
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/");
    }
}

Actionbar notification count icon (badge) like Google has

When you use toolbar:

....
private void InitToolbar() {
    toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    toolbartitle = (TextView) findViewById(R.id.titletool);
    toolbar.inflateMenu(R.menu.show_post);
    toolbar.setOnMenuItemClickListener(this);
    Menu menu = toolbar.getMenu();
    MenuItem menu_comments = menu.findItem(R.id.action_comments);
    MenuItemCompat
            .setActionView(menu_comments, R.layout.menu_commentscount);
    View v = MenuItemCompat.getActionView(menu_comments);
    v.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Your Action
        }
    });
    comment_count = (TextView) v.findViewById(R.id.count);
}

and in your load data call refreshMenu():

private void refreshMenu() {
    comment_count.setVisibility(View.VISIBLE);
    comment_count.setText("" + post_data.getComment_count());
}

How to get file extension from string in C++

Is this too simple of a solution?

#include <iostream>
#include <string>

int main()
{
  std::string fn = "filename.conf";
  if(fn.substr(fn.find_last_of(".") + 1) == "conf") {
    std::cout << "Yes..." << std::endl;
  } else {
    std::cout << "No..." << std::endl;
  }
}

RestTemplate: How to send URL and query parameters together

One-liner using TestRestTemplate.exchange function with parameters map.

restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])

The params map initialized like this is a groovy initializer*

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

Convert a string to integer with decimal in Python

What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

s = '234.67'
i = int(round(float(s)))

Otherwise, just do:

s = '234.67'
i = int(float(s))

Favorite Visual Studio keyboard shortcuts

I am surprised not to find this one on the list as I use it all the time:

Ctrl + K, Ctrl + M - Implement method stub.

Write a call to a non-existent method, and then use that shortcut to create the method in the right place, with the right parameters and return value, but with a method body that just throws a NotImplementedException.

Great for top-down coding.

Oracle Differences between NVL and Coalesce

COALESCE is more modern function that is a part of ANSI-92 standard.

NVL is Oracle specific, it was introduced in 80's before there were any standards.

In case of two values, they are synonyms.

However, they are implemented differently.

NVL always evaluates both arguments, while COALESCE usually stops evaluation whenever it finds the first non-NULL (there are some exceptions, such as sequence NEXTVAL):

SELECT  SUM(val)
FROM    (
        SELECT  NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This runs for almost 0.5 seconds, since it generates SYS_GUID()'s, despite 1 being not a NULL.

SELECT  SUM(val)
FROM    (
        SELECT  COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This understands that 1 is not a NULL and does not evaluate the second argument.

SYS_GUID's are not generated and the query is instant.

error: passing xxx as 'this' argument of xxx discards qualifiers

The objects in the std::set are stored as const StudentT. So when you try to call getId() with the const object the compiler detects a problem, mainly you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId() might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates an error message.

The solution is simple: make the functions const as:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

This is necessary because now you can call getId() and getName() on const objects as:

void f(const StudentT & s)
{
     cout << s.getId();   //now okay, but error with your versions
     cout << s.getName(); //now okay, but error with your versions
}

As a sidenote, you should implement operator< as :

inline bool operator< (const StudentT & s1, const StudentT & s2)
{
    return  s1.getId() < s2.getId();
}

Note parameters are now const reference.

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

Use the updated version of Firebase and avoid extras. This is enough (but if you need to use storage space or .. you should add them too)

//FIREBASE
implementation 'com.google.firebase:firebase-core:17.2.0'
 implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
//ADMob
implementation 'com.google.android.gms:play-services-ads:18.2.0'
//PUSH NOTIFICATION
implementation 'com.google.firebase:firebase-messaging:20.0.0'
implementation 'com.google.firebase:firebase-core:17.2.0'

and update the google-services :

 classpath 'com.google.gms:google-services:4.3.2'

Matplotlib (pyplot) savefig outputs blank image

let's me give a more detail example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

enter image description here

How to compare strings in sql ignoring case?

SELECT STRCMP("string1", "string2");

this returns 0 if the strings are equal.

  • If string1 = string2, this function returns 0 (ignoring the case)
  • If string1 < string2, this function returns -1
  • If string1 > string2, this function returns 1

https://www.w3schools.com/sql/func_mysql_strcmp.asp

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

Difference of keywords 'typename' and 'class' in templates?

There is no difference between using OR ; i.e. it is a convention used by C++ programmers. I myself prefer as it more clearly describes it use; i.e. defining a template with a specific type :)

Note: There is one exception where you do have to use class (and not typename) when declaring a template template parameter:

template <template class T> class C { }; // valid!

template <template typename T> class C { }; // invalid!

In most cases, you will not be defining a nested template definition, so either definition will work -- just be consistent in your use...

pyplot scatter plot marker size

Because other answers here claim that s denotes the area of the marker, I'm adding this answer to clearify that this is not necessarily the case.

Size in points^2

The argument s in plt.scatter denotes the markersize**2. As the documentation says

s : scalar or array_like, shape (n, ), optional
size in points^2. Default is rcParams['lines.markersize'] ** 2.

This can be taken literally. In order to obtain a marker which is x points large, you need to square that number and give it to the s argument.

So the relationship between the markersize of a line plot and the scatter size argument is the square. In order to produce a scatter marker of the same size as a plot marker of size 10 points you would hence call scatter( .., s=100).

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot([0],[0], marker="o",  markersize=10)
ax.plot([0.07,0.93],[0,0],    linewidth=10)
ax.scatter([1],[0],           s=100)

ax.plot([0],[1], marker="o",  markersize=22)
ax.plot([0.14,0.86],[1,1],    linewidth=22)
ax.scatter([1],[1],           s=22**2)

plt.show()

Connection to "area"

So why do other answers and even the documentation speak about "area" when it comes to the s parameter?

Of course the units of points**2 are area units.

  • For the special case of a square marker, marker="s", the area of the marker is indeed directly the value of the s parameter.
  • For a circle, the area of the circle is area = pi/4*s.
  • For other markers there may not even be any obvious relation to the area of the marker.

enter image description here

In all cases however the area of the marker is proportional to the s parameter. This is the motivation to call it "area" even though in most cases it isn't really.

Specifying the size of the scatter markers in terms of some quantity which is proportional to the area of the marker makes in thus far sense as it is the area of the marker that is perceived when comparing different patches rather than its side length or diameter. I.e. doubling the underlying quantity should double the area of the marker.

enter image description here

What are points?

So far the answer to what the size of a scatter marker means is given in units of points. Points are often used in typography, where fonts are specified in points. Also linewidths is often specified in points. The standard size of points in matplotlib is 72 points per inch (ppi) - 1 point is hence 1/72 inches.

It might be useful to be able to specify sizes in pixels instead of points. If the figure dpi is 72 as well, one point is one pixel. If the figure dpi is different (matplotlib default is fig.dpi=100),

1 point == fig.dpi/72. pixels

While the scatter marker's size in points would hence look different for different figure dpi, one could produce a 10 by 10 pixels^2 marker, which would always have the same number of pixels covered:

enter image description here enter image description here enter image description here

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

If you are interested in a scatter in data units, check this answer.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

finally, I got a solution if you are getting:-

**npm WARN tar ENOENT: no such file or directory,.......**

then it is no issue of npm or its version it is os permission issue to resolve this you need to use below command:-

sudo chown -R $USER:$USER *

additional

sudo chmod -R 777 *

then run:-

sudo npm i 

Copy folder recursively in Node.js

If you want to copy all contents of source directory recursively then you need to pass recursive option as true and try catch is documented way by fs-extra for sync

As fs-extra is complete replacement of fs so you don't need to import the base module

const fs = require('fs-extra');
let sourceDir = '/tmp/src_dir';
let destDir = '/tmp/dest_dir';
try {
  fs.copySync(sourceDir, destDir, { recursive: true })
  console.log('success!')
} catch (err) {
  console.error(err)
}

Passing javascript variable to html textbox

You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem() method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.

Passing an integer by reference in Python

class Obj:
  def __init__(self,a):
    self.value = a
  def sum(self, a):
    self.value += a
    
a = Obj(1)
b = a
a.sum(1)
print(a.value, b.value)// 2 2

"Cannot instantiate the type..."

Queue is an Interface not a class.

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

Multidimensional Lists in C#

Why don't you use a List<People> instead of a List<List<string>> ?

Django: OperationalError No Such Table

If anyone finds that any of the suggested:

python manage.py makemigrations

python manage.py migrate

python manage.py migrate --run-syncdb

fail, you may need to add a folder named "migrations" inside the app directory, and create an empty __init__.py file.

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

How to refresh a page with jQuery by passing a parameter to URL

You can use Javascript URLSearchParams.

var url = new URL(window.location.href);
url.searchParams.set('single','');
window.location.href = url.href;

[UPDATE]: If IE support is a need, check this thread:

SCRIPT5009: 'URLSearchParams' is undefined in IE 11

Thanks @john-m to talk about the IE support

Add "Are you sure?" to my excel button, how can I?

Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

OSX - How to auto Close Terminal window after the "exit" command executed.

I tried several variations of the answers here. No matter what I try, I can always find a use case where the user is prompted to close Terminal.

Since my script is a simple (drutil -drive 2 tray open -- to open a specific DVD drive), the user does not need to see the Terminal window while the script runs.

My solution was to turn the script into an app, which runs the script without displaying a Terminal window. The added benefit is that any terminal windows that are already open stay open, and if none are open, then Terminal doesn't stay resident after the script ends. It doesn't seem to launch Terminal at all to run the bash script.

I followed these instructions to turn my script into an app: https://superuser.com/a/1354541/162011

Unable to run Java GUI programs with Ubuntu

In my case

-Djava.awt.headless=true

was set (indirectly by a Maven configuration). I had to actively use

-Djava.awt.headless=false

to override this.

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

Assign one struct to another in C

Did you mean "Complex" as in complex number with real and imaginary parts? This seems unlikely, so if not you'd have to give an example since "complex" means nothing specific in terms of the C language.

You will get a direct memory copy of the structure; whether that is what you want depends on the structure. For example if the structure contains a pointer, both copies will point to the same data. This may or may not be what you want; that is down to your program design.

To perform a 'smart' copy (or a 'deep' copy), you will need to implement a function to perform the copy. This can be very difficult to achieve if the structure itself contains pointers and structures that also contain pointers, and perhaps pointers to such structures (perhaps that's what you mean by "complex"), and it is hard to maintain. The simple solution is to use C++ and implement copy constructors and assignment operators for each structure or class, then each one becomes responsible for its own copy semantics, you can use assignment syntax, and it is more easily maintained.

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

Numpy: Checking if a value is NaT

can check for NaT with pandas.isnull:

>>> import numpy as np
>>> import pandas as pd
>>> pd.isnull(np.datetime64('NaT'))
True

If you don't want to use pandas you can also define your own function (parts are taken from the pandas source):

nat_as_integer = np.datetime64('NAT').view('i8')

def isnat(your_datetime):
    dtype_string = str(your_datetime.dtype)
    if 'datetime64' in dtype_string or 'timedelta64' in dtype_string:
        return your_datetime.view('i8') == nat_as_integer
    return False  # it can't be a NaT if it's not a dateime

This correctly identifies NaT values:

>>> isnat(np.datetime64('NAT'))
True

>>> isnat(np.timedelta64('NAT'))
True

And realizes if it's not a datetime or timedelta:

>>> isnat(np.timedelta64('NAT').view('i8'))
False

In the future there might be an isnat-function in the numpy code, at least they have a (currently open) pull request about it: Link to the PR (NumPy github)

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Can I use conditional statements with EJS templates (in JMVC)?

Yes , You can use conditional statement with EJS like if else , ternary operator or even switch case also

For Example

Ternary operator : <%- role == 'Admin' ? 'Super Admin' : role == 'subAdmin' ? 'Sub Admin' : role %>

Switch Case

<% switch (role) {
case 'Admin' : %>
        Super Admin
        <% break;

case 'eventAdmin' : %>
        Event Admin
        <% break;

case 'subAdmin' : %>
        Sub Admin
        <% break;

} %>

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

Are there any style options for the HTML5 Date picker?

Currently, there is no cross browser, script-free way of styling a native date picker.

As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.

I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".

It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.

While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.

Add one year in current date PYTHON

AGSM's answer shows a convenient way of solving this problem using the python-dateutil package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:

from datetime import date

def add_years(d, years):
    """Return a date that's `years` years after the date (or datetime)
    object `d`. Return the same calendar date (month and day) in the
    destination year, if it exists, otherwise use the following day
    (thus changing February 29 to March 1).

    """
    try:
        return d.replace(year = d.year + years)
    except ValueError:
        return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))

If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:

        return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))

jquery ui Dialog: cannot call methods on dialog prior to initialization

My case is different, it fails because of the scope of 'this':

//this fails:
$("#My-Dialog").dialog({
  ...
  close: ()=>{
    $(this).dialog("close");
  }
});

//this works:
$("#My-Dialog").dialog({
  ...
  close: function(){
    $(this).dialog("close");
  }
});

Cron job every three days

It would be simpler if you configured it to just run e.g. on monday and thursdays, which would give it a 3 and 4 day break.

Otherwise configure it to run daily, but make your php cron script exit early with:

if (! (date("z") % 3)) {
     exit;
}

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

In my case, as I have installed the ConEmu Terminal for Window 7, it creates the ca-bundle during installation at C:\Program Files\Git\mingw64\ssl\certs.

Thus, I have to run the following commands on terminal to make it work:

$ git config --global http.sslbackend schannel
$ git config --global http.sslcainfo /mingw64/ssl/certs/ca-bundle.crt

Hence, my C:\Program Files\Git\etc\gitconfig contains the following:

[http]
    sslBackend = schannel
    sslCAinfo = /mingw64/ssl/certs/ca-bundle.crt

Also, I chose same option as mentioned here when installing the Git.

Hope that helps!

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I tried the steps mentioned by @bcmoney but for me the current version was already set to the latest version. In my it was Java8.

I had various versions of java installed (java6, java7 and java8). I got the same error but instead of 1.5 and 1.7 i got 1.7 and 1.8. I uninstalled java6 on my windows 8.1 machine. After which i tried java -version in command prompt and the error did not appear.

I am not sure whether this is the right answer but it worked for me so i thought it would help the community too.

Read MS Exchange email in C#

Um,

I might be a bit too late here but isn't this kinda the point to EWS ?

https://msdn.microsoft.com/en-us/library/dd633710(EXCHG.80).aspx

Takes about 6 lines of code to get the mail from a mailbox:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

//service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );

service.AutodiscoverUrl( "[email protected]" );

FindItemsResults<Item> findResults = service.FindItems(
   WellKnownFolderName.Inbox,
   new ItemView( 10 ) 
);

foreach ( Item item in findResults.Items )
{
   Console.WriteLine( item.Subject );
}

How can I mix LaTeX in with Markdown?

It is possible to parse Markdown in Lua using the Lunamark code (see its Github repo), meaning that Markdown may be parsed directly by macros in Luatex and supports conversion to many of the formats supported by Pandoc (i.e., the library is well-suited to use in lualatex, context, Metafun, Plain Luatex, and texlua scripts).

The project was started by John MacFarlane, author of Pandoc, and the tool's development tracks that of Pandoc quite closely and is of similar (i.e., excellent) quality.

Khaled Hosny wrote a Context module, providing convenient macro support. Michal's answer to the Is there any package with Markdown support? question gives code providing similar support for Latex.

Get index of a row of a pandas dataframe as an integer

The easier is add [0] - select first value of list with one element:

dfb = df[df['A']==5].index.values.astype(int)[0]
dfbb = df[df['A']==8].index.values.astype(int)[0]

dfb = int(df[df['A']==5].index[0])
dfbb = int(df[df['A']==8].index[0])

But if possible some values not match, error is raised, because first value not exist.

Solution is use next with iter for get default parameetr if values not matched:

dfb = next(iter(df[df['A']==5].index), 'no match')
print (dfb)
4

dfb = next(iter(df[df['A']==50].index), 'no match')
print (dfb)
no match

Then it seems need substract 1:

print (df.loc[dfb:dfbb-1,'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

Another solution with boolean indexing or query:

print (df[(df['A'] >= 5) & (df['A'] < 8)])
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

print (df.query('A >= 5 and A < 8'))
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

Create File If File Does Not Exist

This works as well for me

string path = TextFile + ".txt";

if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
    File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
    w.WriteLine("{0}", "Hello World");
    w.Flush();
    w.Close();
}

How to save a new sheet in an existing excel file, using Pandas?

#This program is to read from excel workbook to fetch only the URL domain names and write to the existing excel workbook in a different sheet..
#Developer - Nilesh K
import pandas as pd
from openpyxl import load_workbook #for writting to the existing workbook

df = pd.read_excel("urlsearch_test.xlsx")

#You can use the below for the relative path.
# r"C:\Users\xyz\Desktop\Python\

l = [] #To make a list in for loop

#begin
#loop starts here for fetching http from a string and iterate thru the entire sheet. You can have your own logic here.
for index, row in df.iterrows():
    try: 
        str = (row['TEXT']) #string to read and iterate
        y = (index)
        str_pos = str.index('http') #fetched the index position for http
        str_pos1 = str.index('/', str.index('/')+2) #fetched the second 3rd position of / starting from http
        str_op = str[str_pos:str_pos1] #Substring the domain name
        l.append(str_op) #append the list with domain names

    #Error handling to skip the error rows and continue.
    except ValueError:
            print('Error!')
print(l)
l = list(dict.fromkeys(l)) #Keep distinct values, you can comment this line to get all the values
df1 = pd.DataFrame(l,columns=['URL']) #Create dataframe using the list
#end

#Write using openpyxl so it can be written to same workbook
book = load_workbook('urlsearch_test.xlsx')
writer = pd.ExcelWriter('urlsearch_test.xlsx',engine = 'openpyxl')
writer.book = book
df1.to_excel(writer,sheet_name = 'Sheet3')
writer.save()
writer.close()

#The below can be used to write to a different workbook without using openpyxl
#df1.to_excel(r"C:\Users\xyz\Desktop\Python\urlsearch1_test.xlsx",index='false',sheet_name='sheet1')

How to convert any Object to String?

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3

pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

code:

ToStringBuilder.reflectionToString(yourObject)

nodemon not found in npm

for linux try

sudo npm install -g nodemon

for windows open powershell or cmd as administration

npm install -g nodemon

How to get the nth occurrence in a string?

I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>Checking regex</title>_x000D_
<script>_x000D_
var string1 = "123xxx5yyy1234ABCxxxabc";_x000D_
var search1 = /\d+/;_x000D_
var search2 = /\d/;_x000D_
var search3 = /abc/;_x000D_
function printList(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList)</p>");_x000D_
   var list = string1.match(search);_x000D_
   if (list == null) {_x000D_
      document.writeln("<p>No matches</p>");_x000D_
      return;_x000D_
   }_x000D_
   // document.writeln("<p>" + list.toString() + "</p>");_x000D_
   // document.writeln("<p>" + typeof(list1) + "</p>");_x000D_
   // document.writeln("<p>" + Array.isArray(list1) + "</p>");_x000D_
   // document.writeln("<p>" + list1 + "</p>");_x000D_
   var count = list.length;_x000D_
   document.writeln("<ul>");_x000D_
   for (i = 0; i < count; i++) {_x000D_
      document.writeln("<li>" +  "  " + list[i] + "   length=" + list[i].length + _x000D_
          " first position=" + string1.indexOf(list[i]) + "</li>");_x000D_
   }_x000D_
   document.writeln("</ul>");_x000D_
}_x000D_
function printList2(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");_x000D_
   var index = 0;_x000D_
   var partial = string1;_x000D_
   document.writeln("<ol>");_x000D_
   for (j = 0; j < 100; j++) {_x000D_
       var found = partial.match(search);_x000D_
       if (found == null) {_x000D_
          // document.writeln("<p>not found</p>");_x000D_
          break;_x000D_
       }_x000D_
       var size = found[0].length;_x000D_
       var loc = partial.search(search);_x000D_
       var actloc = loc + index;_x000D_
       document.writeln("<li>" + found[0] + "  length=" + size + "  first position=" + actloc);_x000D_
       // document.writeln("  " + partial + "  " + loc);_x000D_
       partial = partial.substring(loc + size);_x000D_
       index = index + loc + size;_x000D_
       document.writeln("</li>");_x000D_
   }_x000D_
   document.writeln("</ol>");_x000D_
_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p>Original string is <script>document.writeln(string1);</script></p>_x000D_
<script>_x000D_
   printList(/\d+/g);_x000D_
   printList2(/\d+/);_x000D_
   printList(/\d/g);_x000D_
   printList2(/\d/);_x000D_
   printList(/abc/g);_x000D_
   printList2(/abc/);_x000D_
   printList(/ABC/gi);_x000D_
   printList2(/ABC/i);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I use $scope.$watch and $scope.$apply in AngularJS?

Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:

1) They are all event-driven things. (I hear the laugh, but read on)

If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.

2) $watch is "on-click".

What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...

3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.

4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)

Now, let's make it visual. Picture this to make it even more easy to grab the idea:

In a restaurant,

- WAITERS

are supposed to take orders from customers, this is

$watch(
  function(){return orders;},
  function(){Kitchen make it;}
);

- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()

- OWNER has the ultimate power to drive everyone upon request, this is $apply()

How do I find the number of arguments passed to a Bash script?

that value is contained in the variable $#

Android Layout Weight

weight values 0-1 share distribution of available space (after setting layout_width="0px") in proportion to the weight value. View elements with weight not specified (no weight entry) get weight 0 which means they get no expansion.

A simple alternative with no weight entries needed is to attach marquee to a view with text which tells it to expand from minimum needed for the text (wrap_content) to space available EditText: android:layout_width="wrap_content" android:ellipsize="marquee"

How to refresh or show immediately in datagridview after inserting?

You can set the datagridview DataSource to null and rebind it again.

private void button1_Click(object sender, EventArgs e)
{
    myAccesscon.ConnectionString = connectionString;

    dataGridView.DataSource = null;
    dataGridView.Update();
    dataGridView.Refresh();
    OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
    myAccesscon.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable bookings = new DataTable();
    da.Fill(bookings);
    dataGridView.DataSource = bookings;
    myAccesscon.Close();
}

Regular expression for validating names and surnames?

This somewhat helps:

^[a-zA-Z]'?([a-zA-Z]|\.| |-)+$

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

IE11 Document mode defaults to IE7. How to reset?

Thanks to all the investigations of Lance, I could find a solution to my problem. It possibly had to do with my ISP.

To summarize:

  • Internet sites were displayed in the Intranet zone
  • Because of that the document mode was defaulted to 5 or 7 instead of Edge

I unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.

Now the sites are correctly marked as Internet sites (instead of Intranet sites).

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

How to break out of a loop from inside a switch?

You can use goto.

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;

Jmeter - Run .jmx file through command line and get the summary report in a excel

This worked for me on mac os High sierra 10.13.6, java 8 64-bit, jmeter 4.0

$  jmeter -n --testfile /path/to/Test_Plan.jmx

Sample output:

Creating summariser <summary>
Created the tree successfully using ./src/test/jmeter/Test_Plan.jmx
Starting the test @ Fri Aug 24 17:18:18 PDT 2018 (1535156298333)
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary =     10 in 00:00:09 =    1.1/s Avg:  6666 Min:  1000 Max:  8950 Err:     
0 (0.00%)
Tidying up ...    @ Fri Aug 24 17:18:28 PDT 2018 (1535156308049)
... end of run

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

In my case, I only had read access to the .git/FETCH_HEAD file. I had to do "sudo chmod g+w .git/FETCH_HEAD" in order to be able to do a pull request.

Show image using file_get_contents

You can do that, or you can use the readfile function, which outputs it for you:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

How can I get the browser's scrollbar sizes?

Here's the more concise and easy to read solution based on offset width difference:

function getScrollbarWidth(): number {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

See the JSFiddle.

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Random shuffling of an array

Simplest code to shuffle:

import java.util.*;
public class ch {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        ArrayList<Integer> l=new ArrayList<Integer>(10);
        for(int i=0;i<10;i++)
            l.add(sc.nextInt());
        Collections.shuffle(l);
        for(int j=0;j<10;j++)
            System.out.println(l.get(j));       
    }
}

What are the true benefits of ExpandoObject?

One advantage is for binding scenarios. Data grids and property grids will pick up the dynamic properties via the TypeDescriptor system. In addition, WPF data binding will understand dynamic properties, so WPF controls can bind to an ExpandoObject more readily than a dictionary.

Interoperability with dynamic languages, which will be expecting DLR properties rather than dictionary entries, may also be a consideration in some scenarios.

PHP: Possible to automatically get all POSTed data?

As long as you don't want any special formatting: yes.

foreach ($_POST as $key => $value) 
    $body .= $key . ' -> ' . $value . '<br>';

Obviously, more formatting would be necessary, however that's the "easy" way. Unless I misunderstood the question.

You could also do something like this (and if you like the format, it's certainly easier):

$body = print_r($_POST, true);

Counting Line Numbers in Eclipse

For eclipse(Indigo), install (codepro).

After installation: - Right click on your project - Choose codepro tools --> compute metrics - And you will get your answer in a Metrics tab as Number of Lines.

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

jQuery DataTables: control table width

I have had numerous issues with the column widths of datatables. The magic fix for me was including the line

table-layout: fixed;

this css goes with the overall css of the table. For example, if you have declared the datatables like the following:

LoadTable = $('#LoadTable').dataTable.....

then the magic css line would go in the class Loadtable

#Loadtable {
margin: 0 auto;
clear: both;
width: 100%;
table-layout: fixed;

}

How to convert a normal Git repository to a bare one?

Here is a little BASH function you can add to your .bashrc or .profile on a UNIX based system. Once added and the shell is either restarted or the file is reloaded via a call to source ~/.profile or source ~/.bashrc.

function gitToBare() {
  if [ -d ".git" ]; then
    DIR="`pwd`"
    mv .git ..
    rm -fr *
    mv ../.git .
    mv .git/* .
    rmdir .git

    git config --bool core.bare true
    cd ..
    mv "${DIR}" "${DIR}.git"

    printf "[\x1b[32mSUCCESS\x1b[0m] Git repository converted to "
    printf "bare and renamed to\n  ${DIR}.git\n"
    cd "${DIR}.git"
  else
    printf "[\x1b[31mFAILURE\x1b[0m] Cannot find a .git directory\n"
  fi
}

Once called within a directory containing a .git directory, it will make the appropriate changes to convert the repository. If there is no .git directory present when called, a FAILURE message will appear and no file system changes will happen.

Why does NULL = NULL evaluate to false in SQL server

The equality test, for example, in a case statement when clause, can be changed from

XYZ = NULL 

to

XYZ IS NULL

If I want to treat blanks and empty string as equal to NULL I often also use an equality test like:

(NULLIF(ltrim( XYZ ),'') IS NULL)

Encrypt and decrypt a string in C#?

AES Algorithm:

public static class CryptographyProvider
    {
        public static string EncryptString(string plainText, out string Key)
        {
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");

            using (Aes _aesAlg = Aes.Create())
            {
                Key = Convert.ToBase64String(_aesAlg.Key);
                ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);

                using (MemoryStream _memoryStream = new MemoryStream())
                {
                    _memoryStream.Write(_aesAlg.IV, 0, 16);
                    using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))
                        {
                            _streamWriter.Write(plainText);
                        }
                        return Convert.ToBase64String(_memoryStream.ToArray());
                    }
                }
            }
        }
        public static string DecryptString(string cipherText, string Key)
        {

            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(Key))
                throw new ArgumentNullException("Key");

            string plaintext = null;

            byte[] _initialVector = new byte[16];
            byte[] _Key = Convert.FromBase64String(Key);
            byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);
            byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];

            Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);
            Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);

            using (Aes _aesAlg = Aes.Create())
            {
                _aesAlg.Key = _Key;
                _aesAlg.IV = _initialVector;
                ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);

                using (MemoryStream _memoryStream = new MemoryStream(_originalString))
                {
                    using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader _streamReader = new StreamReader(_cryptoStream))
                        {
                            plaintext = _streamReader.ReadToEnd();
                        }
                    }
                }
            }
            return plaintext;
        }
    }

Set Encoding of File to UTF8 With BOM in Sublime Text 3

I can't set "UTF-8 with BOM" in the corner button either, but I can change it from the menu bar.

"File"->"Save with encoding"->"UTF-8 with BOM"

Javascript - Track mouse position

ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Error: Cannot access file bin/Debug/... because it is being used by another process

In my case was that I have enable "Show All Files". Visual Studio 2017

Creating an XmlNode/XmlElement in C# without an XmlDocument?

I would recommend to use XDoc and XElement of System.Xml.Linq instead of XmlDocument stuff. This would be better and you will be able to make use of the LINQ power in querying and parsing your XML:

Using XElement, your ToXml() method will look like the following:

public XElement ToXml()
{
    XElement element = new XElement("Song",
                        new XElement("Artist", "bla"),
                        new XElement("Title", "Foo"));

    return element;
}

List of all unique characters in a string?

For completeness sake, here's another recipe that sorts the letters as a byproduct of the way it works:

>>> from itertools import groupby
>>> ''.join(k for k, g in groupby(sorted("aaabcabccd")))
'abcd'

How to get a float result by dividing two integer values using T-SQL?

It's not necessary to cast both of them. Result datatype for a division is always the one with the higher data type precedence. Thus the solution must be:

SELECT CAST(1 AS float) / 3

or

SELECT 1 / CAST(3 AS float)

How to prevent caching of my Javascript file?

Add a random query string to the src

You could either do this manually by incrementing the querystring each time you make a change:

<script src="test.js?version=1"></script>

Or if you are using a server side language, you could automatically generate this:

ASP.NET:

<script src="test.js?rndstr=<%= getRandomStr() %>"></script>

More info on cache-busting can be found here:

https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/

Algorithm to find Largest prime factor of a number

Python Iterative approach by removing all prime factors from the number

def primef(n):
    if n <= 3:
        return n
    if n % 2 == 0:
        return primef(n/2)
    elif n % 3 ==0:
        return primef(n/3)
    else:
        for i in range(5, int((n)**0.5) + 1, 6):
            #print i
            if n % i == 0:
                return primef(n/i)
            if n % (i + 2) == 0:
                return primef(n/(i+2))
    return n

How to make lists contain only distinct element in Python?

Modified versions of http://www.peterbe.com/plog/uniqifiers-benchmark

To preserve the order:

def f(seq): # Order preserving
  ''' Modified version of Dave Kirby solution '''
  seen = set()
  return [x for x in seq if x not in seen and not seen.add(x)]

OK, now how does it work, because it's a little bit tricky here if x not in seen and not seen.add(x):

In [1]: 0 not in [1,2,3] and not print('add')
add
Out[1]: True

Why does it return True? print (and set.add) returns nothing:

In [3]: type(seen.add(10))
Out[3]: <type 'NoneType'>

and not None == True, but:

In [2]: 1 not in [1,2,3] and not print('add')
Out[2]: False

Why does it print 'add' in [1] but not in [2]? See False and print('add'), and doesn't check the second argument, because it already knows the answer, and returns true only if both arguments are True.

More generic version, more readable, generator based, adds the ability to transform values with a function:

def f(seq, idfun=None): # Order preserving
  return list(_f(seq, idfun))

def _f(seq, idfun=None):  
  ''' Originally proposed by Andrew Dalke '''
  seen = set()
  if idfun is None:
    for x in seq:
      if x not in seen:
        seen.add(x)
        yield x
  else:
    for x in seq:
      x = idfun(x)
      if x not in seen:
        seen.add(x)
        yield x

Without order (it's faster):

def f(seq): # Not order preserving
  return list(set(seq))

CryptographicException 'Keyset does not exist', but only through WCF

If you use ApplicationPoolIdentity for your application pool, you may have problem with specifying permission for that "virtual" user in registry editor (there is not such user in system).

So, use subinacl - command-line tool that enables set registry ACL's, or something like this.

Android Room - simple select query - Cannot access database on the main thread

You can allow database access on the main thread but only for debugging purpose, you shouldn't do this on production.

Here is the reason.

Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

The project cannot be built until the build path errors are resolved.

Goto to Project=>Build Automatically . Make sure it is ticked

Does Python have an argc argument?

You're better off looking at argparse for argument parsing.

http://docs.python.org/dev/library/argparse.html

Just makes it easy, no need to do the heavy lifting yourself.

C# get and set properties for a List Collection

If I understand your request correctly, you have to do the following:

public class Section 
{ 
    public String Head
    {
        get
        {
            return SubHead.LastOrDefault();
        }
        set
        {
            SubHead.Add(value);
        }

    public List<string> SubHead { get; private set; }
    public List<string> Content { get; private set; }
} 

You use it like this:

var section = new Section();
section.Head = "Test string";

Now "Test string" is added to the subHeads collection and will be available through the getter:

var last = section.Head; // last will be "Test string"

Hope I understood you correctly.

LINQ - Full Outer Join

I think there are problems with most of these, including the accepted answer, because they don't work well with Linq over IQueryable either due to doing too many server round trips and too much data returns, or doing too much client execution.

For IEnumerable I don't like Sehe's answer or similar because it has excessive memory use (a simple 10000000 two list test ran Linqpad out of memory on my 32GB machine).

Also, most of the others don't actually implement a proper Full Outer Join because they are using a Union with a Right Join instead of Concat with a Right Anti Semi Join, which not only eliminates the duplicate inner join rows from the result, but any proper duplicates that existed originally in the left or right data.

So here are my extensions that handle all of these issues, generate SQL as well as implementing the join in LINQ to SQL directly, executing on the server, and is faster and with less memory than others on Enumerables:

public static class Ext {
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from left in leftItems
               join right in rightItems on leftKeySelector(left) equals rightKeySelector(right) into temp
               from right in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from right in rightItems
               join left in leftItems on rightKeySelector(right) equals leftKeySelector(left) into temp
               from left in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    public static IEnumerable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        var hashLK = new HashSet<TKey>(from l in leftItems select leftKeySelector(l));
        return rightItems.Where(r => !hashLK.Contains(rightKeySelector(r))).Select(r => resultSelector(default(TLeft),r));
    }

    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector)  where TLeft : class {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TC, TResult>> CastSMBody<TP, TC, TResult>(LambdaExpression ex, TP unusedP, TC unusedC, TResult unusedRes) => (Expression<Func<TP, TC, TResult>>)ex;

    public static IQueryable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { left = default(TLeft), rightg = default(IEnumerable<TRight>) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TRight), "c");
        var argLeft = Expression.PropertyOrField(parmP, "left");
        var newleftrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, parmC), parmP, parmC), sampleAnonLR, default(TRight), default(TResult));

        return leftItems.AsQueryable().GroupJoin(rightItems, leftKeySelector, rightKeySelector, (left, rightg) => new { left, rightg }).SelectMany(r => r.rightg.DefaultIfEmpty(), newleftrs);
    }

    public static IQueryable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TLeft), "c");
        var argRight = Expression.PropertyOrField(parmP, "right");
        var newrightrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, parmC, argRight), parmP, parmC), sampleAnonLR, default(TLeft), default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).SelectMany(l => l.leftg.DefaultIfEmpty(), newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TResult>> CastSBody<TP, TResult>(LambdaExpression ex, TP unusedP, TResult unusedRes) => (Expression<Func<TP, TResult>>)ex;

    public static IQueryable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLgR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmLgR = Expression.Parameter(sampleAnonLgR.GetType(), "lgr");
        var argLeft = Expression.Constant(default(TLeft), typeof(TLeft));
        var argRight = Expression.PropertyOrField(parmLgR, "right");
        var newrightrs = CastSBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, argRight), parmLgR), sampleAnonLgR, default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).Where(lgr => !lgr.leftg.Any()).Select(newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }
}

The difference between a Right Anti-Semi-Join is mostly moot with Linq to Objects or in the source, but makes a difference on the server (SQL) side in the final answer, removing an unnecessary JOIN.

The hand coding of Expression to handle merging an Expression<Func<>> into a lambda could be improved with LinqKit, but it would be nice if the language/compiler had added some help for that. The FullOuterJoinDistinct and RightOuterJoin functions are included for completeness, but I did not re-implement FullOuterGroupJoin yet.

I wrote another version of a full outer join for IEnumerable for cases where the key is orderable, which is about 50% faster than combining the left outer join with the right anti semi join, at least on small collections. It goes through each collection after sorting just once.

I also added another answer for a version that works with EF by replacing the Invoke with a custom expansion.

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

What does "Changes not staged for commit" mean

What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

How To Use DateTimePicker In WPF?

This just came in ;)

There is a new DatePicker class for WPF in the .NET 4.0 runtime: http://msdn.microsoft.com/en-us/library/system.windows.controls.datepicker.aspx

Also see the "Whats new in WPF" for more nice features: http://msdn.microsoft.com/en-us/library/bb613588.aspx

How to set thousands separator in Java?

NumberFormat nf = DecimalFormat.getInstance(myLocale);
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator(' ');
((DecimalFormat)nf).setDecimalFormatSymbols(customSymbol);
nf.setGroupingUsed(true);

Zsh: Conda/Pip installs command not found

None of these solutions worked for me. I had to append bash environment to the zsh:

echo 'source ~/.bash_profile' >> ~/.zshrc

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):

You called the draw() method with the wrong type of data rather than a DataTable or DataView.

The solution would be: replace jsapi and just use loader.js with:

google.charts.load('current', {packages: ['corechart']}) and 
google.charts.setOnLoadCallback 

-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

jQuery & CSS - Remove/Add display:none

So, let me give you sample code:

<div class="news">
Blah, blah, blah. I'm hidden.
</div>

<a class="trigger">Hide/Show News</a>

The link will be the trigger to show the div when clicked. So your Javascript will be:

$('.trigger').click(function() {
   $('.news').toggle();
});

You're almost always better off letting jQuery handle the styling for hiding and showing elements.

Edit: I see people above are recommending using .show and .hide for this. .toggle allows you to do both with just one effect. So that's cool.

How do I invert BooleanToVisibilityConverter?

Or the real lazy mans way, just make use of what is there already and flip it:

public class InverseBooleanToVisibilityConverter : IValueConverter
{
    private BooleanToVisibilityConverter _converter = new BooleanToVisibilityConverter();

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var result = _converter.Convert(value, targetType, parameter, culture) as Visibility?;
        return result == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var result = _converter.ConvertBack(value, targetType, parameter, culture) as bool?;
        return result == true ? false : true;
    }
}

SQL, Postgres OIDs, What are they and why are they useful?

OIDs being phased out

The core team responsible for Postgres is gradually phasing out OIDs.

Postgres 12 removes special behavior of OID columns

The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:

  • CREATE TABLE … WITH OIDS command
  • default_with_oids (boolean) compatibility setting

The data type OID remains in Postgres 12. You can explicitly create a column of the type OID.

After migrating to Postgres 12, any optionally-defined system column oid will no longer be invisible by default. Performing a SELECT * will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.

Displaying splash screen for longer than default seconds

The simplest way to achieve this is to creat an UIImageView with "Default.png" on the top of your first ViewController's UIView.

And add an Timer to remove the UIImageView after seconds you expected.

Stop Excel from automatically converting certain text values to dates

None of the solutions offered here is a good solution. It may work for individual cases, but only if you're in control of the final display. Take my example: my work produces list of products they sell to retail. This is in CSV format and contain part-codes, some of them start with zero's, set by manufacturers (not under our control). Take away the leading zeroes and you may actually match another product. Retail customers want the list in CSV format because of back-end processing programs, that are also out of our control and different per customer, so we cannot change the format of the CSV files. No prefixed'=', nor added tabs. The data in the raw CSV files is correct; it's when customers open those files in Excel the problems start. And many customers are not really computer savvy. They can just about open and save an email attachment. We are thinking of providing the data in two slightly different formats: one as Excel Friendly (using the options suggested above by adding a TAB, the other one as the 'master'. But this may be wishful thinking as some customers will not understand why we need to do this. Meanwhile we continue to keep explaining why they sometimes see 'wrong' data in their spreadsheets. Until Microsoft makes a proper change I see no proper resolution to this, as long as one has no control over how end-users use the files.

How to know if other threads have finished?

You could also use the Executors object to create an ExecutorService thread pool. Then use the invokeAll method to run each of your threads and retrieve Futures. This will block until all have finished execution. Your other option would be to execute each one using the pool and then call awaitTermination to block until the pool is finished executing. Just be sure to call shutdown() when you're done adding tasks.

Generating Fibonacci Sequence

According to the Interview Cake question, the sequence goes 0,1,1,2,3,5,8,13,21. If this is the case, this solution works and is recursive without the use of arrays.

function fibonacci(n) {
   return n < 1 ? 0
        : n <= 2 ? 1
        : fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(4));

Think of it like this.

   fibonacci(4)   .--------> 2 + 1 = 3
      |          /               |
      '--> fibonacci(3) + fibonacci(2)
            |    ^           
            |    '----------- 2 = 1 + 1 <----------.
1st step -> |                     ^                |
            |                     |                |
            '---->  fibonacci(2) -' + fibonacci(1)-'

Take note, this solution is not very efficient though.

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

UIButton: set image for selected-highlighted state

If someone's wondering how this works in Swift, here's my solution:

button.setImage("normal.png", forState: .Normal)
button.setImage("highlighted.png", forState: .Highlighted)
button.setImage("selected.png", forState: .Selected)

var selectedHighLightedStates: UIControlState = UIControlState.Highlighted
selectedHighLightedStates = selectedHighLightedStates.union(UIControlState.Selected)
button.setImage("selectedHighlighted.png", forState: selectedHighLightedStates)

How do you create nested dict in Python?

For arbitrary levels of nestedness:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

get url content PHP

original answer moved to this topic .

Reading a date using DataReader

 (DateTime)MyReader["ColumnName"];

OR

Convert.ToDateTime(MyReader["ColumnName"]);

Proxy Basic Authentication in C#: HTTP 407 error

You can use like this, it works!

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")
        };

        HttpClientHandler httpClientHandler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");

What is an IIS application pool?

IIS-Internet information Service is a web server used to host one or more web application . Lets take any example here say Microsoft is maintaining web server and we are running our website abc.com (news content based)on this IIS. Since, Microsoft is a big shot company it might take or also ready to host another website say xyz.com(ecommerce based).

Now web server is hosting i.e providing memory to run both websites on its single web server.Thus , here application pools come into picture . abc.com has its own rules, business logic , data etc and same applies to xyz.com.

IIS provides two application pools (path) to run two websites in their own world (data) smoothly in a single webserver without affecting each ones matter (security, scalability).This is application pool in IIS.

So you can have any number of application pool depending upon on servers capacity

How to change an image on click using CSS alone?

You can use the different states of the link for different images example

You can also use the same image (css sprite) which combines all the different states and then just play with the padding and position to show only the one you want to display.

Another option would be using javascript to replace the image, that would give you more flexibility

How can I define an array of objects?

What you really want may simply be an enumeration

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

Scala: write string to file in one statement

os-lib is the best modern way to write to a file, as mentioned here.

Here's how to write "hello" to the file.txt file.

os.write(os.pwd/"file.txt", "hello")

os-lib hides the Java ugliness and complexity (it uses the Java libs under the hood, so it's just as performant). See here for more info about using the lib.

Creating a simple login form

Using <table> is not a bad choice. Of course it is bit old fashioned. 

But still not obsolete. But if you prefer you can use "Boostrap". There you have options for panels and enhanced forms.

This is the sample code for your requirement. Used minimal styles to simplify.

<!DOCTYPE html>
<html>
   <head>
      <title>Simple Login Form</title>
   </head>
   <style>
      table{
      border-style: solid;
      position: absolute;
      top: 40%;
      left : 40%;
      padding:10px;
      }
   </style>
   <body>
      <form method="post" action="login.php">
         <table>
            <tr bgcolor="black">
               <th colspan="3"><font color="white">Enter login details</th>
            </tr>
            <tr height="20"></tr>
            <tr>
               <td>User Name</td>
               <td>:</td>
               <td>
                  <input type="text" name="username"/>
               </td>
            </tr>
            <tr>
               <td>Password</td>
               <td>:</td>
               <td>
                  <input type="password" name="password"/>
               </td>
            </tr>
            <tr height="10"></tr>
            <tr>
               <td></td>
               <td></td>
               <td align="center"><input type="submit" value="Submit"></td>
            </tr>
         </table>
      </form>
   </body>
</html>

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

Changing background colour of tr element on mouseover

You can give the tr an id and do it.

tr#element{
    background-color: green;
    cursor: pointer;
    height: 30px;

}

tr#element:hover{
    background-color: blue;
    cursor: pointer;

}

<table width="400px">
<tr id="element">
<td></td>
</tr>
</table>

Squash my last X commits together using Git

Use git rebase -i <after-this-commit> and replace "pick" on the second and subsequent commits with "squash" or "fixup", as described in the manual.

In this example, <after-this-commit> is either the SHA1 hash or the relative location from the HEAD of the current branch from which commits are analyzed for the rebase command. For example, if the user wishes to view 5 commits from the current HEAD in the past the command is git rebase -i HEAD~5.

Javascript "Not a Constructor" Exception while creating objects

I've googled around also and found this solution:

You have a variable Project somewhere that is not a function. Then the new operator will complain about it. Try console.log(Project) at the place where you would have used it as a construcotr, and you will find it.

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

phpmyadmin logs out after 1440 secs

You should restart apache or httpd, not mysqld

sudo service httpd restart

or

sudo /etc/init.d/apache2 restart

How to present UIAlertController when not in a view controller?

I use this code with some little personal variations in my AppDelegate class

-(UIViewController*)presentingRootViewController
{
    UIViewController *vc = self.window.rootViewController;
    if ([vc isKindOfClass:[UINavigationController class]] ||
        [vc isKindOfClass:[UITabBarController class]])
    {
        // filter nav controller
        vc = [AppDelegate findChildThatIsNotNavController:vc];
        // filter tab controller
        if ([vc isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tbc = ((UITabBarController*)vc);
            if ([tbc viewControllers].count > 0) {
                vc = [tbc viewControllers][tbc.selectedIndex];
                // filter nav controller again
                vc = [AppDelegate findChildThatIsNotNavController:vc];
            }
        }
    }
    return vc;
}
/**
 *   Private helper
 */
+(UIViewController*)findChildThatIsNotNavController:(UIViewController*)vc
{
    if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).viewControllers.count > 0) {
            vc = [((UINavigationController *)vc).viewControllers objectAtIndex:0];
        }
    }
    return vc;
}

Do I really need to encode '&' as '&amp;'?

Validation aside, the fact remains that encoding certain characters is important to an HTML document so that it can render properly and safely as a web page.

Encoding & as &amp; under all circumstances, for me, is an easier rule to live by, reducing the likelihood of errors and failures.

Compare the following: which is easier? which is easier to bugger up?

Methodology 1

  1. Write some content which includes ampersand characters.
  2. Encode them all.

Methodology 2

(with a grain of salt, please ;) )

  1. Write some content which includes a ampersand characters.
  2. On a case-by-case basis, look at each ampersand. Determine if:
    • It is isolated, and as such unambiguously an ampersand. eg. volt & amp
       > In that case don't bother encoding it.
    • It is not isolated, but you feel it is nonetheless unambiguous, as the resulting entity does not exist and will never exist since the entity list could never evolve. eg amp&volt
       > In that case don't bother encoding it.
    • It is not isolated, and ambiguous. eg. volt&amp
       > Encode it.

??

Value cannot be null. Parameter name: source

I just got this exact error in .Net Core 2.2 Entity Framework because I didn't have the set; in my DbContext like so:

public DbSet<Account> Account { get; }

changed to:

public DbSet<Account> Account { get; set;}

However, it didn't show the exception until I tried to use a linq query with Where() and Select() as others had mentioned above.

I was trying to set the DbSet as read only. I'll keep trying...

Waiting till the async task finish its work

AsyncTask have four methods..

onPreExecute  -- for doing something before calling background task in Async

doInBackground  -- operation/Task to do in Background

onProgressUpdate  -- it is for progress Update

onPostExecute  -- this method calls after asyncTask return from doInBackground.

you can call your work on onPostExecute() it calls after returning from doInBackground()

onPostExecute is what you need to Implement.

How do I create a URL shortener?

Here is my PHP 5 class.

<?php
class Bijective
{
    public $dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public function __construct()
    {
        $this->dictionary = str_split($this->dictionary);
    }

    public function encode($i)
    {
        if ($i == 0)
        return $this->dictionary[0];

        $result = '';
        $base = count($this->dictionary);

        while ($i > 0)
        {
            $result[] = $this->dictionary[($i % $base)];
            $i = floor($i / $base);
        }

        $result = array_reverse($result);

        return join("", $result);
    }

    public function decode($input)
    {
        $i = 0;
        $base = count($this->dictionary);

        $input = str_split($input);

        foreach($input as $char)
        {
            $pos = array_search($char, $this->dictionary);

            $i = $i * $base + $pos;
        }

        return $i;
    }
}

HTML CSS How to stop a table cell from expanding

This could be useful. Like another answer it is just CSS.

td {
    word-wrap: break-word;
}

Bash syntax error: unexpected end of file

I know I am too late to the party. Hope this may help someone.

Check your .bashrc file. Perhaps rename or move it.

Discussion here: Unable to source a simple bash script

How do I tell Python to convert integers into words

You have to use a dictionnary/array. For example :

 to_19= ['zero','one','two','three','four','five','six','seven','eight','nine'..'nineteen']
 tens = ['twenty'...'ninety']

And you could generate the string of a number by doing, for example :

 if len(str(number)) == 2 and  number > 20:
       word_number = tens[str(number)[0]]+' '+units[str(number)[0]]

You have to check if the last figure is not a zero and so on.. classic value checking.

It reminds a project euler challenge (problem 17).. you should try to find some solutions about it

Hope it helps

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

In windows:

pip install tesseract

pip install tesseract-ocr

and check the file which is stored in your system usr/appdata/local/programs/site-pakages/python/python36/lib/pytesseract/pytesseract.py file and compile the file

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

Visual Studio Code compile on save

I implemented compile on save with gulp task using gulp-typescript and incremental build. This allows to control compilation whatever you want. Notice my variable tsServerProject, in my real project I also have tsClientProject because I want to compile my client code with no module specified. As I know you can't do it with vs code.

var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    sourcemaps = require('gulp-sourcemaps');

var tsServerProject = ts.createProject({
   declarationFiles: false,
   noExternalResolve: false,
   module: 'commonjs',
   target: 'ES5'
});

var srcServer = 'src/server/**/*.ts'

gulp.task('watch-server', ['compile-server'], watchServer);
gulp.task('compile-server', compileServer);

function watchServer(params) {
   gulp.watch(srcServer, ['compile-server']);
}

function compileServer(params) {
   var tsResult = gulp.src(srcServer)
      .pipe(sourcemaps.init())
      .pipe(ts(tsServerProject));

   return tsResult.js
      .pipe(sourcemaps.write('./source-maps'))
      .pipe(gulp.dest('src/server/'));

}

How to combine class and ID in CSS selector?

I think you are all wrong. IDs versus Class is not a question of specificity; they have completely different logical uses.

IDs should be used to identify specific parts of a page: the header, the nav bar, the main article, author attribution, footer.

Classes should be used to apply styles to the page. Let's say you have a general magazine site. Every page on the site is going to have the same elements--header, nav, main article, sidebar, footer. But your magazine has different sections--economics, sports, entertainment. You want the three sections to have different looks--economics conservative and square, sports action-y, entertainment bright and young.

You use classes for that. You don't want to have to make multiple IDs--#economics-article and #sports-article and #entertainment-article. That doesn't make sense. Rather, you would define three classes, .economics, sports, and .entertainment, then define the #nav, #article, and #footer ids for each.

"Thinking in AngularJS" if I have a jQuery background?

Those are some very nice, but lengthy answers.

To sum up my experiences:

  1. Controllers and providers (services, factories, etc.) are for modifying the data model, NOT HTML.
  2. HTML and directives define the layout and binding to the model.
  3. If you need to share data between controllers, create a service or factory - they are singletons that are shared across the application.
  4. If you need an HTML widget, create a directive.
  5. If you have some data and are now trying to update HTML... STOP! update the model, and make sure your HTML is bound to the model.

Why in C++ do we use DWORD rather than unsigned int?

When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.

When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.

When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.

I don't think WORD or DWORD will ever change.

Avoid Adding duplicate elements to a List C#

Taking the hint from #Felipe Oriani, I made the extension which I would like to share here for good.

public static class CollectionExtension
{
    public static void AddUniqueItem<T>(this List<T> list, T item, bool throwException)
    {
        if (!list.Contains(item))
        {
            list.Add(item);
        }
        else if(throwException)
        {
            throw new InvalidOperationException("Item already exists in the list");
        }
    }
    public static bool IsUnique<T>(this List<T> list, IEqualityComparer<T> comparer)
    {
        return list.Count == list.Distinct(comparer).Count();
    }
    public static bool IsUnique<T>(this List<T> list)
    {
        return list.Count == list.Distinct().Count();
    }
}

MySQL Query GROUP BY day / month / year

try this one

SELECT COUNT(id)
FROM stats
GROUP BY EXTRACT(YEAR_MONTH FROM record_date)

EXTRACT(unit FROM date) function is better as less grouping is used and the function return a number value.

Comparison condition when grouping will be faster than DATE_FORMAT function (which return a string value). Try using function|field that return non-string value for SQL comparison condition (WHERE, HAVING, ORDER BY, GROUP BY).

The difference between the Runnable and Callable interfaces in Java

Runnable (vs) Callable comes into point when we are using Executer framework.

ExecutorService is a subinterface of Executor, which accepts both Runnable and Callable tasks.

Earlier Multi-Threading can be achieved using Interface RunnableSince 1.0, but here the problem is after completing the thread task we are unable to collect the Threads information. In-order to collect the data we may use Static fields.

Example Separate threads to collect each student data.

static HashMap<String, List> multiTasksData = new HashMap();
public static void main(String[] args) {
    Thread t1 = new Thread( new RunnableImpl(1), "T1" );
    Thread t2 = new Thread( new RunnableImpl(2), "T2" );
    Thread t3 = new Thread( new RunnableImpl(3), "T3" );

    multiTasksData.put("T1", new ArrayList() ); // later get the value and update it.
    multiTasksData.put("T2", new ArrayList() );
    multiTasksData.put("T3", new ArrayList() );
}

To resolve this problem they have introduced Callable<V>Since 1.5 which returns a result and may throw an exception.

  • Single Abstract Method : Both Callable and Runnable interface have a single abstract method, which means they can be used in lambda expressions in java 8.

    public interface Runnable {
    public void run();
    }
    
    public interface Callable<Object> {
        public Object call() throws Exception;
    }
    

There are a few different ways to delegate tasks for execution to an ExecutorService.

  • execute(Runnable task):void crates new thread but not blocks main thread or caller thread as this method return void.
  • submit(Callable<?>):Future<?>, submit(Runnable):Future<?> crates new thread and blocks main thread when you are using future.get().

Example of using Interfaces Runnable, Callable with Executor framework.

class CallableTask implements Callable<Integer> {
    private int num = 0;
    public CallableTask(int num) {
        this.num = num;
    }
    @Override
    public Integer call() throws Exception {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < 5; i++) {
            System.out.println(i + " : " + threadName + " : " + num);
            num = num + i;
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task. Final Value : "+ num);

        return num;
    }
}
class RunnableTask implements Runnable {
    private int num = 0;
    public RunnableTask(int num) {
        this.num = num;
    }
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < 5; i++) {
            System.out.println(i + " : " + threadName + " : " + num);
            num = num + i;
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task. Final Value : "+ num);
    }
}
public class MainThread_Wait_TillWorkerThreadsComplete {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println("Main Thread start...");
        Instant start = java.time.Instant.now();

        runnableThreads();
        callableThreads();

        Instant end = java.time.Instant.now();
        Duration between = java.time.Duration.between(start, end);
        System.out.format("Time taken : %02d:%02d.%04d \n", between.toMinutes(), between.getSeconds(), between.toMillis()); 

        System.out.println("Main Thread completed...");
    }
    public static void runnableThreads() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        Future<?> f1 = executor.submit( new RunnableTask(5) );
        Future<?> f2 = executor.submit( new RunnableTask(2) );
        Future<?> f3 = executor.submit( new RunnableTask(1) );

        // Waits until pool-thread complete, return null upon successful completion.
        System.out.println("F1 : "+ f1.get());
        System.out.println("F2 : "+ f2.get());
        System.out.println("F3 : "+ f3.get());

        executor.shutdown();
    }
    public static void callableThreads() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        Future<Integer> f1 = executor.submit( new CallableTask(5) );
        Future<Integer> f2 = executor.submit( new CallableTask(2) );
        Future<Integer> f3 = executor.submit( new CallableTask(1) );

        // Waits until pool-thread complete, returns the result.
        System.out.println("F1 : "+ f1.get());
        System.out.println("F2 : "+ f2.get());
        System.out.println("F3 : "+ f3.get());

        executor.shutdown();
    }
}

How do I undo the most recent local commits in Git?

You need to do the easy and fast

    git commit --amend

if it's a private branch or

    git commit -m 'Replace .class files with .java files'

if it's a shared or public branch.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I would not change the constraints, instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.

Then you can remove the initial primary key row with id_no =7008255601088.

Three steps include:

  1. Insert duplicate row for new id_no
  2. Update Patient_address to point to new duplicate row
  3. Remove the row with old id_no

Assembly - JG/JNLE/JL/JNGE after CMP

Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:

cmp_instruction op1, op2

Which sets various flags based on the result, and

jmp_conditional_instruction address

which will execute the jump based on the results of those flags.

Compare (cmp) will basically compute the subtraction op1-op2, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx that's the same as saying eax-ebx - then deciding based on whether that is positive, negative or zero which flags to set.

More detailed reference here.

Ruby: How to post a file via HTTP as multipart/form-data?

I like RestClient. It encapsulates net/http with cool features like multipart form data:

require 'rest_client'
RestClient.post('http://localhost:3000/foo', 
  :name_of_file_param => File.new('/path/to/file'))

It also supports streaming.

gem install rest-client will get you started.

View the change history of a file using Git versioning

In Sourcetree UI (https://www.sourcetreeapp.com/), you can find history of a file by selecting 'Log Selected' option in right click context menu:

enter image description here

It would show the history of all the commits.

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

select data up to a space?

An alternative if you sometimes do not have spaces do not want to use the CASE statement

select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))

This works in SQL Server, and according to my searching MySQL has the same functions

spring PropertyPlaceholderConfigurer and context:property-placeholder

<context:property-placeholder ... /> is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/> simply factories a java.util.Properties instance that you can inject.

In Spring 3.1 (not 3.0...) you can do something like this:

@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration { 

    @Autowired Environment environment; 

    @Bean public javax.sql.DataSource dataSource( ){ 
        String user = this.environment.getProperty("ds.user");
        ...
    } 
}

In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:

@Value("${ds.user}") private String user;

If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:

@Configuration 
public class MySpring3Configuration {     
        @Bean 
        public static PropertyPlaceholderConfigurer configurer() { 
             PropertyPlaceholderConfigurer ppc = ...
             ppc.setLocations(...);
             return ppc; 
        } 

        @Bean 
        public class DataSource dataSource(
                @Value("${ds.user}") String user, 
                @Value("${ds.pw}") String pw, 
                ...) { 
            DataSource ds = ...
            ds.setUser(user);
            ds.setPassword(pw);                        
            ...
            return ds;
        }
}

Note that the PPC is defined using a static bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor - it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.

Encrypt and Decrypt text with RSA in PHP

You can use phpseclib, a pure PHP RSA implementation:

<?php
include('Crypt/RSA.php');

$privatekey = file_get_contents('private.key');

$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey);

$plaintext = new Math_BigInteger('aaaaaa');
echo $rsa->_exponentiate($plaintext)->toBytes();
?>

Aren't Python strings immutable? Then why does a + " " + b work?

Consider this addition to your example

 a = "Dog"
 b = "eats"
 c = "treats"
 print (a,b,c)
 #Dog eats treats
 d = a + " " + b + " " + c
 print (a)
 #Dog
 print (d)
 #Dog eats treats

One of the more precise explanations I found in a blog is:

In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.

Eg:

some_guy = 'Fred'
# ...
some_guy = 'George'

When we later say some_guy = 'George', the string object containing 'Fred' is unaffected. We've just changed the binding of the name some_guy. We haven't, however, changed either the 'Fred' or 'George' string objects. As far as we're concerned, they may live on indefinitely.

Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

$(window).height() vs $(document).height

jQuery $(window).height(); or $(window).width(); is only work perfectly when your html page doctype is html

<!DOCTYPE html>
<html lang="en">
...

Random number generator only generating one random number

Mark's solution can be quite expensive since it needs to synchronize everytime.

We can get around the need for synchronization by using the thread-specific storage pattern:


public class RandomNumber : IRandomNumber
{
    private static readonly Random Global = new Random();
    [ThreadStatic] private static Random _local;

    public int Next(int max)
    {
        var localBuffer = _local;
        if (localBuffer == null) 
        {
            int seed;
            lock(Global) seed = Global.Next();
            localBuffer = new Random(seed);
            _local = localBuffer;
        }
        return localBuffer.Next(max);
    }
}

Measure the two implementations and you should see a significant difference.

how to toggle (hide/show) a table onClick of <a> tag in java script

visibility property makes the element visible or invisible.

function showTable(){
    document.getElementById('table').style.visibility = "visible";
}
function hideTable(){
    document.getElementById('table').style.visibility = "hidden";
}

Data-frame Object has no Attribute

I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.

What is "runtime"?

Runtime is somewhat opposite to design-time and compile-time/link-time. Historically it comes from slow mainframe environment where machine-time was expensive.

How to make an inline-block element fill the remainder of the line?

I've used flex-grow property to achieve this goal. You'll have to set display: flex for parent container, then you need to set flex-grow: 1 for the block you want to fill remaining space, or just flex: 1 as tanius mentioned in the comments.

Change the "From:" address in Unix "mail"

GNU mailutils's 'mail' command doesn't let you do this (easily at least). But If you install 'heirloom-mailx', its mail command (mailx) has the '-r' option to override the default '$USER@$HOSTNAME' from field.

echo "Hello there" | mail -s "testing" -r [email protected] [email protected]

Works for 'mailx' but not 'mail'.

$ ls -l /usr/bin/mail
lrwxrwxrwx 1 root root 22 2010-12-23 08:33 /usr/bin/mail -> /etc/alternatives/mail
$ ls -l /etc/alternatives/mail
lrwxrwxrwx 1 root root 23 2010-12-23 08:33 /etc/alternatives/mail -> /usr/bin/heirloom-mailx

Is it better to return null or empty collection?

I would argue that null isn't the same thing as an empty collection and you should choose which one best represents what you're returning. In most cases null is nothing (except in SQL). An empty collection is something, albeit an empty something.

If you have have to choose one or the other, I would say that you should tend towards an empty collection rather than null. But there are times when an empty collection isn't the same thing as a null value.

How to execute a Ruby script in Terminal?

For those not getting a solution for older answers, i simply put my file name as the very first line in my code.

like so

 #ruby_file_name_here.rb

 puts "hello world"

Using reCAPTCHA on localhost

If you have old key, you should recreate your API Key. Also be aware of proxies.

How can I tell if a DOM element is visible in the current viewport?

I use this function (it only checks if the y is inscreen since most of the time the x is not needed)

function elementInViewport(el) {
    var elinfo = {
        "top":el.offsetTop,
        "height":el.offsetHeight,
    };

    if (elinfo.top + elinfo.height < window.pageYOffset || elinfo.top > window.pageYOffset + window.innerHeight) {
        return false;
    } else {
        return true;
    }

}

Method to Add new or update existing item in Dictionary

Functionally, they are equivalent.

Performance-wise map[key] = value would be quicker, as you are only making single lookup instead of two.

Style-wise, the shorter the better :)

The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.

GROUP_CONCAT comma separator - MySQL

Query to achieve your requirment

SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;

How do I ignore all files in a folder with a Git repository in Sourcetree?

  • Ignore all files in folder with Git in Sourcetree:

Ignore all files in folder with Git in Sourcetree

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

Change background color of edittext in android

For me this code it work So put this code in XML file rounded_edit_text

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#3498db" /> <solid android:color="#00FFFFFF" /> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" > </padding> </shape> </item> </layer-list>

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

How to return a result (startActivityForResult) from a TabHost Activity?

http://tylenoly.wordpress.com/2010/10/27/how-to-finish-activity-with-results/

With a slight modification for "param_result"

/* Start Activity */
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90);
}
/* Called when the second activity's finished */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    }
}

private void finishWithResult()
{
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish();
}

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

TortoiseGit-git did not exit cleanly (exit code 1)

Right click -> TortoiseGit -> Settings -> Network
SSH client was pointing to C:\Program Files\TortoiseGit\bin\TortoisePlink.exe
Changed path to C:\Program Files (x86)\Git\bin\ssh.exe

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

exception in initializer error in java when using Netbeans

@Christian Ullenboom' explanation is correct.

I'm surmising that the OBD2nerForm code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.

I'd do the following to try and diagnose this:

  • Google for reports of similar problems with NetBeans generated forms.
  • If you are running an old version of NetBeans, scan through the "bugs fixed" pages for more recent releases. Or just upgrade try a newer release anyway to see if that fixes the problem.
  • Try cutting bits out of the form design until the problem "goes away" ... and try to figure out what the real cause is that way.
  • Run the application under a debugger to figure out what is being (incorrectly) type cast as what. Just knowing the class names may help. And looking at the instance variables of the objects may reveal more; e.g. which specific form component is causing the problem.

My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname

AES Encrypt and Decrypt

You can just copy & paste these methods (Swift 4+):

    class func encryptMessage(message: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let encrypted = try? aes.encrypt(Array<UInt8>(message.utf8)) {
            return encrypted.toHexString()
        }
        return nil
    }

    class func decryptMessage(encryptedMessage: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let decrypted = try? aes.decrypt(Array<UInt8>(hex: encryptedMessage)) {
            return String(data: Data(bytes: decrypted), encoding: .utf8)
        }
        return nil
    }

Example:

let encryptMessage = encryptMessage(message: "Hello World!", encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")    
// Output of encryptMessage is: 649849a5e700d540f72c4429498bf9f4

let decryptedMessage = decryptMessage(encryptedMessage: encryptMessage, encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")
// Output of decryptedMessage is: Hello World!

Don't forget encryptionKey & iv should be 16 bytes.


How to find my realm file?

Under Tools -> Android Device Monitor

And under File Explorer. Search for the apps. And the file is under data/data.

Disabling Log4J Output in Java

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;

Bootstrap Columns Not Working

Your Nesting DIV structure was missing, you must add another ".row" div when creating nested divs in bootstrap :

Here is the Code:

<div class="container">
   <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-4"> <a href="">About</a>
    
                    </div>
                    <div class="col-md-4">
                        <img src="https://www.google.ca/images/srpr/logo11w.png" width="100px" />
                    </div>
                    <div class="col-md-4"> <a href="#myModal1" data-toggle="modal">SHARE</a>
    
                    </div>
                </div>
            </div>
        </div>
    </div>

Refer the Bootstrap example description for the same:

http://getbootstrap.com/css/

Nesting columns

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).


Here is the working Fiddle of your code: http://jsfiddle.net/52j6avkb/1/embedded/result/

Get the new record primary key ID from MySQL insert query?

You need to use the LAST_INSERT_ID() function with transaction:

START TRANSACTION;
  INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
  SELECT LAST_INSERT_ID();
COMMIT;

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

This function will be return last inserted primary key in table.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

How to make for loops in Java increase by increments other than 1

Change

for(j = 0; j<=90; j+3)

to

for(j = 0; j<=90; j=j+3)

is there a function in lodash to replace matched item

Using lodash unionWith function, you can accomplish a simple upsert to an object. The documentation states that if there is a match, it will use the first array. Wrap your updated object in [ ] (array) and put it as the first array of the union function. Simply specify your matching logic and if found it will replace it and if not it will add it

Example:

let contacts = [
     {type: 'email', desc: 'work', primary: true, value: 'email prim'}, 
     {type: 'phone', desc: 'cell', primary: true, value:'phone prim'},
     {type: 'phone', desc: 'cell', primary: false,value:'phone secondary'},
     {type: 'email', desc: 'cell', primary: false,value:'email secondary'}
]

// Update contacts because found a match
_.unionWith([{type: 'email', desc: 'work', primary: true, value: 'email updated'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)

// Add to contacts - no match found
_.unionWith([{type: 'fax', desc: 'work', primary: true, value: 'fax added'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)