Programs & Examples On #Mysql python

Use this tag for questions about the MySQL-Python database connector library (MySQLdb). Do not use this tag for questions about MySQL Connector/Python (use the [mysql-connector-python] tag instead).

Python 3.4.0 with MySQL database

MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.

mysqlclient is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).

PyMySQL is a pure python MySQL driver, which means it is slower, but it does not require a compiled C component or MySQL libraries and header files to be installed on client machines. It has Python 3 support.

Another option is simply to use another database system like PostgreSQL.

pip install mysql-python fails with EnvironmentError: mysql_config not found

In Mac OS, I simply ran this in terminal to fix:

export PATH=$PATH:/usr/local/mysql/bin

This is the quickest fix I found - it adds it to the path, but I think you're better off adding it permanently (ie add it to /etc/paths) if you plan to install MySQL-python in another environment.

(tested in OSX Mountain Lion)

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

Note about bug of MySQL Connector/C on macOS (my current version is 10.13.2), fix the mysql_config and reinstall mysqlclient or MySQL-python, here is the detail

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Quite old, yet I stumbled upon the very same issue. Try doing this:

df['col_replaced'] = df['col_with_npnans'].apply(lambda x: None if np.isnan(x) else x)

mysql_config not found when installing mysqldb python interface

sudo apt-get install libmysqlclient-dev sudo apt-get install python-dev sudo apt-get install MySQL-python

NOtice you should install python-dev as well, the packages like MySQL-python are compiled from source. The pythonx.x-dev packages contain the necessary header files for linking against python. Why does installing numpy require python-dev in Kubuntu 12.04

Install mysql-python (Windows)

try running the following command:

pip install mysqlclient

Visibility of global variables in imported modules

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it's just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don't use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

All I had to do was go over to oracle, and download the MySQL Connector C 6.0.2 (newer doesn't work!) and do the typical install.

https://downloads.mysql.com/archives/c-c/

Be sure to include all optional extras (Extra Binaries) via the custom install, without these it did not work for the win64.msi

Once that was done, I went into pycharms, and selected the MySQL-python>=1.2.4 package to install, and it worked great. No need to update any configuration or anything like that. This was the simplest version for me to work through.

Hope it helps

MySQL: Get column name or alias from query

You could also use MySQLdb.cursors.DictCursor. This turns your result set into a python list of python dictionaries, although it uses a special cursor, thus technically less portable than the accepted answer. Not sure about speed. Here's the edited original code that uses this.

#!/usr/bin/python -u

import MySQLdb
import MySQLdb.cursors

#===================================================================
# connect to mysql
#===================================================================

try:
    db = MySQLdb.connect(host='myhost', user='myuser', passwd='mypass', db='mydb', cursorclass=MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
    print 'Error %d: %s' % (e.args[0], e.args[1])
    sys.exit(1)

#===================================================================
# query select from table
#===================================================================

cursor = db.cursor()

sql = 'SELECT ext, SUM(size) AS totalsize, COUNT(*) AS filecount FROM fileindex GROUP BY ext ORDER BY totalsize DESC;'

cursor.execute(sql)
all_rows = cursor.fetchall()

print len(all_rows) # How many rows are returned.
for row in all_rows: # While loops always make me shudder!
    print '%s %s %s\n' % (row['ext'], row['totalsize'], row['filecount'])

cursor.close()
db.close()  

Standard dictionary functions apply, for example, len(row[0]) to count the number of columns for the first row, list(row[0]) for a list of column names (for the first row), etc. Hope this helps!

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

cursor.fetchall() vs list(cursor) in Python

A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor is that list(cursor) will always give you a list, while cursor.fetchall() gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.

Given the above, I suggest always favouring list(cursor) over cursor.fetchall(), to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.

How to insert pandas dataframe via mysqldb into database?

Update:

There is now a to_sql method, which is the preferred way to do this, rather than write_frame:

df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')

Also note: the syntax may change in pandas 0.14...

You can set up the connection with MySQLdb:

from pandas.io import sql
import MySQLdb

con = MySQLdb.connect()  # may need to add some other options to connect

Setting the flavor of write_frame to 'mysql' means you can write to mysql:

sql.write_frame(df, con=con, name='table_name_for_df', 
                if_exists='replace', flavor='mysql')

The argument if_exists tells pandas how to deal if the table already exists:

if_exists: {'fail', 'replace', 'append'}, default 'fail'
     fail: If table exists, do nothing.
     replace: If table exists, drop it, recreate it, and insert data.
     append: If table exists, insert data. Create if does not exist.

Although the write_frame docs currently suggest it only works on sqlite, mysql appears to be supported and in fact there is quite a bit of mysql testing in the codebase.

Installing specific package versions with pip

There are 2 ways you may install any package with version:- A). pip install -Iv package-name == version B). pip install -v package-name == version

For A

Here, if you're using -I option while installing(when you don't know if the package is already installed) (like 'pip install -Iv pyreadline == 2.* 'or something), you would be installing a new separate package with the same existing package having some different version.

For B

  1. At first, you may want to check for no broken requirements. pip check

2.and then see what's already installed by pip list

3.if the list of the packages contain any package that you wish to install with specific version then the better option is to uninstall the package of this version first, by pip uninstall package-name

4.And now you can go ahead to reinstall the same package with a specific version, by pip install -v package-name==version e.g. pip install -v pyreadline == 2.*

mysql-python install error: Cannot open include file 'config-win.h'

Assume you want to install package MySQL-python on Windows, maybe try pip install command with --global-option. See the example command below:

pip install MySQL-python ^
 --force-reinstall --no-cache-dir ^
 --global-option=build_ext ^
 --global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
 --global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
 --verbose

For this example, I fully installed 64-bit version of MySQL Connector C in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\.

By the way, I noticed that pip install MySQL-python by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.

Hope the above might be of some help.

Python MYSQL update statement

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

    cursor.execute("""
       UPDATE tblTableName
       SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
       WHERE Server=%s
    """, (Year, Month, Day, Hour, Minute, ServerID))

    connect.commit()
    connect.close()

P.S. Don't forget connect.commit(), or it won't work

ImportError: No module named MySQLdb

Got so many errors related to permissions and what not. You may wanna try this :

xcode-select --install

Set margins in a LinearLayout programmatically

Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

How to check type of variable in Java?

I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

public class TypeTester <T extends Number>{

<T extends Object> String tester(T ToTest){

    if (ToTest instanceof Integer) return ("Integer");
    else if(ToTest instanceof Double) return ("Double");
    else if(ToTest instanceof Float) return ("Float");
    else if(ToTest instanceof String) return ("String");
    else if(ToTest.getClass().isArray()) return ("Array");
    else return ("Unsure");
}
}

I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

public class Generics {
public static void main(String[] args) {
    int [] myArray = new int [10];

    TypeTester<Integer> callFunction = new TypeTester<Integer>();
    System.out.println(callFunction.tester(myArray));
}
}

You can swap out the myArray in the final line for say 10.2F to test Float etc

Can't perform a React state update on an unmounted component

Here is a React Hooks specific solution for

Error

Warning: Can't perform a React state update on an unmounted component.

Solution

You can declare let isMounted = true inside useEffect, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:

useEffect(() => {
  let isMounted = true; // note this flag denote mount status
  someAsyncOperation().then(data => {
    if (isMounted) setState(data);
  })
  return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});

_x000D_
_x000D_
const Parent = () => {_x000D_
  const [mounted, setMounted] = useState(true);_x000D_
  return (_x000D_
    <div>_x000D_
      Parent:_x000D_
      <button onClick={() => setMounted(!mounted)}>_x000D_
        {mounted ? "Unmount" : "Mount"} Child_x000D_
      </button>_x000D_
      {mounted && <Child />}_x000D_
      <p>_x000D_
        Unmount Child, while it is still loading. It won't set state later on,_x000D_
        so no error is triggered._x000D_
      </p>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
const Child = () => {_x000D_
  const [state, setState] = useState("loading (4 sec)...");_x000D_
  useEffect(() => {_x000D_
    let isMounted = true; // note this mounted flag_x000D_
    fetchData();_x000D_
    return () => {_x000D_
      isMounted = false;_x000D_
    }; // use effect cleanup to set flag false, if unmounted_x000D_
_x000D_
    // simulate some Web API fetching_x000D_
    function fetchData() {_x000D_
      setTimeout(() => {_x000D_
        // drop "if (isMounted)" to trigger error again_x000D_
        if (isMounted) setState("data fetched");_x000D_
      }, 4000);_x000D_
    }_x000D_
  }, []);_x000D_
_x000D_
  return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

Extension: Custom useAsync Hook

We can encapsulate all the boilerplate into a custom Hook, that just knows, how to deal with and automatically abort async functions in case the component unmounts before:

function useAsync(asyncFn, onSuccess) {
  useEffect(() => {
    let isMounted = true;
    asyncFn().then(data => {
      if (isMounted) onSuccess(data);
    });
    return () => { isMounted = false };
  }, [asyncFn, onSuccess]);
}

_x000D_
_x000D_
// use async operation with automatic abortion on unmount_x000D_
function useAsync(asyncFn, onSuccess) {_x000D_
  useEffect(() => {_x000D_
    let isMounted = true;_x000D_
    asyncFn().then(data => {_x000D_
      if (isMounted) onSuccess(data);_x000D_
    });_x000D_
    return () => {_x000D_
      isMounted = false;_x000D_
    };_x000D_
  }, [asyncFn, onSuccess]);_x000D_
}_x000D_
_x000D_
const Child = () => {_x000D_
  const [state, setState] = useState("loading (4 sec)...");_x000D_
  useAsync(delay, setState);_x000D_
  return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
const Parent = () => {_x000D_
  const [mounted, setMounted] = useState(true);_x000D_
  return (_x000D_
    <div>_x000D_
      Parent:_x000D_
      <button onClick={() => setMounted(!mounted)}>_x000D_
        {mounted ? "Unmount" : "Mount"} Child_x000D_
      </button>_x000D_
      {mounted && <Child />}_x000D_
      <p>_x000D_
        Unmount Child, while it is still loading. It won't set state later on,_x000D_
        so no error is triggered._x000D_
      </p>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
const delay = () => new Promise(resolve => setTimeout(() => resolve("data fetched"), 4000));_x000D_
_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

Django Server Error: port is already in use

By default, the runserver command starts the development server on the internal IP at port 8000.

If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:

python manage.py runserver 8080

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

After installation of Oracle Client 11.02.04, reboot the server and make sure USERS(Local Computer) is added with Full Control on Root folder for eg WWW

Tested, it worked.

How to embed an autoplaying YouTube video in an iframe?

Since April 2018, Google made some changes to the Autoplay Policy. You not only need to add the autoplay=1 as a query param, but also add allow='autoplay' as an iframe's attribute

So you will have to do something like this:

<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></iframe>

Default parameters with C++ constructors

Sam's answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow delegation from one constructor to another, thereby removing the need for defaults.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Either of these methods may be "better", i.e. more suitable, depending on what you want to do.

A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.

A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.

How to change an input button image using CSS?

My solution without js and without images is this:

*HTML:

<input type=Submit class=continue_shopping_2 
name=Register title="Confirm Your Data!" 
value="confirm your data">

*CSS:

.continue_shopping_2:hover{
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;}


.continue_shopping_2{
padding:0 0 3px 0;
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:174px;
height:21px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#919191;
font-family:Verdana;
font-size:13px;
font-style:normal;
line-height:normal;
font-weight:bold;
color:#FFFFFF;}

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

Logical XOR operator in C++?

The XOR operator cannot be short circuited; i.e. you cannot predict the result of an XOR expression just by evaluating its left hand operand. Thus, there's no reason to provide a ^^ version.

What is the difference between Bower and npm?

2017-Oct update

Bower has finally been deprecated. End of story.

Older answer

From Mattias Petter Johansson, JavaScript developer at Spotify:

In almost all cases, it's more appropriate to use Browserify and npm over Bower. It is simply a better packaging solution for front-end apps than Bower is. At Spotify, we use npm to package entire web modules (html, css, js) and it works very well.

Bower brands itself as the package manager for the web. It would be awesome if this was true - a package manager that made my life better as a front-end developer would be awesome. The problem is that Bower offers no specialized tooling for the purpose. It offers NO tooling that I know of that npm doesn't, and especially none that is specifically useful for front-end developers. There is simply no benefit for a front-end developer to use Bower over npm.

We should stop using bower and consolidate around npm. Thankfully, that is what is happening:

Module counts - bower vs. npm

With browserify or webpack, it becomes super-easy to concatenate all your modules into big minified files, which is awesome for performance, especially for mobile devices. Not so with Bower, which will require significantly more labor to get the same effect.

npm also offers you the ability to use multiple versions of modules simultaneously. If you have not done much application development, this might initially strike you as a bad thing, but once you've gone through a few bouts of Dependency hell you will realize that having the ability to have multiple versions of one module is a pretty darn great feature. Note that npm includes a very handy dedupe tool that automatically makes sure that you only use two versions of a module if you actually have to - if two modules both can use the same version of one module, they will. But if they can't, you have a very handy out.

(Note that Webpack and rollup are widely regarded to be better than Browserify as of Aug 2016.)

Converting an array to a function arguments list

A very readable example from another post on similar topic:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, args);

And here a link to the original post that I personally liked for its readability

Python BeautifulSoup extract text between element

soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
  hit = hit.text.strip()
  print hit

This will print: THIS IS MY TEXT Try this..

Android Get Current timestamp?

Here's a human-readable time stamp that may be used in a file name, just in case someone needs the same thing that I needed:

package com.example.xyz;

import android.text.format.Time;

/**
 * Clock utility.
 */
public class Clock {

    /**
     * Get current time in human-readable form.
     * @return current time as a string.
     */
    public static String getNow() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d %T");
        return sTime;
    }
    /**
     * Get current time in human-readable form without spaces and special characters.
     * The returned value may be used to compose a file name.
     * @return current time as a string.
     */
    public static String getTimeStamp() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d_%H_%M_%S");
        return sTime;
    }

}

How do I convert a string to enum in TypeScript?

enum Color{
    Red, Green
}

// To String
 var green: string = Color[Color.Green];

// To Enum / number
var color : Color = Color[green as keyof typeof Color]; //Works with --noImplicitAny

This example works with --noImplicitAny in TypeScript

Sources:
https://github.com/Microsoft/TypeScript/issues/13775#issuecomment-276381229 https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

How to pass form input value to php function

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

window.location.href and window.open () methods in JavaScript

There are already answers which describes about window.location.href property and window.open() method.

I will go by Objective use:

1. To redirect the page to another

Use window.location.href. Set href property to the href of another page.

2. Open link in the new or specific window.

Use window.open(). Pass parameters as per your goal.

3. Know current address of the page

Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.

See Location Object for more information.

Get most recent file in a directory on Linux

A note about reliability:

Since the newline character is as valid as any in a file name, any solution that relies on lines like the head/tail based ones are flawed.

With GNU ls, another option is to use the --quoting-style=shell-always option and a bash array:

eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

(add the -A option to ls if you also want to consider hidden files).

If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find.

With bash 4.4 or newer (for readarray -d) and GNU coreutils 8.25 or newer (for cut -z):

readarray -t -d '' files < <(
  LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
  sort -rzn | cut -zd/ -f2)

((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

Or recursively:

readarray -t -d '' files < <(
  LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
  sort -rzn | cut -zd/ -f2-)

Best here would be to use zsh and its glob qualifiers instead of bash to avoid all this hassle:

Newest regular file in the current directory:

printf '%s\n' *(.om[1])

Including hidden ones:

printf '%s\n' *(D.om[1])

Second newest:

printf '%s\n' *(.om[2])

Check file age after symlink resolution:

printf '%s\n' *(-.om[1])

Recursively:

printf '%s\n' **/*(.om[1])

Also, with the completion system (compinit and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.

So:

vi Ctrl+Xm

Would make you edit the newest file (you also get a chance to see which it before you press Return).

vi Alt+2Ctrl+Xm

For the second-newest file.

vi *.cCtrl+Xm

for the newest c file.

vi *(.)Ctrl+Xm

for the newest regular file (not directory, nor fifo/device...), and so on.

CSS Background Opacity

You can use Sass' transparentize.

I found it to be the most useful and plain to use.

transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6) 

See more: #transparentize($color, $amount) ? Sass::Script::Value::Color

Same font except its weight seems different on different browsers

In order to best standardise your @font-face embedded fonts across browsers try including the below inside your @font-face declaration or on your body font styling:

speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;

At present there looks to be no universal fix across all platforms and browser builds. As stated frequently all browsers/OS have different text rendering engines.

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

Using IQueryable with Linq

It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.

For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.

Strip double quotes from a string in .NET

if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json. as it's bad json with "quoted" text identifiers.

Add the below method to a class containing your extension methods.

  public static string Remove(this string text, char character)
  {
      var sb = new StringBuilder();
      foreach (char c in text)
      {
         if (c != character)
             sb.Append(c);
      }
      return sb.ToString();
  }

you can then use this extension method:

var text= myString.Remove('"');

How to get the IP address of the docker host from inside a docker container

Here is how I do it. In this case, it adds a hosts entry into /etc/hosts within the docker image pointing taurus-host to my local machine IP: :

TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...

Then, from within Docker container, script can use host name taurus-host to get out to my local machine which hosts the docker container.

Get Android API level of phone currently running my application

try this :Float.valueOf(android.os.Build.VERSION.RELEASE) <= 2.1

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

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

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

Get specific object by id from array of objects in AngularJS

Unfortunately (unless I'm mistaken), I think you need to iterate over the results object.

for(var i = 0; i < results.length; i += 1){
    var result = results[i];
    if(result.id === id){
        return result;
    }
}

At least this way it will break out of the iteration as soon as it finds the correct matching id.

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If you're in a Browser-Only environment, use SridharR's solution.

If you're in a Node/CommonJS + Browser environment (e.g. electron, node-webkit, etc..); the reason for this error is that jQuery's export logic first checks for module, not window:

if (typeof module === "object" && typeof module.exports === "object") {
    // CommonJS/Node
} else {
    // window
}

Note that it exports itself via module.exports in this case; so jQuery and $ are not assigned to window.

So to resolve this, instead of <script src="path/to/jquery.js"></script>;

Simply assign it yourself by a require statement:

<script>
    window.jQuery = window.$ = require('jquery');
</script>

NOTE: If your electron app does not need nodeIntegration, set it to false so you won't need this workaround.

Writing a dictionary to a text file?

The probelm with your first code block was that you were opening the file as 'r' even though you wanted to write to it using 'w'

with open('/Users/your/path/foo','w') as data:
    data.write(str(dictionary))

Find files in created between a date range

Script oldfiles

I've tried to answer this question in a more complete way, and I ended up creating a complete script with options to help you understand the find command.

The script oldfiles is in this repository

To "create" a new find command you run it with the option -n (dry-run), and it will print to you the correct find command you need to use.

Of course, if you omit the -n it will just run, no need to retype the find command.

Usage:

$ oldfiles [-v...] ([-h|-V|-n] | {[(-a|-u) | (-m|-t) | -c] (-i | -d | -o| -y | -g) N (-\> | -\< | -\=) [-p "pat"]})

  • Where the options are classified in the following groups:
    • Help & Info:

      -h, --help : Show this help.
      -V, --version : Show version.
      -v, --verbose : Turn verbose mode on (cumulative).
      -n, --dry-run : Do not run, just explain how to create a "find" command

    • Time type (access/use, modification time or changed status):

      -a or -u : access (use) time
      -m or -t : modification time (default)
      -c : inode status change

    • Time range (where N is a positive integer):

      -i N : minutes (default, with N equal 1 min)
      -d N : days
      -o N : months
      -y N : years
      -g N : N is a DATE (example: "2017-07-06 22:17:15")

    • Tests:

      -p "pat" : optional pattern to match (example: -p "*.c" to find c files) (default -p "*")
      -\> : file is newer than given range, ie, time modified after it.
      -\< : file is older than given range, ie, time is from before it. (default)
      -\= : file that is exactly N (min, day, month, year) old.

Example:

  • Find C source files newer than 10 minutes (access time) (with verbosity 3):

$ oldfiles -a -i 10 -p"*.c" -\> -nvvv Starting oldfiles script, by beco, version 20170706.202054... $ oldfiles -vvv -a -i 10 -p "*.c" -\> -n Looking for "*.c" files with (a)ccess time newer than 10 minute(s) find . -name "*.c" -type f -amin -10 -exec ls -ltu --time-style=long-iso {} + Dry-run

  • Find H header files older than a month (modification time) (verbosity 2):

$ oldfiles -m -o 1 -p"*.h" -\< -nvv Starting oldfiles script, by beco, version 20170706.202054... $ oldfiles -vv -m -o 1 -p "*.h" -\< -n find . -name "*.h" -type f -mtime +30 -exec ls -lt --time-style=long-iso {} + Dry-run

  • Find all (*) files within a single day (Dec, 1, 2016; no verbosity, dry-run):

$ oldfiles -mng "2016-12-01" -\= find . -name "*" -type f -newermt "2016-11-30 23:59:59" ! -newermt "2016-12-01 23:59:59" -exec ls -lt --time-style=long-iso {} +

Of course, removing the -n the program will run the find command itself and save you the trouble.

I hope this helps everyone finally learn this {a,c,t}{time,min} options.

the LS output:

You will also notice that the "ls" option ls OPT changes to match the type of time you choose.

Link for clone/download of the oldfiles script:

https://github.com/drbeco/oldfiles

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

n-grams in python, four, five, six grams?

Using only nltk tools

from nltk.tokenize import word_tokenize
from nltk.util import ngrams

def get_ngrams(text, n ):
    n_grams = ngrams(word_tokenize(text), n)
    return [ ' '.join(grams) for grams in n_grams]

Example output

get_ngrams('This is the simplest text i could think of', 3 )

['This is the', 'is the simplest', 'the simplest text', 'simplest text i', 'text i could', 'i could think', 'could think of']

In order to keep the ngrams in array format just remove ' '.join

Breaking a list into multiple columns in Latex

I don't know if it would work, but maybe you could break the page into columns using the multicol package.

\usepackage{multicol}

\begin{document}
\begin{multicols}{2}[Your list here]
\end{multicols}

How can I present a file for download from an MVC controller?

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

public ActionResult GetPdf(string filename)
{
    return File(filename, "application/pdf", Server.UrlEncode(filename));
}

function to remove duplicate characters in a string

I couldn't understand the logic behind the solution so I wrote my simple solution:

  public static void removeDuplicates(char[] str) {

    if (str == null) return; //If the string is null return      
    int length = str.length; //Getting the length of the string
    if (length < 2) return; //Return if the length is 1 or smaller

    for(int i=0; i<length; i++){ //Loop through letters on the array

        int j;

        for(j=i+1;j<length;j++){ //Loop through letters after the checked letters (i) 

            if (str[j]==str[i]){ //If you find duplicates set it to 0

                str[j]=0;
            }
        }
    }
}

Convert List<String> to List<Integer> directly

Using Streams and Lambda:

newIntegerlist = listName.stream().map(x-> 
    Integer.valueOf(x)).collect(Collectors.toList());

The above line of code will convert the List of type List<String> to List<Integer>.

I hope it was helpful.

Save Dataframe to csv directly to s3 Python

since you are using boto3.client(), try:

import boto3
from io import StringIO #python3 
s3 = boto3.client('s3', aws_access_key_id='key', aws_secret_access_key='secret_key')
def copy_to_s3(client, df, bucket, filepath):
    csv_buf = StringIO()
    df.to_csv(csv_buf, header=True, index=False)
    csv_buf.seek(0)
    client.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key=filepath)
    print(f'Copy {df.shape[0]} rows to S3 Bucket {bucket} at {filepath}, Done!')

copy_to_s3(client=s3, df=df_to_upload, bucket='abc', filepath='def/test.csv')

What is the easiest way to clear a database from the CLI with manage.py in Django?

Using Django Extensions, running:

./manage.py reset_db

Will clear the database tables, then running:

./manage.py syncdb

Will recreate them (south may ask you to migrate things).

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

How do I call an Angular 2 pipe with multiple arguments?

In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Advantage of switch over if-else statement

switch is definitely preferred. It's easier to look at a switch's list of cases & know for sure what it is doing than to read the long if condition.

The duplication in the if condition is hard on the eyes. Suppose one of the == was written !=; would you notice? Or if one instance of 'numError' was written 'nmuError', which just happened to compile?

I'd generally prefer to use polymorphism instead of the switch, but without more details of the context, it's hard to say.

As for performance, your best bet is to use a profiler to measure the performance of your application in conditions that are similar to what you expect in the wild. Otherwise, you're probably optimizing in the wrong place and in the wrong way.

How to start and stop android service from a adb shell?

To stop a service, you have to find service name using:

adb shell dumpsys activity services <your package>

for example: adb shell dumpsys activity services com.xyz.something

This will list services running for your package.
Output should be similar to:

ServiceRecord{xxxxx u0 com.xyz.something.beta/xyz.something.abc.XYZService}

Now select your service and run:

adb shell am stopservice <service_name> 

For example:

adb shell am stopservice com.xyz.something.beta/xyz.something.abc.XYZService

similarly, to start service:

adb shell am startservice <service_name>

To access service, your service(in AndroidManifest.xml) should set exported="true"

<!-- Service declared in manifest -->
<service
    android:name=".YourServiceName"
    android:exported="true"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="com.your.package.name.YourServiceName"/>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</service>

UIAlertView first deprecated IOS 9

-(void)showAlert{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
                                                                   message:"Message"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

[self showAlert]; // calling Method

How do I remove background-image in css?

Try:

div#a {
    background-image:none
}

JWT (JSON Web Token) automatic prolongation of expiration

I actually implemented this in PHP using the Guzzle client to make a client library for the api, but the concept should work for other platforms.

Basically, I issue two tokens, a short (5 minute) one and a long one that expires after a week. The client library uses middleware to attempt one refresh of the short token if it receives a 401 response to some request. It will then try the original request again and if it was able to refresh gets the correct response, transparently to the user. If it failed, it will just send the 401 up to the user.

If the short token is expired, but still authentic and the long token is valid and authentic, it will refresh the short token using a special endpoint on the service that the long token authenticates (this is the only thing it can be used for). It will then use the short token to get a new long token, thereby extending it another week every time it refreshes the short token.

This approach also allows us to revoke access within at most 5 minutes, which is acceptable for our use without having to store a blacklist of tokens.

Late edit: Re-reading this months after it was fresh in my head, I should point out that you can revoke access when refreshing the short token because it gives an opportunity for more expensive calls (e.g. call to the database to see if the user has been banned) without paying for it on every single call to your service.

Access to file download dialog in Firefox

Not that I know of. But you can configure Firefox to automatically start the download and save the file in a specific place. Your test could then check that the file actually arrived.

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

How to copy files from 'assets' folder to sdcard?

If anyone else is having the same problem, this is how I did it

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Reference : Move file using Java

how to delete all cookies of my website in php

I agree with some of the above answers. I would just recommend replacing "time()-1000" with "1". A value of "1" means January 1st, 1970, which ensures expiration 100%. Therefore:

setcookie($name, '', 1);
setcookie($name, '', 1, '/');

How to comment a block in Eclipse?

It depends upon the version of OS - for me it works with Command + 7

BATCH file asks for file or folder

A seemingly undocumented trick is to put a * at the end of the destination - then xcopy will copy as a file, like so

xcopy c:\source\file.txt c:\destination\newfile.txt*

The echo f | xcopy ... trick does not work on localized versions of Windows, where the prompt is different.

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

How can I select all elements without a given class in jQuery?

You can use the .not() method or :not() selector

Code based on your example:

$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)")   // not selector

How to read multiple Integer values from a single line of input in Java?

Try this

public static void main(String[] args) {
    Scanner in = new Scanner(System.in); 
    while (in.hasNext()) {
        if (in.hasNextInt())
            System.out.println(in.nextInt());
        else 
            in.next();
    }
}

By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.

If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this

Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");

How do I use NSTimer?

The answers are missing a specific time of day timer here is on the next hour:

NSCalendarUnit allUnits = NSCalendarUnitYear   | NSCalendarUnitMonth |
                          NSCalendarUnitDay    | NSCalendarUnitHour  |
                          NSCalendarUnitMinute | NSCalendarUnitSecond;

NSCalendar *calendar = [[ NSCalendar alloc]  
                          initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents = [calendar components: allUnits 
                                                  fromDate: [ NSDate date ] ];

[ weekdayComponents setHour: weekdayComponents.hour + 1 ];
[ weekdayComponents setMinute: 0 ];
[ weekdayComponents setSecond: 0 ];

NSDate *nextTime = [ calendar dateFromComponents: weekdayComponents ];

refreshTimer = [[ NSTimer alloc ] initWithFireDate: nextTime
                                          interval: 0.0
                                            target: self
                                          selector: @selector( doRefresh )
                                          userInfo: nil repeats: NO ];

[[NSRunLoop currentRunLoop] addTimer: refreshTimer forMode: NSDefaultRunLoopMode];

Of course, substitute "doRefresh" with your class's desired method

try to create the calendar object once and make the allUnits a static for efficiency.

adding one to hour component works just fine, no need for a midnight test (link)

Static extension methods

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();

How do you represent a JSON array of strings?

Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:

{ "MyStringArray" : ["somestring1", "somestring2"] }

then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and "somestring2".

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I was getting this error for lots of entities when I was migrating down from an EF7 model to an EF6 version. I didn't want to have to go through each entity one at a time, so I used:

builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

Merge PDF files with PHP

$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=".$new." ".implode(" ", $files);
shell_exec($cmd);

A simplified version of Chauhan's answer

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Bottom Line

Use either COUNT(field) or COUNT(*), and stick with it consistently, and if your database allows COUNT(tableHere) or COUNT(tableHere.*), use that.

In short, don't use COUNT(1) for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)

Use count(*) for counting

Use * for all your queries that need to count everything, even for joins, use *

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But don't use COUNT(*) for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table

SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Don't be fooled by those advising that when using * in COUNT, it fetches entire row from your table, saying that * is slow. The * on SELECT COUNT(*) and SELECT * has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *.

An alternate syntax

In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere) the same semantics as COUNT(*). Example:

For counting rows we could have this:

SELECT COUNT(emp) FROM emp

And they could make it simpler:

SELECT COUNT() FROM emp

And for LEFT JOINs, we could have this:

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But they cannot do that (COUNT(tableNameHere)) since SQL standard permits naming a field with the same name as its table name:

CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name, 
                and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)

Counting with null

And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit field. This will not count all rows, it will only yield 3, not 4

SELECT count(fruit) FROM fruit

Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But that could cause confusion later if we will add a subordinate field in the table, as it will count the field(which could be nullable), not the table rows.

So to be on the safe side, use:

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

count(1): The one-trick pony

In particular to COUNT(1), it is a one-trick pony, it works well only on one table query:

SELECT COUNT(1) FROM tbl

But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

So what's the meaning of COUNT(1) here?

SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Is it this...?

-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Or this...?

-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

By careful thought, you can infer that COUNT(1) is the same as COUNT(*), regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1) to work as: COUNT(subordinate.boss_id), COUNT(subordinate.*)

So just use either of the following:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Works on Postgresql, it's clear that you want to count the cardinality of the set

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7

select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You cannot do this: http://www.sqlfiddle.com/#!1/98515/8

select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9

select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

use of entityManager.createNativeQuery(query,foo.class)

Here is a DB2 Stored Procidure that receive a parameter

SQL

CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
    -- Declare cursor
    DECLARE State_Cursor CURSOR WITH RETURN for
    -- #######################################################################
    -- # Replace the SQL statement with your statement.
    -- # Note: Be sure to end statements with the terminator character (usually ';')
    -- #
    -- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
    -- # returns all names from SYSIBM.SYSTABLES.
    -- ######################################################################
    SELECT * FROM COUNTRY.STATE
    WHERE PROVINCE_NAME LIKE UPPER(stateName);
    -- Cursor left open for client application
    OPEN Province_Cursor;
END P1

Java

//Country is a db2 scheme

//Now here is a java Entity bean Method

public List<Province> getStateByName(String stateName) throws Exception {

    EntityManager em = this.em;
    List<State> states= null;
    try {
        Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
        query.setParameter(1, provinceName);
        states= (List<Province>) query.getResultList();
    } catch (Exception ex) {
        throw ex;
    }

    return states;
}

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

Python function pointer

Why not store the function itself? myvar = mypackage.mymodule.myfunction is much cleaner.

Using ExcelDataReader to read Excel data starting from a particular cell

One way to do it :

FileStream stream = File.Open(@"c:\working\test.xls", FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

excelReader.IsFirstRowAsColumnNames = true;

DataSet result = excelReader.AsDataSet();

The result.Tables contains the sheets and the result.tables[0].Rows contains the cell rows.

What's HTML character code 8203?

I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.

The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.

To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

There is no need to update anything in config/mail.php. just put you credential in .env with this specific key's. This is my .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=********
MAIL_ENCRYPTION=tls

I had the same issue after long time debugging and googling i have found the solution. that by enabling less secure apps. the email started working.

if your gmail is secure with 2 step verification you can't enable less secure app. so turn off 2 step verification and enable less secure app. by click here enable less secure apps on your gmail account

How to debug on a real device (using Eclipse/ADT)

With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.

1. Declare your application as "debuggable" in AndroidManifest.xml.

<application
    android:debuggable="true"
    ... >
    ...
</application>

2. On your handset, navigate to Settings > Security and check Unknown sources

enter image description here

3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options is invisible you will need to navigate to Settings > About Phone and tap on Build number several times until you are notified that it has been unlocked.

enter image description here

4. Set up your system to detect your device.
Follow the instructions below for your OS:


Windows Users

Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).

enter image description here

For devices not listed above, install an OEM driver for your device


Mac OS X

Your device should automatically work; Go to the next step


Ubuntu Linux

Add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:

  1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.
  2. Use this format to add each vendor to the file:
    SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
    In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node.
  3. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules

Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.


5. Run the project with your connected device.

With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).

With ADB: issue commands with the -d flag to target your connected device.

Still need help? Click here for the full guide.

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

How can I call a function using a function pointer?

bool (*fptr)();

int main(void)
{
    ...
    ...
    printf("Enter your choice");
    scanf("%d",&a);
    switch(a)
    {
        case 0:
               fptr = A;
               break;
        case 1:
               fptr = B;
               break;
        case 2:
               fptr = C;
               break;
        case 3:
                break;
    }
    (*fptr)();
    return 0;
}

Your choice is stored in a. Then accordingly, functions are assigned in the function pointer. Finally, depending on your choice, the very same function is called to return the desired result.

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

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

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

How to order citations by appearance using BibTeX?

Add this if you want the number of citations to appear in order in the document they will only be unsorted in the reference page:

\bibliographystyle{unsrt}

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

How to convert DataSet to DataTable

Here is my solution:

DataTable datatable = (DataTable)dataset.datatablename;

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

How do I insert a JPEG image into a python Tkinter window?

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

How to run C program on Mac OS X using Terminal?

For compiling a c program on your latest macOS just type the following in terminal after saving the file with a .c extension and on reaching the path where the file is saved :

cc yourfilename.c

Once you have checked all the errors after compilation (if any), type the following for executing the code :

./a.out

These commands are tested on macOS Mojave and are working perfectly fine, cheers coding!

How do I find and replace all occurrences (in all files) in Visual Studio Code?

This is the best way.

  1. First put your cursor on the member and click F2.

  2. Then type the new name and hit the Enter key. This will rename all of the occurrences in every file in your project.

This is ideal for when you want to rename across multiple files. For example, you may want to rename a publicly accessible function on an Angular service and have everywhere that uses it get updated.

For more great tools I highly recommend: https://johnpapa.net/refactoring-with-visual-studio-code/

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

Just in case if this helps anybody.

Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS

This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)

tkinter was not working even when the help('module') shows tkinter in the list.

The following steps worked for me:

  1. sudo apt-get install tk-dev.

rebuild the python: 1. Navigate to your python folder and run the checks:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. Build using make command: sudo make -j 8 --- here 8 are the number of processors, check yours using nproc command.
  2. Installing using:

    sudo make altinstall
    

Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.

  1. Check tkinter now
    python3.7 -m tkinter
    

A windows box will pop up, your tkinter is ready now.

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

Logcat not displaying my log calls

I have this problems and fixed, String TAG without space:

"my tag" // noting show
"my_tag" // is ok

How do you programmatically set an attribute?

setattr(x, attr, 'magic')

For help on it:

>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.

Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

How can I list all foreign keys referencing a given table in SQL Server?

You should also mind the references to other objects.

If the table was highly referenced by other tables than it’s probably also highly referenced by other objects such as views, stored procedures, functions and more.

I’d really recommend GUI tool such as ‘view dependencies’ dialog in SSMS or free tool like ApexSQL Search for this because searching for dependencies in other objects can be error prone if you want to do it only with SQL.

If SQL is the only option you could try doing it like this.

select O.name as [Object_Name], C.text as [Object_Definition]
from sys.syscomments C
inner join sys.all_objects O ON C.id = O.object_id
where C.text like '%table_name%'

Reading string by char till end of line C/C++

The answer to your original question

How to read a string one char at the time, and stop when you reach end of line?

is, in C++, very simply, namely: use getline. The link shows a simple example:

#include <iostream>
#include <string>
int main () {
  std::string name;
  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";
  return 0;
}

Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.

C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.

Your later questions regarding "\0" and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.

String comparison - Android

if(gender.equals(g1)); <---
if(gender == "Female"); <---

You have semicolon after if.REMOVE IT.

Get HTML code using JavaScript with a URL

For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS

It uses $.ajax() function, so it includes jquery.

Get User's Current Location / Coordinates

 override func viewDidLoad() {

    super.viewDidLoad()       
    locationManager.requestWhenInUseAuthorization();     
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }
    else{
        print("Location service disabled");
    }
  }

This is your view did load method and in the ViewController Class also include the mapStart updating method as follows

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var locValue : CLLocationCoordinate2D = manager.location.coordinate;
    let span2 = MKCoordinateSpanMake(1, 1)    
    let long = locValue.longitude;
    let lat = locValue.latitude;
    print(long);
    print(lat);        
    let loadlocation = CLLocationCoordinate2D(
                    latitude: lat, longitude: long            

   )     

    mapView.centerCoordinate = loadlocation;
    locationManager.stopUpdatingLocation();
}

Also do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project (no longer necessary as of XCode 7.2.1)

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This happened to me when using java sdk. The problem was for me was i wasnt using the session token from assumed role.

Working code example ( in kotlin )

        val identityUserPoolProviderClient = AWSCognitoIdentityProviderClientBuilder
            .standard()
            .withCredentials(AWSStaticCredentialsProvider(BasicSessionCredentials("accessKeyId", ""secretAccessKey, "sessionToken")))
            .build()

Simple DatePicker-like Calendar

this datepicker is an excellent solution. datepickers are a must if you want to avoid code injection.

Wait till a Function with animations is finished until running another Function

Here is a solution for n-calls (recursive function). https://jsfiddle.net/mathew11/5f3mu0f4/7/

function myFunction(array){
var r = $.Deferred();

if(array.length == 0){
    r.resolve();
    return r;
}

var element = array.shift();
// async task 
timer = setTimeout(function(){
    $("a").text($("a").text()+ " " + element);
    var resolving = function(){
        r.resolve();
    }

    myFunction(array).done(resolving);

 }, 500);

return r;
}

//Starting the function
var myArray = ["Hi", "that's", "just", "a", "test"];
var alerting = function (){window.alert("finished!")};
myFunction(myArray).done(alerting);

Passing a string array as a parameter to a function java

look at familiar main method which takes string array as param

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

How to enable or disable an anchor using jQuery?

$("a").click(function(){
                alert('disabled');
                return false;

}); 

How to deal with certificates using Selenium?

In selenium python, you need to set desired_capabilities as:

desired_capabilities = {
    "acceptInsecureCerts": True
}

How to change the server port from 3000?

1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:

{ "port": 1337 }

2->Using Command Line Tool Run this command in Angular-Cli

ng serve --port 1234

To change the port number permanently:

Goto

node_modules/angular-cli/commands/server.js

Search for var defaultPort = process.env.PORT || 4200; (change 4200 to anything else you want).

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

Age from birthdate in python

import datetime

def age(date_of_birth):
    if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
        return datetime.date.today().year - date_of_birth.year - 1
    else:
        return datetime.date.today().year - date_of_birth.year

In your case:

import datetime

# your model
def age(self):
    if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
        return datetime.date.today().year - self.birthdate.year - 1
    else:
        return datetime.date.today().year - self.birthdate.year

Ruby send JSON request

uri = URI('https://myapp.com/api/v1/resource')
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = {param1: 'some value', param2: 'some other value'}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

How do I convert a IPython Notebook into a Python file via commandline?

Following the previous example but with the new nbformat lib version :

import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, modulePath):

  with open(notebookPath) as fh:
    nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)

  exporter = PythonExporter()
  source, meta = exporter.from_notebook_node(nb)

  with open(modulePath, 'w+') as fh:
    fh.writelines(source.encode('utf-8'))

Convert number to month name in PHP

You can do it in just one line:

DateTime::createFromFormat('!m', $salary->month)->format('F'); //April

Access Database opens as read only

In my case it was because it was being backed up my a background process which started before I opened Access. It isn't normally a problem if it have the database open when the backup starts.

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

How do I get elapsed time in milliseconds in Ruby?

Try subtracting the first Time.now from the second. Like so:

a = Time.now
sleep(3)
puts Time.now - a # about 3.0

This gives you a floating-point number of the seconds between the two times (and with that, the milliseconds).

Least common multiple for 3 or more numbers

We have working implementation of Least Common Multiple on Calculla which works for any number of inputs also displaying the steps.

What we do is:

0: Assume we got inputs[] array, filled with integers. So, for example:
   inputsArray = [6, 15, 25, ...]
   lcm = 1

1: Find minimal prime factor for each input.
   Minimal means for 6 it's 2, for 25 it's 5, for 34 it's 17
   minFactorsArray = []

2: Find lowest from minFactors:
   minFactor = MIN(minFactorsArray)

3: lcm *= minFactor

4: Iterate minFactorsArray and if the factor for given input equals minFactor, then divide the input by it:
  for (inIdx in minFactorsArray)
    if minFactorsArray[inIdx] == minFactor
      inputsArray[inIdx] \= minFactor

5: repeat steps 1-4 until there is nothing to factorize anymore. 
   So, until inputsArray contains only 1-s.

And that's it - you got your lcm.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

how to remove css property using javascript?

This should do the trick - setting the inline style to normal for zoom:

$('div').attr("style", "zoom:normal;");

How do I grant myself admin access to a local SQL Server instance?

Microsoft has an article about this issue. It goes through it all step by step.

https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out

In short it involves starting up the instance of sqlserver with -m like all the other answers suggest. However Microsoft provides slightly more detailed instructions.

From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)

In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.

Close Management Studio.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)

Click OK, and after the message to restart, right-click your server name, and then click Restart.

After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.

On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)

Note

For earlier versions of Windows, the Run as administrator option appears as a sub-menu.

In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.

a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.

b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.

CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS;   ALTER SERVER ROLE
sysadmin ADD MEMBER [CONTOSO\PatK];   

c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.

CREATE LOGIN TempLogin WITH PASSWORD = '************';   ALTER
SERVER ROLE sysadmin ADD MEMBER TempLogin;   

Warning:

Replace ************ with a strong password.

d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.

ALTER LOGIN sa WITH PASSWORD = '************';   Warning

Replace ************ with a strong password.

The following steps now change SQL Server back to multi-user mode. Close SSMS.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.

Right-click your server name, and then click Restart.

Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

How to set time zone of a java.util.Date?

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

What's the difference between window.location and document.location in JavaScript?

document.location.constructor === window.location.constructor is true.

It's because it's exactly the same object as you can see from document.location===window.location.

So there's no need to compare the constructor or any other property.

Android List View Drag and Drop sort

Now it's pretty easy to implement for RecyclerView with ItemTouchHelper. Just override onMove method from ItemTouchHelper.Callback:

 @Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mMovieAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

Pretty good tutorial on this can be found at medium.com : Drag and Swipe with RecyclerView

How to extract closed caption transcript from YouTube video?

Choose Open Transcript from the ... dropdown to the right of the vote up/down and share links.

This will open a Transcript scrolling div on the right side.

You can then use Copy. Note that you cannot use Select All but need to click the top line, then scroll to the bottom using the scroll thumb, and then shift-click on the last line.

Note that you can also search within this text using the normal web page search.

Default value for field in Django model

You can set the default like this:

b = models.CharField(max_length=7,default="foobar")

and then you can hide the field with your model's Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

How to add "class" to host element?

for multiple classes situation, as @jbojcic mentioned above, you can use:

host: {class: 'A B C'}

Removing duplicates in the lists

Very simple way in Python 3:

>>> n = [1, 2, 3, 4, 1, 1]
>>> n
[1, 2, 3, 4, 1, 1]
>>> m = sorted(list(set(n)))
>>> m
[1, 2, 3, 4]

What is the syntax for adding an element to a scala.collection.mutable.Map?

The point is that the first line of your codes is not what you expected.

You should use:

val map = scala.collection.mutable.Map[A,B]()

You then have multiple equivalent alternatives to add items:

scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()


scala> map("k1") = "v1"

scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))


scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))


scala> map.put("k3", "v3")
res3: Option[String] = None

scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))

And starting Scala 2.13:

scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)

c# dictionary How to add multiple values for single key?

Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();

foreach(string key in keys) {
    if(!dictionary.ContainsKey(key)) {
        //add
        dictionary.Add(key, new List<string>());
    }
    dictionary[key].Add("theString");
}

If the key doesn't exist, a new List is added (inside if). Else the key exists, so just add a new value to the List under that key.

How can I start PostgreSQL on Windows?

After a lot of search and tests i found the solution : if you are in windows :

1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools

$ show data_directory;

result :

------------------------
- D:/PG_DATA/data      -
------------------------

2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"

and open a command prompt (CMD) and execute this command :

pg_ctl -D "D:\PSG_SQL\data" restart

This should do it.

How to replace ${} placeholders in a text file?

Here's a robust Bash function that - despite using eval - should be safe to use.

All ${varName} variable references in the input text are expanded based on the calling shell's variables.

Nothing else is expanded: neither variable references whose names are not enclosed in {...} (such as $varName), nor command substitutions ($(...) and legacy syntax `...`), nor arithmetic substitutions ($((...)) and legacy syntax $[...]).

To treat a $ as a literal, \-escape it; e.g.:\${HOME}

Note that input is only accepted via stdin.

Example:

$ expandVarsStrict <<<'$HOME is "${HOME}"; `date` and \$(ls)' # only ${HOME} is expanded
$HOME is "/Users/jdoe"; `date` and $(ls)

Function source code:

expandVarsStrict(){
  local line lineEscaped
  while IFS= read -r line || [[ -n $line ]]; do  # the `||` clause ensures that the last line is read even if it doesn't end with \n
    # Escape ALL chars. that could trigger an expansion..
    IFS= read -r -d '' lineEscaped < <(printf %s "$line" | tr '`([$' '\1\2\3\4')
    # ... then selectively reenable ${ references
    lineEscaped=${lineEscaped//$'\4'{/\${}
    # Finally, escape embedded double quotes to preserve them.
    lineEscaped=${lineEscaped//\"/\\\"}
    eval "printf '%s\n' \"$lineEscaped\"" | tr '\1\2\3\4' '`([$'
  done
}

The function assumes that no 0x1, 0x2, 0x3, and 0x4 control characters are present in the input, because those chars. are used internally - since the function processes text, that should be a safe assumption.

Make <body> fill entire screen?

If you have a border or padding, then the solution

_x000D_
_x000D_
html, body {_x000D_
    margin: 0;_x000D_
    height: 100%;_x000D_
}_x000D_
body {_x000D_
    border: solid red 5px;_x000D_
    border-radius: 2em;_x000D_
}
_x000D_
_x000D_
_x000D_

produces the imperfect rendering

not good

To get it right in the presence of a border or padding

good

use instead

_x000D_
_x000D_
html, body {_x000D_
    margin: 0;_x000D_
    height: 100%;_x000D_
}_x000D_
body {_x000D_
    box-sizing: border-box;_x000D_
    border: solid red 5px;_x000D_
    border-radius: 2em;_x000D_
}
_x000D_
_x000D_
_x000D_

as Martin pointed out, although overflow: hidden is not needed.

(2018 - tested with Chrome 69 and IE 11)

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

Calculating Pearson correlation and significance in Python

You may wonder how to interpret your probability in the context of looking for a correlation in a particular direction (negative or positive correlation.) Here is a function I wrote to help with that. It might even be right!

It's based on info I gleaned from http://www.vassarstats.net/rsig.html and http://en.wikipedia.org/wiki/Student%27s_t_distribution, thanks to other answers posted here.

# Given (possibly random) variables, X and Y, and a correlation direction,
# returns:
#  (r, p),
# where r is the Pearson correlation coefficient, and p is the probability
# that there is no correlation in the given direction.
#
# direction:
#  if positive, p is the probability that there is no positive correlation in
#    the population sampled by X and Y
#  if negative, p is the probability that there is no negative correlation
#  if 0, p is the probability that there is no correlation in either direction
def probabilityNotCorrelated(X, Y, direction=0):
    x = len(X)
    if x != len(Y):
        raise ValueError("variables not same len: " + str(x) + ", and " + \
                         str(len(Y)))
    if x < 6:
        raise ValueError("must have at least 6 samples, but have " + str(x))
    (corr, prb_2_tail) = stats.pearsonr(X, Y)

    if not direction:
        return (corr, prb_2_tail)

    prb_1_tail = prb_2_tail / 2
    if corr * direction > 0:
        return (corr, prb_1_tail)

    return (corr, 1 - prb_1_tail)

JavaScript and Threads

The new v8 engine which should come out today supports it (i think)

Pass value to iframe from a window

Depends on your specific situation, but if the iframe can be deployed after the rest of the page's loading, you can simply use a query string, a la:

<iframe src="some_page.html?somedata=5&more=bacon"></iframe>

And then somewhere in some_page.html:

<script>
var params = location.href.split('?')[1].split('&');
data = {};
for (x in params)
 {
data[params[x].split('=')[0]] = params[x].split('=')[1];
 }
</script>

How to select a radio button by default?

They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:

<input type="radio" checked="checked">

...and you got it.

Cheers!

Virtualbox shared folder permissions

Try this (on the guest machine. i.e. the OS running in the Virtual box):

sudo adduser your-user vboxsf

Now reboot the OS running in the virtual box.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

adding using Microsoft.EntityFrameworkCore;

manually solved the problem for me

Found that here

Edit...

for dotnet core 3.1 add

Microsoft.EntityFrameworkCore.SqlServer

WPF binding to Listbox selectedItem

Yocoder is right,

Inside the DataTemplate, your DataContext is set to the Rule its currently handling..

To access the parents DataContext, you can also consider using a RelativeSource in your binding:

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />

More info on RelativeSource can be found here:

http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx

Datetime in where clause

Assuming we're talking SQL Server DateTime

Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:

errorDate BETWEEN '12/20/2008' AND '12/21/2008'

My preferred method for a time range like that is:

'20081220' <= errorDate AND errordate < '20081221'

Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)

Rollback transaction after @Test

You need to run your test with a Spring context and a transaction manager, e.g.,

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"/your-applicationContext.xml"})
@TransactionConfiguration(transactionManager="txMgr")
public class StudentSystemTest {

     @Test
     public void testTransactionalService() {
         // test transactional service
     }

     @Test
     @Transactional
     public void testNonTransactionalService() {
         // test non-transactional service
     }
}

See chapter 3.5.8. Transaction Management of the Spring reference for further details.

Switch php versions on commandline ubuntu 16.04

May be you might have an old PHP version like PHP 5.6 in your system and you installed PHP 7.2 too so thats multiple PHP in your machine. There are some applications which were developed when older PHP 5.6 was latest version, they are still live and you working on those applications, You might be working on Laravel simultaneously but Laravel requires PHP 7+ to get started. Getting the picture ?

In that case you can switch between the PHP versions to suit your requirements.

Switch From PHP 5.6 => PHP 7.2

Apache:-

sudo a2dismod php5.6
sudo a2enmod php7.2
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php7.2
sudo update-alternatives --set phar /usr/bin/phar7.2
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.2
sudo update-alternatives --set phpize /usr/bin/phpize7.2
sudo update-alternatives --set php-config /usr/bin/php-config7.2

And vice-versa, Switch From PHP 7.2 => PHP 5.6

Apache:-

sudo a2dismod php7.2
sudo a2enmod php5.6
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6
sudo update-alternatives --set phpize /usr/bin/phpize5.6
sudo update-alternatives --set php-config /usr/bin/php-config5.6

Converting binary to decimal integer output

a = input('Enter a binary number : ')
ar = [int(i) for  i in a]
ar  = ar[::-1]
res = []
for i in range(len(ar)):
    res.append(ar[i]*(2**i))
sum_res = sum(res)      
print('Decimal Number is : ',sum_res)

Ways to insert javascript into URL?

old question that I stumbled into that I believe deserves an update... You can infact execute javascript from the URL, and you can get creative about it too. I recently made a members only area that I wanted to remind someone what their password was, so I was looking for a non-local alert...of course you can embed an alert into the page itself, but then its public. the difference here is I can create a link and slip some JS into the href so clicking on the link will generate the alert.

here is what I mean >>

<a href="javascript:alert('the secret is to ask.');window.location.replace('http://google.com');">You can have anything</a>

and so upon clicking the link, the user is given an alert with the info, then they are taken to the new page.

obviously you could also write an onClick, but the href works just fine when you slip it through the URL, just remember to prepend it with "javascript:"

*works in chrome, didnt check anything else.

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

To switch to C99 mode in CodeBlocks, follow the next steps:

Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok.

This will turn C99 mode on for your Compiler.

I hope this will help someone!

How to actually search all files in Visual Studio

Press Ctrl+,

Then you will see a docked window under name of "Go to all"

This a picture of the "Go to all" in my IDE

Picture

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

Entity Framework: table without primary key

I`m very happy my problem is solved.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

and do this : Look below that line and find the tag. It will have a big ol' select statement in it. Remove the tag and it's contents..

now without changing DB T I can insert to a table which has not PK

thanks all and thank Pharylon

Maintain aspect ratio of div but fill screen width and height in CSS?

Just reformulating Danield's answer in a LESS mixin, for further usage:

// Mixin for ratio dimensions    
.viewportRatio(@x, @y) {
  width: 100vw;
  height: @y * 100vw / @x;
  max-width: @x / @y * 100vh;
  max-height: 100vh;
}

div {

  // Force a ratio of 5:1 for all <div>
  .viewportRatio(5, 1);

  background-color: blue;
  margin: 0;
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

Bash scripting missing ']'

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

Adding text to ImageView in Android

Use drawalbeLeft/Right/Bottom/Top in TextView to render image at respective position.

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/image"    
        android:text="@strings/text" 
        />

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Your module is not yet loaded by the Angular Server in node ng serve, so restart your server so the server loads the module that you just added in @NgModule app.module.ts

jQuery: Check if button is clicked

$('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

bootstrap initially collapsed element

Just add class "show" to the collapsing element's class, bootstrap will use js dynamically to remove it to collapse and show

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I had this problem during migration to Spring Boot. I've found a advice to remove dependencies and it helped. So, I removed dependency for jsp-api Project had. Also, servlet-api dependency has to be removed as well.

compileOnly group: 'javax.servlet.jsp', name: 'jsp-api', version: '2.2' 

How to run Visual Studio post-build events for debug build only

This works for me in Visual Studio 2015.

I copy all DLL files from a folder located in a library folder on the same level as my solution folder into the targetdirectory of the project being built.

Using a relative path from my project directory and going up the folder structure two steps with..\..\lib

MySolutionFolder
....MyProject
Lib

if $(ConfigurationName) == Debug (
xcopy /Y "$(ProjectDir)..\..\lib\*.dll" "$(TargetDir)"
) ELSE (echo "Not Debug mode, no file copy from lib")

How do I get the first n characters of a string without checking the size or going out of bounds?

Here's a neat solution:

String upToNCharacters = s.substring(0, Math.min(s.length(), n));

Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value

How to center buttons in Twitter Bootstrap 3?

I had this problem. I used

<div class = "col-xs-8 text-center">

On my div containing a few h3 lines, a couple h4 lines and a Bootstrap button. Everything besides the button jumped to the center after I used text-center so I went into my CSS sheet overriding Bootstrap and gave the button a

margin: auto;

which seems to have solved the problem.

pandas dataframe groupby datetime month

(update: 2018)

Note that pd.Timegrouper is depreciated and will be removed. Use instead:

 df.groupby(pd.Grouper(freq='M'))

How to put more than 1000 values into an Oracle IN clause

I am almost sure you can split values across multiple INs using OR:

select * from table1 where ID in (1,2,3,4,...,1000) or 
ID in (1001,1002,...,2000)

Attach the Java Source Code

enter image description here

if you are add jre and jkd path, remove jre install path, keep jdk path is work

Can't install nuget package because of "Failed to initialize the PowerShell host"

I had the same problem after upgrading to Windows 10.

This worked for me

  1. Close Visual Studio
  2. Run Powershell as admin
  3. Run Set-ExecutionPolicy Unrestricted
  4. Run Visual studio as admin
  5. Clean the project and add the nuget package

If it still doesn't work try editing devenv.exe.config

Visual Studio 2013: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\12.0

Visual Studio 2015: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\14.0

Add the following

    <dependentAssembly>
        <assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
        <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Utility" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.ConsoleHost" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Management" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Security" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Diagnostics" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How do I capture response of form.submit

I am not sure that you understand what submit() does...

When you do form1.submit(); the form information is sent to the webserver.

The WebServer will do whatever its supposed to do and return a brand new webpage to the client(usually the same page with something changed).

So, there is no way you can "catch" the return of a form.submit() action.

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

How to force Selenium WebDriver to click on element which is not currently visible?

I had the same problem with selenium 2 in internet explorer 9, but my fix is really strange. I was not able to click into inputs inside my form -> selenium repeats, their are not visible.

It occured when my form had curved shadows -> http://www.paulund.co.uk/creating-different-css3-box-shadows-effects: in the concrete "Effect no. 2"

I have no idea, why&how this pseudo element solution's stopped selenium tests, but it works for me.

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

GDB: Listing all mapped memory regions for a crashed process

(gdb) maintenance info sections 
Exec file:
    `/path/to/app.out', file type elf32-littlearm.
    0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS

This is from comment by phihag above, deserves a separate answer. This works but info proc does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

How to check what user php is running as?

You can use these commands :

<? system('whoami');?>

or

<? passthru('whoami');?>

or

<? print exec('whoami');?>

or

<? print shell_exec('whoami');?>

Be aware, the get_current_user() returns the name of the owner of the current PHP script !

Disabled UIButton not faded or grey

You can use adjustsImageWhenDisabled which is property of UIButton
(@property (nonatomic) BOOL adjustsImageWhenDisabled)

Ex:

 Button.adjustsImageWhenDisabled = false

How to SSH to a VirtualBox guest externally through a host?

A good explanation about how to configure port forwarding with NAT is found in the VirtualBox documents: http://www.virtualbox.org/manual/ch06.html#natforward

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

Installing Tomcat 7 as Service on Windows Server 2008

its done through service.bat file in apache tomcat7

visit this blog .. install tomcat7 on windows

Java to Jackson JSON serialization: Money fields

I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.

private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
    return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

Android Studio: /dev/kvm device permission denied

Provide appropriate permissions with this command

sudo chmod 777 -R /dev/kvm

Bundling data files with PyInstaller (--onefile)

For those of whom are still looking for a more recent answer, here you go:

In the documentation, there's a section on accessing added data files.
Here is the short and sweet of it.


You'll want to import pkgutil and locate which folder you added the datafile to; i.e. the second string in the tuple which was added to the spec file:

datas = [("path/to/mypackage/data_file.txt", "path/to/mypackage")]

Knowing where you added the data file can then be used for reading it in as binary data, and decoding it as you wish. Take this example:

File structure:

mypackage
      __init__.py  # This is a MUST in order for the package to be registered
      data_file.txt  # The data file you've added

data_file.txt

Hello world!

main.py

import pkgutil

file = pkgutil.get_data("mypackage", "data_file.txt")
contents = file.decode("utf-8")
print(contents)  # Hello world!

References:

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

How to Load Ajax in Wordpress

Use wp_localize_script and pass url there:

wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );

then inside js, you can call it by

admin_url.ajax_url