Programs & Examples On #Syncdb

Django: OperationalError No Such Table

The issue may be solved by running migrations.

  1. python manage.py makemigrations
  2. python manage.py migrate

perform the operations above whenever you make changes in models.py.

How to reset db in Django? I get a command 'reset' not found error

If you want to clean the whole database, you can use: python manage.py flush If you want to clean database table of a Django app, you can use: python manage.py migrate appname zero

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

You are missing the python mysqldb library. Use this command (for Debian/Ubuntu) to install it: sudo apt-get install python-mysqldb

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

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Rationale for the / POSIX PATH rule

The rule was mentioned at: Why do you need ./ (dot-slash) before executable or script name to run it in bash? but I would like to explain why I think that is a good design in more detail.

First, an explicit full version of the rule is:

  • if the path contains / (e.g. ./someprog, /bin/someprog, ./bin/someprog): CWD is used and PATH isn't
  • if the path does not contain / (e.g. someprog): PATH is used and CWD isn't

Now, suppose that running:

someprog

would search:

  • relative to CWD first
  • relative to PATH after

Then, if you wanted to run /bin/someprog from your distro, and you did:

someprog

it would sometimes work, but others it would fail, because you might be in a directory that contains another unrelated someprog program.

Therefore, you would soon learn that this is not reliable, and you would end up always using absolute paths when you want to use PATH, therefore defeating the purpose of PATH.

This is also why having relative paths in your PATH is a really bad idea. I'm looking at you, node_modules/bin.

Conversely, suppose that running:

./someprog

Would search:

  • relative to PATH first
  • relative to CWD after

Then, if you just downloaded a script someprog from a git repository and wanted to run it from CWD, you would never be sure that this is the actual program that would run, because maybe your distro has a:

/bin/someprog

which is in you PATH from some package you installed after drinking too much after Christmas last year.

Therefore, once again, you would be forced to always run local scripts relative to CWD with full paths to know what you are running:

"$(pwd)/someprog"

which would be extremely annoying as well.

Another rule that you might be tempted to come up with would be:

relative paths use only PATH, absolute paths only CWD

but once again this forces users to always use absolute paths for non-PATH scripts with "$(pwd)/someprog".

The / path search rule offers a simple to remember solution to the about problem:

  • slash: don't use PATH
  • no slash: only use PATH

which makes it super easy to always know what you are running, by relying on the fact that files in the current directory can be expressed either as ./somefile or somefile, and so it gives special meaning to one of them.

Sometimes, is slightly annoying that you cannot search for some/prog relative to PATH, but I don't see a saner solution to this.

How to set up a PostgreSQL database in Django

Please note that installation of psycopg2 via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat). If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here.

How to use MySQLdb with Python and Django in OSX 10.6?

I overcame the same problem by installing MySQL-python library using pip. You can see the message displayed on my console when I first changed my database settings in settings.py and executed makemigrations command(The solution is following the below message, just see that).

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Finally I overcame this problem as follows:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 112kB 364kB/s 
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$ 

Show a PDF files in users browser via PHP/Perl

    $url ="https://yourFile.pdf";
    $content = file_get_contents($url);

    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: inline; filename="YourFileName.pdf"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    ini_set('zlib.output_compression','0');

    die($content);

Tested and works fine. If you want the file to download instead, replace

    Content-Disposition: inline

with

    Content-Disposition: attachment

Using <style> tags in the <body> with other HTML

I guess this may be an issue about limited contexts, e.g. WYIWYG editors on a web system used by not-programmers users, that limits the possibilities of follow the standards. Sometimes (like TinyMCE), it's a lib that puts your content/code inside a textarea tag, that is rendered by the editor as a big div tag. And sometimes, it may be an old version of these editors.

I'm supposing that:

  1. these not-programmers users don't have an open channel with the system admins (or institution's webdevs), to ask for including some CSS rules at the system's stylesheets. Actually, it would be impractical for the admins (or webdevs), considering the number of requests in that sense that they would have.
  2. this system is legacy and still doesn't support newer versions of HTML.

In some cases, without use style rules, it may be a very poor design experience. So, yes, these users need customization. Okay, but what would be the solutions, in this scenario? Considering the different ways to insert CSS in a html page, I suppose these solutions:


1st option: ask your sysadm

Ask to your system adm for including some CSS rules at the system's stylesheets. This will be an external or internal CSS solution. As already said, it might be not possible.


2nd option: <link> on <body>

Use external style sheet on the body tag, i.e., use of the link tag inside the area you have access (that will be, on the site, inside the body tag and not in the head tag). Some sources says this is okay, but "not a good practice", like MDN:

A <link> element can occur either in the <head> or <body> element, depending on whether it has a link type that is body-ok. For example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head>.

Some others, restrict it to the <head> section, like w3schools:

Note: This element goes only in the head section, but it can appear any number of times.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <link href="bar.css" type="text/css" rel="stylesheet">
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
</body>
</html>

And then a CSS file, at the same directory, called bar.css:

.test1 { 
    color: green;
};

Well, this will just looks possible if you have how upload an CSS file somewhere at the institution system. Maybe this would be the case.


3rd option: <style> on <body>

Use internet style sheet on the body tag, i.e., use of the style tag inside the area you have access (that will be, on the site, inside the body tag and not in the head tag). This is what Charles Salvia's and Sz's answers here are about. Choosing this option, consider their concerns.


4th, 5th and 6th options: JS ways

Alert These ones are related to modifying the <head> element of the page. Maybe this will not be allowed by the institution's system administrators. So, it's recommended to ask them permission first.

Okay, supposing permission granted, the strategy is access the <head>. How? JavaScript methods.

4th option: new <link> on <head>

This is another version of the 2nd option. Use external style sheet on the <head> tag, i.e., use of the <link> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag). This solution complies with the recommendations of MDN and w3schools, as cited above, on 2nd option solution. A new Link object will be created.

To solve the matter through JS, there are many ways but at the following codelines I demonstrate one simple.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file f.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the script tag:

var newLink = document.createElement("link");
newLink.href = "bar.css";
newLink.rel = "stylesheet";
newLink.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(newLink);

And then at the CSS file, at the same directory, called bar.css (as at the 2nd option):

.test1 { 
    color: green;
};

As I already said: this will just looks possible if you have how upload an CSS file somewhere at the institution system.

5th option: new <style> on <head>

Use new internal style sheet on the <head> tag, i.e., use of a new <style> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag). A new Style object will be created.

This is solved through JS. One simple way is demonstrated following.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foobar.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the script tag:

var newStyle = document.createElement("style");
newStyle.innerHTML = 
    "h1.test1 {"+
        "color: green;"+
    "}";
document.getElementsByTagName("head")[0].appendChild(newStyle);

6th option: using an existing <style> on <head>

Use an existing internal style sheet on the <head> tag, i.e., use of a <style> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag), if some exists. A new Style object will be created or a CSSStyleSheet object will be used (in the code of the solution adopted here).

This is at some point of view risky. First, because it may not exists some <style> object. Depending of the way you implement this solution, you may get undefined return (the system may use external style sheet). Second, because you will be editing the system design author's work (authorship issues). Third, because it may not be allowed at your institution's IT politics of safety. So, do ask permission to do this (as at in other JS solutions).

Supposing, again, permission was granted:

You will need to consider some restrictions of the method available to this way: insertRule(). The solution proposed uses the default scenario, and a operation at the first stylesheet, if some exists.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo_bar.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
      // JS code here
    </script>
  </body>
</html>

Inside the script tag:

function demoLoop(){ // remove this line
    var elmnt = document.getElementsByTagName("style");
    if (elmnt.length === 0) {
        // there isn't style objects, so it's more interesting create one
        var newStyle = document.createElement("style");
        newStyle.innerHTML =
            "h1.test1 {" +
                "color: green;" +
            "}";
        document.getElementsByTagName("head")[0].appendChild(newStyle);
    } else {
        // Using CSSStyleSheet interface
        var firstCSS = document.styleSheets[0];
        firstCSS.insertRule("h1.test2{color:blue;}"); // at this way (without index specified), will be like an Array unshift() method
    }
} // remove this too
demoLoop(); // remove this too
demoLoop(); // remove this too

Another approach to this solution it's using CSSStyleDeclaration object (docs at w3schools and MDN). But it may not be interesting, considering the risk to override existing rules on the system's CSS.


7th option: inline CSS

Use inline CSS. This solve the problem, although depending of the page size (in code lines), the maintenance (by the author itself or other assigned person) of code can be very difficult.

But depending of the context of your role at the institution, or its web system security policies, this might be the unique available solution to you.

Testing

Create a file _foobar.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 style="color: green;">Hello</h1>
    <h1 style="color: blue;">World</h1>    
  </body>
</html>

Answering strictly the question asked by Gagan

How is a browser supposed to render css which is non contiguous?

  1. Is it supposed to generate some data structure using all the css styles on a page and use that for rendering?
  2. Or does it render using style information in the order it sees?

(quote adapted)

For a more accurate answer, I suggest Google these articles:

  • How Browsers Work: Behind the scenes of modern web browsers
  • Render-tree Construction, Layout, and Paint
  • What Does It Mean To “Render” a Webpage?
  • How browser rendering works — behind the scenes
  • Rendering - HTML Standard
  • 10 Rendering — HTML5

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

The top answers in this question may be misleading in some cases. Imagine that the file, whose absolute path you want to find, is in the $PATH variable:

# node is in $PATH variable
type -P node
# /home/user/.asdf/shims/node
cd /tmp
touch node
readlink -e node
# /tmp/node
readlink -m node
# /tmp/node
readlink -f node
# /tmp/node
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node
realpath node
# /tmp/node
realpath -e node
# /tmp/node

# Now let's say that for some reason node does not exist in current directory
rm node
readlink -e node
# <nothing printed>
readlink -m node    
# /tmp/node         # Note: /tmp/node does not exist, but is printed
readlink -f node
# /tmp/node         # Note: /tmp/node does not exist, but is printed
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node         # Note: /tmp/node does not exist, but is printed
realpath node
# /tmp/node         # Note: /tmp/node does not exist, but is printed
realpath -e node
# realpath: node: No such file or directory

Based on the above I can conclude that: realpath -e and readlink -e can be used for finding the absolute path of a file, that we expect to exist in current directory, without result being affected by the $PATH variable. The only difference is that realpath outputs to stderr, but both will return error code if file is not found:

cd /tmp
rm node
realpath -e node ; echo $?
# realpath: node: No such file or directory
# 1
readlink -e node ; echo $?
# 1

Now in case you want the absolute path a of a file that exists in $PATH, the following command would be suitable, independently on whether a file with same name exists in current dir.

type -P example.txt
# /path/to/example.txt

# Or if you want to follow links
readlink -e $(type -P example.txt)
# /originalpath/to/example.txt

# If the file you are looking for is an executable (and wrap again through `readlink -e` for following links )
which executablefile
# /opt/bin/executablefile

And a, fallback to $PATH if missing, example:

cd /tmp
touch node
echo $(readlink -e node || type -P node)
# /tmp/node
rm node
echo $(readlink -e node || type -P node)
# /home/user/.asdf/shims/node

How to set the timeout for a TcpClient?

Another alternative using https://stackoverflow.com/a/25684549/3975786:

var timeOut = TimeSpan.FromSeconds(5);     
var cancellationCompletionSource = new TaskCompletionSource<bool>();
try
{
    using (var cts = new CancellationTokenSource(timeOut))
    {
        using (var client = new TcpClient())
        {
            var task = client.ConnectAsync(hostUri, portNumber);

            using (cts.Token.Register(() => cancellationCompletionSource.TrySetResult(true)))
            {
                if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
                {
                    throw new OperationCanceledException(cts.Token);
                }
            }

            ...

        }
    }
}
catch(OperationCanceledException)
{
    ...
}

Python memory leaks

As far as best practices, keep an eye for recursive functions. In my case I ran into issues with recursion (where there didn't need to be). A simplified example of what I was doing:

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    .....
    my_flag = True
    if my_flag:  # restart the function if a certain flag is true
        my_function()

def main():
    my_function()

operating in this recursive manner won't trigger the garbage collection and clear out the remains of the function, so every time through memory usage is growing and growing.

My solution was to pull the recursive call out of my_function() and have main() handle when to call it again. this way the function ends naturally and cleans up after itself.

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    .....
    my_flag = True
    .....
    return my_flag

def main():
    result = my_function()
    if result:
        my_function()

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

How to remove .html from URL?

This should work for you:

#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

Index of element in NumPy array

This problem can be solved efficiently using the numpy_indexed library (disclaimer: I am its author); which was created to address problems of this type. npi.indices can be viewed as an n-dimensional generalisation of list.index. It will act on nd-arrays (along a specified axis); and also will look up multiple entries in a vectorized manner as opposed to a single item at a time.

a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]

import numpy_indexed as npi
assert all(i == npi.indices(a, b))

This solution has better time complexity (n log n at worst) than any of the previously posted answers, and is fully vectorized.

How can I selectively merge or pick changes from another branch in Git?

I would do a

git diff commit1..commit2 filepattern | git-apply --index && git commit

This way you can limit the range of commits for a filepattern from a branch.

It is stolen from Re: How to pull only a few files from one branch to another?

Axios get access to response header fields

This really helped me, thanks Nick Uraltsev for your answer.

For those of you using nodejs with cors:

...
const cors = require('cors');

const corsOptions = {
  exposedHeaders: 'Authorization',
};

app.use(cors(corsOptions));
...

In the case you are sending the response in the way of res.header('Authorization', `Bearer ${token}`).send();

Node.js create folder or use existing

I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

LAST UPDATE :

In v10.12.0, NodeJS impletement recursive options :

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

UPDATE :

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create 
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');

How to check if activity is in foreground or in visible background?

I don't know why nobody talked about sharedPreferences, for Activity A,setting a SharedPreference like that (for example in onPause() ) :

SharedPreferences pref = context.getSharedPreferences(SHARED_PREF, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("is_activity_paused_a", true);
editor.commit();

I think this is the reliable way to track activities visibilty.

TempData keep() vs peek()

Keep() method marks the specified key in the dictionary for retention

You can use Keep() when prevent/hold the value depends on additional logic.

when you read TempData one’s and want to hold for another request then use keep method, so TempData can available for next request as above example.

Style bottom Line in Android

Try next xml drawable code:

    <layer-list>
        <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
            <shape>
                <solid android:color="@android:color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="#fff" />
            </shape>
        </item>
    </layer-list>

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Hbase quickly count number of rows

You can use the count method in hbase to count the number of rows. But yes, counting rows of a large table can be slow.count 'tablename' [interval]

Return value is the number of rows.

This operation may take a LONG time (Run ‘$HADOOP_HOME/bin/hadoop jar hbase.jar rowcount’ to run a counting mapreduce job). Current count is shown every 1000 rows by default. Count interval may be optionally specified. Scan caching is enabled on count scans by default. Default cache size is 10 rows. If your rows are small in size, you may want to increase this parameter.

Examples:

hbase> count 't1'

hbase> count 't1', INTERVAL => 100000

hbase> count 't1', CACHE => 1000

hbase> count 't1', INTERVAL => 10, CACHE => 1000

The same commands also can be run on a table reference. Suppose you had a reference to table 't1', the corresponding commands would be:

hbase> t.count

hbase> t.count INTERVAL => 100000

hbase> t.count CACHE => 1000

hbase> t.count INTERVAL => 10, CACHE => 1000

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

What precisely does 'Run as administrator' do?

A little clearer... A software program that has kernel mode access has total access to all of the computer's data and its hardware.

Since Windows Vista Microsoft has stopped any and all I/O processes from accessing the kernel (ring 0) directly ever again. The closest we get is a folder created as a virtual kernel access partition, but technically no access to kernel itself; the kernel meets halfway.

This is because the software itself dictates which token to use, so if it asks for an administrator access token, instead of just allowing communications with the kernel like on Windows XP you are prompted to allow access to the kernel, each and every time. Changing UAC could reduce prompts, but never the kernel prompts.

Even when you login as an Administrator, you are running processes as a standard user until prompted to elevate the rights you have. I believe logged in as the administrator saves you from entering the credentials. But it also writes to the administrator users folder structure.

Kernel access is similar to root access in Linux. When you elevate your permissions you are isolating yourself from the root of C:\ and whatever lovely environment variables are contained within.

If you remember BSODs this was the OS shutting down when it believed a bad I/O reached the kernel.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

There are a few functions like:

NSStringFromCGPoint  
NSStringFromCGSize  
NSStringFromCGRect  
NSStringFromCGAffineTransform  
NSStringFromUIEdgeInsets

An example:

NSLog(@"rect1: %@", NSStringFromCGRect(rect1));

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

What is the difference between Left, Right, Outer and Inner Joins?

Simple Example: Let's say you have a Students table, and a Lockers table. In SQL, the first table you specify in a join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

Each student can be assigned to a locker, so there is a LockerNumber column in the Student table. More than one student could potentially be in a single locker, but especially at the beginning of the school year, you may have some incoming students without lockers and some lockers that have no students assigned.

For the sake of this example, let's say you have 100 students, 70 of which have lockers. You have a total of 50 lockers, 40 of which have at least 1 student and 10 lockers have no student.

INNER JOIN is equivalent to "show me all students with lockers".
Any students without lockers, or any lockers without students are missing.
Returns 70 rows

LEFT OUTER JOIN would be "show me all students, with their corresponding locker if they have one".
This might be a general student list, or could be used to identify students with no locker.
Returns 100 rows

RIGHT OUTER JOIN would be "show me all lockers, and the students assigned to them if there are any".
This could be used to identify lockers that have no students assigned, or lockers that have too many students.
Returns 80 rows (list of 70 students in the 40 lockers, plus the 10 lockers with no student)

FULL OUTER JOIN would be silly and probably not much use.
Something like "show me all students and all lockers, and match them up where you can"
Returns 110 rows (all 100 students, including those without lockers. Plus the 10 lockers with no student)

CROSS JOIN is also fairly silly in this scenario.
It doesn't use the linked lockernumber field in the students table, so you basically end up with a big giant list of every possible student-to-locker pairing, whether or not it actually exists.
Returns 5000 rows (100 students x 50 lockers). Could be useful (with filtering) as a starting point to match up the new students with the empty lockers.

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

window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.

How to replace substrings in windows batch file

SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%

EDIT

Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.

Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:

@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
  SET "line=%%L"
  SETLOCAL ENABLEDELAYEDEXPANSION
  ECHO !line:bath=hello!
  ENDLOCAL
)
ENDLOCAL

You can add a redirection to a file:

  ECHO !line:bath=hello!>>file2.txt

Or you can apply the redirection to the batch file. It must be a different file.

EDIT 2

Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !, ^ et al. (Thanks, jeb!)

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Syntax for async arrow function

Async arrow functions look like this:

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

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

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

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

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

The anonymous form works as well:

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

An async function declaration looks like this:

async function foo() {
  // do something
}

Using async function in a callback:

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

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

Counting DISTINCT over multiple columns

It works for me. In oracle:

SELECT SUM(DECODE(COUNT(*),1,1,1))
FROM DocumentOutputItems GROUP BY DocumentId, DocumentSessionId;

In jpql:

SELECT SUM(CASE WHEN COUNT(i)=1 THEN 1 ELSE 1 END)
FROM DocumentOutputItems i GROUP BY i.DocumentId, i.DocumentSessionId;

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

How do I overload the square-bracket operator in C#?

If you mean the array indexer,, You overload that just by writing an indexer property.. And you can overload, (write as many as you want) indexer properties as long as each one has a different parameter signature

public class EmployeeCollection: List<Employee>
{
    public Employee this[int employeeId]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.EmployeeId == employeeId)
                    return emp;
            }

            return null;
        }
    }

    public Employee this[string employeeName]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.Name == employeeName)
                    return emp;
            }

            return null;
        }
    }
}

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

Move all files except one

The following is not a 100% guaranteed method, and should not at all be attempted for scripting. But some times it is good enough for quick interactive shell usage. A file file glob like

[abc]*

(which will match all files with names starting with a, b or c) can be negated by inserting a "^" character first, i.e.

[^abc]*

I sometimes use this for not matching the "lost+found" directory, like for instance:

mv /mnt/usbdisk/[^l]* /home/user/stuff/.

Of course if there are other files starting with l I have to process those afterwards.

What's the difference between a null pointer and a void pointer?

Null pointer is a special reserved value of a pointer. A pointer of any type has such a reserved value. Formally, each specific pointer type (int *, char * etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.

Void pointer is a specific pointer type - void * - a pointer that points to some data location in storage, which doesn't have any specific type.

So, once again, null pointer is a value, while void pointer is a type. These concepts are totally different and non-comparable. That essentially means that your question, as stated, is not exactly valid. It is like asking, for example, "What is the difference between a triangle and a car?".

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

Make sure that "android-support-v4.jar" is unchecked in Order and Export tab under Java Build Path

Follow the steps:

  1. Project Properties
  2. Java Build path
  3. Order and Export
  4. Uncheck "android-support-v4.jar"

std::string to float or double

Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.

Your own version could look like:

template<typename to, typename from>to lexical_cast(from const &x) {
  std::stringstream os;
  to ret;

  os << x;
  os >> ret;

  return ret;  
}

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

lodash multi-column sortBy descending

Is there some handy way of defining direction per column?

No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.

You might be able to do

 _.each(array_of_objects, function(o) {
     o.typeDesc = -o.type; // assuming a number
 });
 _.sortBy(array_of_objects, ['typeDesc', 'name'])

For everything else, you will need to resort to the native .sort() with a custom comparison function:

 array_of_objects.sort(function(a, b) {
     return a.type - b.type // asc
         || +(b.name>a.name)||-(a.name>b.name) // desc
         || …;
 });

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

Which characters are valid in CSS class names/selectors?

The complete regular expression is:

-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*

So all of your listed character except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the unicode notation foo\7E bar.

Is try-catch like error handling possible in ASP Classic?

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

http://www.15seconds.com/issue/020821.htm

Here is a link to Archive.org's version

How to name Dockerfiles

I know this is an old question, with quite a few answers, but I was surprised to find that no one was suggesting the naming convention used in the official documentation:

$ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug .
$ docker build -f dockerfiles/Dockerfile.prod  -t myapp_prod .

The above commands will build the current build context (as specified by the .) twice, once using a debug version of a Dockerfile and once using a production version.

In summary, if you have a file called Dockerfile in the root of your build context it will be automatically picked up. If you need more than one Dockerfile for the same build context, the suggested naming convention is:

Dockerfile.<purpose>

These dockerfiles could be in the root of your build context or in a subdirectory to keep your root directory more tidy.

sed: print only matching group

I agree with @kent that this is well suited for grep -o. If you need to extract a group within a pattern, you can do it with a 2nd grep.

# To extract \1 from /xx([0-9]+)yy/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'xx[0-9]+yy' | grep -Eo '[0-9]+'
123
4

# To extract \1 from /a([0-9]+)b/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'a[0-9]+b' | grep -Eo '[0-9]+'
678
9

I generally cringe when I see 2 calls to grep/sed/awk piped together, but it's not always wrong. While we should exercise our skills of doing things efficiently, "A foolish consistency is the hobgoblin of little minds", and "Real artists ship".

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, the command is simpler tesseract imagename outputbase digits according to the FAQ. But it doesn't work for me very well.

I turn to try different psm options and find -psm 6 works best for my case.

man tesseract for details.

Validate phone number with JavaScript

If you using on input tag than this code will help you. I write this code by myself and I think this is very good way to use in input. but you can change it using your format. It will help user to correct their format on input tag.

$("#phone").on('input', function() {  //this is use for every time input change.
        var inputValue = getInputValue(); //get value from input and make it usefull number
        var length = inputValue.length; //get lenth of input

        if (inputValue < 1000)
        {
            inputValue = '1('+inputValue;
        }else if (inputValue < 1000000) 
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, length);
        }else if (inputValue < 10000000000) 
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, length);
        }else
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, 10);
        }       
        $("#phone").val(inputValue); //correct value entered to your input.
        inputValue = getInputValue();//get value again, becuase it changed, this one using for changing color of input border
       if ((inputValue > 2000000000) && (inputValue < 9999999999))
      {
          $("#phone").css("border","black solid 1px");//if it is valid phone number than border will be black.
      }else
      {
          $("#phone").css("border","red solid 1px");//if it is invalid phone number than border will be red.
      }
  });

    function getInputValue() {
         var inputValue = $("#phone").val().replace(/\D/g,'');  //remove all non numeric character
        if (inputValue.charAt(0) == 1) // if first character is 1 than remove it.
        {
            var inputValue = inputValue.substring(1, inputValue.length);
        }
        return inputValue;
}

What does the "at" (@) symbol do in Python?

Starting with Python 3.5, the '@' is used as a dedicated infix symbol for MATRIX MULTIPLICATION (PEP 0465 -- see https://www.python.org/dev/peps/pep-0465/)

Uri not Absolute exception getting while calling Restful Webservice

An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.

http://docs.oracle.com/javase/8/docs/api/java/net/URI.html

So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?

    URLEncoder.encode(uri) 

Most efficient way to get table row count

SELECT id FROM table ORDER BY id DESC LIMIT 1 can returns max id not auto increment id. both are different in some conditions

initialize a const array in a class initializer in C++

It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).

TimeSpan to DateTime conversion

A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.

Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?

public void should_return_totaldays()
{
    _ts = new TimeSpan(2, 1, 30, 10);
    var format = "dd";
    var returnedVal = _ts.ToString(format);
    Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}

What's the better (cleaner) way to ignore output in PowerShell?

There is also the Out-Null cmdlet, which you can use in a pipeline, for example, Add-Item | Out-Null.

Manual page for Out-Null

NAME
    Out-Null

SYNOPSIS
    Deletes output instead of sending it to the console.


SYNTAX
    Out-Null [-inputObject <psobject>] [<CommonParameters>]


DETAILED DESCRIPTION
    The Out-Null cmdlet sends output to NULL, in effect, deleting it.


RELATED LINKS
    Out-Printer
    Out-Host
    Out-File
    Out-String
    Out-Default

REMARKS
     For more information, type: "get-help Out-Null -detailed".
     For technical information, type: "get-help Out-Null -full".

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

How does one use glide to download an image into a bitmap?

If you want to assign dynamic bitmap image to bitmap variables

Example for kotlin

backgroundImage = Glide.with(applicationContext).asBitmap().load(PresignedUrl().getUrl(items!![position].img)).into(100, 100).get();

The above answers did not work for me

.asBitmap should be before the .load("http://....")

MySQL Database won't start in XAMPP Manager-osx

Minimal Guide

1. sudo killall mysqld

2. manager-osx > start mysql


If that didn't work...

sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

Google the error...


Examples:

Error:

ERROR! The server quit without updating PID file (/Applications/XAMPP/xamppfiles/var/mysql/<computername>.local.pid)

My Solution:

In /Applications/XAMPP/xamppfiles/etc/my.cnf change user = <uid> s that <uid> is uid from id command.

$ id
uid=...

$ vim /Applications/XAMPP/xamppfiles/etc/my.cnf
...

What version of JBoss I am running?

If you know the location of installed jboss folder then simply open it and look for version.txt file.

jQuery - Trigger event when an element is removed from the DOM

referencing to @David answer:

When You want to do soo with another function, eg. html() like in my case, don't forget to add return in new function:

(function() {
    var ev = new $.Event('html'),
        orig = $.fn.html;
    $.fn.html = function() {
        $(this).trigger(ev);
        return orig.apply(this, arguments);
    }
})();

How can I access getSupportFragmentManager() in a fragment?

in java you can replace with

getChildFragmentManager()

in kotlin, make it simple by

childFragmentManager

hope it help :)

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

If anyone is getting this error using Nginx, try adding the following to your server config:

server {
    listen 443 ssl;
    ...
}

The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl in the listen directive, you clear this up on the server side.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Markdown: continue numbered list

If you use tab to indent the code block it will shape the entire block into one line. To avoid this you need to use html ordered list.

  1. item 1
  2. item 2

Code block

<ol start="3">
  <li>item 3</li>
  <li>item 4</li>
</ol>

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Regarding Bruce Adams answer:

Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.

For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.

A makefile segment to explain it:

install:
    cp program $DESTDIR$PREFIX/bin/program

Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:

prog.pseudo.in:
    open("@prefix@/share/prog.db")
    ...

prog:
    sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
    compile prog.pseudo

install:
    cp prog $DESTDIR$PREFIX/bin/prog
    cp prog.db $DESTDIR$PREFIX/share/prog.db

If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.

Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).

Differences in boolean operators: & vs && and | vs ||

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand.

When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

If the first operand returns a value of true then the second operand is evaluated. If the second operand returns a value of true then && operator is then applied to the first and second operands.

Similar for | and ||.

How to use a dot "." to access members of dictionary?

The answer of @derek73 is very neat, but it cannot be pickled nor (deep)copied, and it returns None for missing keys. The code below fixes this.

Edit: I did not see the answer above that addresses the exact same point (upvoted). I'm leaving the answer here for reference.

class dotdict(dict):
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

In Java, what is the best way to determine the size of an object?

You can use the java.lang.instrument package

Compile and put this class in a JAR:

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

Add the following to your MANIFEST.MF:

Premain-Class: ObjectSizeFetcher

Use getObjectSize:

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}

Invoke with:

java -javaagent:ObjectSizeFetcherAgent.jar C

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

Change the Value of h1 Element within a Form with JavaScript

You may try the following:

document.getElementById("your_h1_id").innerHTML = "your new text here"

Powershell script to locate specific file/file name?

I'm using this function based on @Murph answer. It searches inside the current directory and lists the full path:

function findit
{
$filename = $args[0];
gci -recurse -filter "*${filename}*" -file -ErrorAction SilentlyContinue | foreach-object {
    $place_path = $_.directory
    echo "${place_path}\${_}"
    }
}

Example usage: findit myfile

Fastest way to check a string contain another substring in JavaScript?

Does this work for you?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

How to refresh an access form

I recommend that you use REQUERY the specific combo box whose data you have changed AND that you do it after the Cmd.Close statement. that way, if you were inputing data, that data is also requeried.

DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery

you might also want to point to the recently changed value

Dim id As Integer
id = Me.[Index_Field]
DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery
Forms![Form_Name]![Combo_Box_Name] = id

this example supposes that you opened a form to input data into a secondary table.

let us say you save School_Index and School_Name in a School table and refer to it in a Student table (which contains only the School_Index field). while you are editing a student, you need to associate him with a school that is not in your School table, etc etc

Java Constructor Inheritance

Because constructors are an implementation detail - they're not something that a user of an interface/superclass can actually invoke at all. By the time they get an instance, it's already been constructed; and vice-versa, at the time you construct an object there's by definition no variable it's currently assigned to.

Think about what it would mean to force all subclasses to have an inherited constructor. I argue it's clearer to pass the variables in directly than for the class to "magically" have a constructor with a certain number of arguments just because it's parent does.

Getting the last n elements of a vector. Is there a better way than using the length() function?

Here is a function to do it and seems reasonably fast.

endv<-function(vec,val) 
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}

USAGE:

test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)

BENCHMARK:

                                                    test replications elapsed relative
1                                 expression(tail(x, 5))       100000    5.24    6.469
2 expression(x[seq.int(to = length(x), length.out = 5)])       100000    0.98    1.210
3                       expression(x[length(x) - (4:0)])       100000    0.81    1.000
4                                 expression(endv(x, 5))       100000    1.37    1.691

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

Bootstrap 4 card-deck with number of columns based on viewport

Here's a solution with Sass to configure the number of cards per line depending on breakpoints: https://codepen.io/migli/pen/OQVRMw

It works fine with Bootstrap 4 beta 3

// Bootstrap 4 breakpoints & gutter
$grid-breakpoints: (
    xs: 0,
    sm: 576px,
    md: 768px,
    lg: 992px,
    xl: 1200px
) !default;

$grid-gutter-width: 30px !default;

// number of cards per line for each breakpoint
$cards-per-line: (
    xs: 1,
    sm: 2,
    md: 3,
    lg: 4,
    xl: 5
);

@each $name, $breakpoint in $grid-breakpoints {
    @media (min-width: $breakpoint) {
        .card-deck .card {
            flex: 0 0 calc(#{100/map-get($cards-per-line, $name)}% - #{$grid-gutter-width});
        }
    }
}

EDIT (2019/10)

I worked on another solution which uses horizontal lists group + flex utilities instead of card-deck:

https://codepen.io/migli/pen/gOOmYLb

It's an easy solution to organize any kind of elements into responsive grid

<div class="container">
    <ul class="list-group list-group-horizontal align-items-stretch flex-wrap">
        <li class="list-group-item">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <li class="list-group-item">Morbi leo risus</li>
        <li class="list-group-item">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <!--= add as many items as you need  =-->
    </ul>
</div>
.list-group-item {
    width: 95%;
    margin: 1% !important;
}

@media (min-width: 576px) {
    .list-group-item {
        width: 47%;
        margin: 5px 1.5% !important;
    }
}

@media (min-width: 768px) {
    .list-group-item {
        width: 31.333%;
        margin: 5px 1% !important;
    }
}

@media (min-width: 992px) {
    .list-group-item {
        width: 23%;
        margin: 5px 1% !important;
    }
}

@media (min-width: 1200px) {
    .list-group-item {
        width: 19%;
        margin: 5px .5% !important;
    }
}

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Django set field value after a form is initialized

Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:

form = FormType(request.POST)
if request.method == "POST":
    formcopy = form(request.POST.copy())
    formcopy.data['Email'] = GetEmailString()

Is it possible to change the package name of an Android app on Google Play?

Nope, you cannot just change it, you would have to upload a new package as a new app. Have a look at the Google's app Talk, its name was changed to Hangouts, but the package name is still com.google.android.talk. Because it is not doable :) Cheers.

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

delete all from table

You can also use truncate.

truncate table table_name;

Boxplot in R showing the mean

abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or

points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.

Note that these are called after you have drawn the boxplot.

If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:

boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

Can a background image be larger than the div itself?

This could help. It requires the footer height to be a fixed number. Basically, you have a div inside the footer div with it's normal content, with position: absolute, and then the image with position: relative, a negative z-index so it stays "below" everything, and a negative top value of the footer's height minus the image height (in my example, 50px - 600px = -550px). Tested in Chrome 8, FireFox 3.6 and IE 9.

Regular expression for matching HH:MM time format

Regular Expressions for Time

  • HH:MM 12-hour format, optional leading 0

      /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
    
  • HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)

      /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
    
  • HH:MM 24-hour with leading 0

     /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    
  • HH:MM 24-hour format, optional leading 0

     /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    
  • HH:MM:SS 24-hour format with leading 0

     /(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)/
    

Reference and Demo

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

Struct with template variables in C++

The problem is you can't template a typedef, also there is no need to typedef structs in C++.

The following will do what you need

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences

Getting activity from context in android

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

If you already have node installed, your path variable is set up and you suddenly start getting this error; try updating to the latest version.

This worked for me going from 6.9.2 to 6.10.

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

GitLab git user password

In my case, I was using a pair of keys that didn't have the default names id_rsa and id_rsa.pub.

Producing keys with these names solved the problem, and I actually found it looking at the output of ssh -vT my_gitlab_address. Strange fact: it worked on one computer with Ubuntu, but not on others with different distributions and older versions of OpenSSH.

I/O error(socket error): [Errno 111] Connection refused

I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).

Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ... block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.

How to set dropdown arrow in spinner?

As a follow-up to another answer, I was asked how I changed the spinner icon to get something like this:

One pretty easy way is to use a custom spinner item layout:

Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this,
        R.layout.view_spinner_item,
        ITEMS
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

In res/layout/view_spinner_item.xml, define a TextView with android:drawableRight pointing to the desired icon (along with any customisations to text size, paddings and so on, if you wish):

<?xml version="1.0" encoding="utf-8"?>
<!-- Custom spinner item layout -->
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:textSize="@dimen/text_size_medium"
    android:drawablePadding="@dimen/spacing_medium"
    android:drawableRight="@drawable/ic_arrow_down"
    />

(For the opened state, just use android.R.layout.simple_spinner_dropdown_item or similarly create a customised layout if you want to tweak every aspect of your spinner.)

To get the background & colours looking nice, set the Spinner's android:background and android:popupBackground as shown in that other question. And if you were wondering about the custom font in the screenshot above, you'll need a custom SpinnerAdapter.

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

Google Gson - deserialize list<class> object? (generic type)

In My case @uncaught_exceptions's answer didn't work, I had to use List.class instead of java.lang.reflect.Type:

String jsonDuplicatedItems = request.getSession().getAttribute("jsonDuplicatedItems").toString();
List<Map.Entry<Product, Integer>> entries = gson.fromJson(jsonDuplicatedItems, List.class);

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

Android Studio - Gradle sync project failed

I know this is an old thread but I ended up here with the same issue.

I solved it by comparing the dependencies classpath in the build.gradle script(Project) to the installed version.

The error message was pointing to the following folder

C:\Program Files\Android\android-studio3 preview\gradle\m2repository\com\android\tools\build\gradle

It turned out that the alpha2 version was installed but the classpath was still pointing to alpaha1. A simple change to the classpath ('com.android.tools.build:gradle:3.0.0-alpha2') was all that was needed.

This may not help everyone, but I do hope it help most people out.

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.

How to serialize an object into a string

You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.

ArrayList - How to modify a member of an object?

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

https with WCF error: "Could not find base address that matches scheme https"

Make sure SSL is enabled for your server!

I got this error when trying to use a HTTPS configuration file on my local box which doesn't have that certificate. I was trying to do local testing - by converting some of the bindings from HTTPS to HTTP. I thought it would be easier to do this than try to install a self signed certificate for local testing.

Turned out I was getting this error becasue I didn't have SSL enabled on my local IIS even though I wasn't intending on actually using it.

There was something in the configuration for HTTPS. Creating a self signed cert in IIS7 allowed HTTP to then work :-)

How to get twitter bootstrap modal to close (after initial launch)

I had problems closing the bootstrap modal dialog, if it was opened with:

$('#myModal').modal('show');

I solved this problem opening the dialog by the following link:

<a href="#myModal" data-toggle="modal">Open my dialog</a>

Do not forget the initialization:

$('#myModal').modal({show: false});

I also used the following attributes for the closing button:

data-dismiss="modal" data-target="#myModal"

How to mock location on device?

What Dr1Ku posted works. Used the code today but needed to add more locs. So here are some improvements:

Optional: Instead of using the LocationManager.GPS_PROVIDER String, you might want to define your own constat PROVIDER_NAME and use it. When registering for location updates, pick a provider via criteria instead of directly specifying it in as a string.

First: Instead of calling removeTestProvider, first check if there is a provider to be removed (to avoid IllegalArgumentException):

if (mLocationManager.getProvider(PROVIDER_NAME) != null) {
  mLocationManager.removeTestProvider(PROVIDER_NAME);
}

Second: To publish more than one location, you have to set the time for the location:

newLocation.setTime(System.currentTimeMillis());
...
mLocationManager.setTestProviderLocation(PROVIDER_NAME, newLocation);

There also seems to be a google Test that uses MockLocationProviders: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/location/LocationManagerProximityTest.java

Another good working example can be found at: http://pedroassuncao.com/blog/2009/11/12/android-location-provider-mock/

Another good article is: http://ballardhack.wordpress.com/2010/09/23/location-gps-and-automated-testing-on-android/#comment-1358 You'll also find some code that actually works for me on the emulator.

Best practices for circular shift (rotate) operations in C++

Source Code x bit number

int x =8;
data =15; //input
unsigned char tmp;
for(int i =0;i<x;i++)
{
printf("Data & 1    %d\n",data&1);
printf("Data Shifted value %d\n",data>>1^(data&1)<<(x-1));
tmp = data>>1|(data&1)<<(x-1);
data = tmp;  
}

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

if you want to install a PHP version < 5.3.0, you must replace

--enable-cgi

with:

--enable-fastcgi

in your ./configure statement, excerpt from the php.net doc:

--enable-fastcgi

If this is enabled, the CGI module will be built with support for FastCGI also. Available since PHP 4.3.0

As of PHP 5.3.0 this argument no longer exists and is enabled by --enable-cgi instead. After the compilation the ./php-cgi -v should look like this:

PHP 5.2.17 (cgi-fcgi) (built: Jul  9 2013 18:28:12)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies

NOTICE THE (cgi-fcgi)

Angular HttpClient "Http failure during parsing"

You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0 characters and DevTools will ignore then, so it's quite hard to spot in Chrome.

Based on this article

Vim multiline editing like in sublimetext?

Do yourself a favor by dropping the Windows compatibility layer.

The normal shortcut for entering Visual-Block mode is <C-v>.

Others have dealt with recording macros, here are a few other ideas:

Using only visual-block mode.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    
  3. Hit I"<Esc> to obtain:

    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  4. Put the cursor on the last char of the third word:

    asd "asd as|d| asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  5. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    
  6. Hit A"<Esc> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-block mode and Surround.vim.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom and the right:

    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    
  3. Hit S" to surround your selection with ":

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-line mode and :normal.

  1. Hit V to select the whole line and expand it toward the bottom:

    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    
  2. Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    
    • :norm[al] allows you to execute normal mode commands on a range of lines (the '<,'> part is added automatically by Vim and means "act on the selected area")

    • ^ puts the cursor on the first char of the line

    • w moves to the next word

    • i" inserts a " before the cursor

    • <C-v><Esc> is Vim's way to input a control character in this context, here it's <Esc> used to exit insert mode

    • ee moves to the end of the next word

    • a" appends a " after the cursor

    • <CR> executes the command

    Using Surround.vim, the command above becomes

    :'<,'>norm ^wvees"<CR>
    

How do I run a VBScript in 32-bit mode on a 64-bit machine?

Alternate method to run 32-bit scripts on 64-bit machine: %windir%\syswow64\cscript.exe vbscriptfile.vbs

Why is the jquery script not working?

<script type="text/javascript" >
    do your codes here  it will work..
    type="text/javascript" is important for jquery 
<script>

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

In asp.net core, If your api controller doesn't have annotation called [AllowAnonymous], add it to above your controller name like

[ApiController]
    [Route("api/")]
    [AllowAnonymous]
    public class TestController : ControllerBase

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

This question has MANY answers, and I think mine would suit another question better, but the answers to that question are locked. It points to this thread.

What solved it for me was appending &createDatabaseIfNotExist=true to the spring.datasource.url string in application.properties.

This was very tricky because it manifested itself in a couple of different, weird, seemingly unrelated errors, and when I tried to fix what it complained about it simply would pop another error up, or the error was impossible to fix. It complained about not being able to load JDBC, saying it wasn't in the classpath, but I added it to the classpath in some 30 different ways and was already facedesking.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Running a single test from unittest.TestCase via the command line

Inspired by yarkee, I combined it with some of the code I already got. You can also call this from another script, just by calling the function run_unit_tests() without requiring to use the command line, or just call it from the command line with python3 my_test_file.py.

import my_test_file
my_test_file.run_unit_tests()

Sadly this only works for Python 3.3 or above:

import unittest

class LineBalancingUnitTests(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.maxDiff = None

    def test_it_is_sunny(self):
        self.assertTrue("a" == "a")

    def test_it_is_hot(self):
        self.assertTrue("a" != "b")

Runner code:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .somewhere import LineBalancingUnitTests

def create_suite(classes, unit_tests_to_run):
    suite = unittest.TestSuite()
    unit_tests_to_run_count = len( unit_tests_to_run )

    for _class in classes:
        _object = _class()
        for function_name in dir( _object ):
            if function_name.lower().startswith( "test" ):
                if unit_tests_to_run_count > 0 \
                        and function_name not in unit_tests_to_run:
                    continue
                suite.addTest( _class( function_name ) )
    return suite

def run_unit_tests():
    runner = unittest.TextTestRunner()
    classes =  [
        LineBalancingUnitTests,
    ]

    # Comment all the tests names on this list, to run all Unit Tests
    unit_tests_to_run =  [
        "test_it_is_sunny",
        # "test_it_is_hot",
    ]
    runner.run( create_suite( classes, unit_tests_to_run ) )

if __name__ == "__main__":
    print( "\n\n" )
    run_unit_tests()

Editing the code a little, you can pass an array with all unit tests you would like to call:

...
def run_unit_tests(unit_tests_to_run):
    runner = unittest.TextTestRunner()

    classes = \
    [
        LineBalancingUnitTests,
    ]

    runner.run( suite( classes, unit_tests_to_run ) )
...

And another file:

import my_test_file

# Comment all the tests names on this list, to run all unit tests
unit_tests_to_run = \
[
    "test_it_is_sunny",
    # "test_it_is_hot",
]

my_test_file.run_unit_tests( unit_tests_to_run )

Alternatively, you can use load_tests Protocol and define the following method in your test module/file:

def load_tests(loader, standard_tests, pattern):
    suite = unittest.TestSuite()

    # To add a single test from this file
    suite.addTest( LineBalancingUnitTests( 'test_it_is_sunny' ) )

    # To add a single test class from this file
    suite.addTests( unittest.TestLoader().loadTestsFromTestCase( LineBalancingUnitTests ) )

    return suite

If you want to limit the execution to one single test file, you just need to set the test discovery pattern to the only file where you defined the load_tests() function.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest

test_pattern = 'mytest/module/name.py'
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )

loader = unittest.TestLoader()
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

suite = loader.discover( start_dir, test_pattern )
runner = unittest.TextTestRunner( verbosity=2 )
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )

sys.exit( not results.wasSuccessful() )

References:

  1. Problem with sys.argv[1] when unittest module is in a script
  2. Is there a way to loop through and execute all of the functions in a Python class?
  3. looping over all member variables of a class in python

Alternatively, to the last main program example, I came up with the following variation after reading the unittest.main() method implementation:

  1. https://github.com/python/cpython/blob/master/Lib/unittest/main.py#L65
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import unittest

PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

from testing_package import main_unit_tests_module
testNames = ["TestCaseClassName.test_nameHelloWorld"]

loader = unittest.TestLoader()
suite = loader.loadTestsFromNames( testNames, main_unit_tests_module )

runner = unittest.TextTestRunner(verbosity=2)
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )

Replacing instances of a character in a string

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

usernames = []

for i in names:
    if " " in i:
        i = i.replace(" ", "_")
    print(i)

Output: Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay

How to run a Runnable thread in Android at defined intervals?

now in Kotlin you can run threads this way:

class SimpleRunnable: Runnable {
    public override fun run() {
        println("${Thread.currentThread()} has run.")
    }
}
fun main(args: Array<String>) {
    val thread = SimpleThread()
    thread.start() // Will output: Thread[Thread-0,5,main] has run.
    val runnable = SimpleRunnable()
    val thread1 = Thread(runnable)
    thread1.start() // Will output: Thread[Thread-1,5,main] has run
}

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

From the documentation , the function mysqli_real_escape_string() has two parameters.

string mysqli_real_escape_string ( mysqli $link , string $escapestr ).

The first one is a link for a mysqli instance (database connection object), the second one is the string to escape. So your code should be like :

$username = mysqli_real_escape_string($yourconnectionobject,$_POST['username']);

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

Default interface methods are only supported starting with Android N

This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.

What is the behavior of integer division?

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I am using Entity Framework to repupulate my database, and the users gets overridden each time I generate my database.

Now I run this each time I load a new DBContext:

cnt.Database.ExecuteSqlCommand("EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\\NETWORK SERVICE'");

fatal error: mpi.h: No such file or directory #include <mpi.h>

On my system, I was just missing the Linux package.

sudo apt install libopenmpi-dev
pip install mpi4py

(example of something that uses it that is a good instant test to see if it succeeded)

Succeded.

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Send mail via Gmail with PowerShell V2's Send-MailMessage

On a Windows 8.1 machine I got Send-MailMessage to send an email with an attachment through Gmail using the following script:

$EmFrom = "[email protected]"
$username = "[email protected]"
$pwd = "YOURPASSWORD"
$EmTo = "[email protected]"
$Server = "smtp.gmail.com"
$port = 587
$Subj = "Test"
$Bod = "Test 123"
$Att = "c:\Filename.FileType"
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl  -Credential $cred

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Send POST request with JSON data using Volley

You can also send data by overriding getBody() method of JsonObjectRequest class. As shown below.

    @Override
    public byte[] getBody()
    {

        JSONObject jsonObject = new JSONObject();
        String body = null;
        try
        {
            jsonObject.put("username", "user123");
            jsonObject.put("password", "Pass123");

            body = jsonObject.toString();
        } catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try
        {
            return body.toString().getBytes("utf-8");
        } catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

Excel tab sheet names vs. Visual Basic sheet names

I think I may have an alternative solution. It's a little ugly, but it seems to work.

Function GetAnyNameValue(NameofName) As String
    Dim nm, ws, rng As String
    nm = ActiveWorkbook.Names(NameofName).Value
    ws = CStr(Split(nm, "!")(0))
    ws = Replace(ws, "'", "")
    ws = Replace(ws, "=", "")
    rng = CStr(Split(nm, "!")(1))
    GetAnyNameValue = CStr(Worksheets(ws).Range(rng).Value)
End Function

Pandas groupby: How to get a union of strings

In [4]: df = read_csv(StringIO(data),sep='\s+')

In [5]: df
Out[5]: 
   A         B       C
0  1  0.749065    This
1  2  0.301084      is
2  3  0.463468       a
3  4  0.643961  random
4  1  0.866521  string
5  2  0.120737       !

In [6]: df.dtypes
Out[6]: 
A      int64
B    float64
C     object
dtype: object

When you apply your own function, there is not automatic exclusions of non-numeric columns. This is slower, though, than the application of .sum() to the groupby

In [8]: df.groupby('A').apply(lambda x: x.sum())
Out[8]: 
   A         B           C
A                         
1  2  1.615586  Thisstring
2  4  0.421821         is!
3  3  0.463468           a
4  4  0.643961      random

sum by default concatenates

In [9]: df.groupby('A')['C'].apply(lambda x: x.sum())
Out[9]: 
A
1    Thisstring
2           is!
3             a
4        random
dtype: object

You can do pretty much what you want

In [11]: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))
Out[11]: 
A
1    {This, string}
2           {is, !}
3               {a}
4          {random}
dtype: object

Doing this on a whole frame, one group at a time. Key is to return a Series

def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

In [14]: df.groupby('A').apply(f)
Out[14]: 
   A         B               C
A                             
1  2  1.615586  {This, string}
2  4  0.421821         {is, !}
3  3  0.463468             {a}
4  4  0.643961        {random}

How do you obtain a Drawable object from a resource id in android package?

best way is

 button.setBackgroundResource(android.R.drawable.ic_delete);

OR this for Drawable left and something like that for right etc.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

and

getResources().getDrawable() is now deprecated

Exception of type 'System.OutOfMemoryException' was thrown. Why?

You're obviously not disposing of things.

Consider the "using" command when temporarily using objects that implement IDisposable.

Find unused code

I have come across AXTools CODESMART..Try that once. Use code analyzer in reviews section.It will list dead local and global functions along with other issues.

brew install mysql on macOS

If mysql is already installed

Stop mysql completely.

  1. mysql.server stop <-- may need editing based on your version
  2. ps -ef | grep mysql <-- lists processes with mysql in their name
  3. kill [PID] <-- kill the processes by PID

Remove files. Instructions above are good. I'll add:

  1. sudo find /. -name "*mysql*"
  2. Using your judgement, rm -rf these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.

Install

Hopefully you have homebrew. If not, download it.

I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore

  1. sudo brew update
  2. sudo brew install cmake <-- dependency for mysql, useful
  3. sudo brew install openssl <-- dependency for mysql, useful
  4. sudo brew info mysql <-- skim through this... it gives you some idea of what's coming next
  5. sudo brew install mysql --with-embedded; say done <-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)

Afterwards

  1. sudo chown -R mysql /usr/local/var/mysql/ <-- mysql wouldn't work for me until I ran this command
  2. sudo mysql.server start <-- once again, the exact syntax may vary
  3. Create users in mysql (http://dev.mysql.com/doc/refman/5.7/en/create-user.html). Remember to add a password for the root user.

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Laravel Eloquent compare date from datetime field

You can use this

whereDate('date', '=', $date)

If you give whereDate then compare only date from datetime field.

jQuery event for images loaded

  function CheckImageLoadingState()
  {
     var counter = 0;
     var length = 0;

     jQuery('#siteContent img').each(function() 
     {
        if(jQuery(this).attr('src').match(/(gif|png|jpg|jpeg)$/))
          length++;
     });

     jQuery('#siteContent img').each(function() 
     {  
        if(jQuery(this).attr('src').match(/(gif|png|jpg|jpeg)$/))
        {
           jQuery(this).load(function() 
           {
           }).each(function() {
              if(this.complete) jQuery(this).load();
            });
        }
        jQuery(this).load(function()
        {
           counter++;
           if(counter === length) 
           {  
              //function to call when all the images have been loaded
              DisplaySiteContent();
           }
        });
     });
  }

Java Error: "Your security settings have blocked a local application from running"

I am using an older Data Structure and Algs book that comes with Java Applets for practice. So I needed to store and run some applets locally. I am currently running Windows 10 OS with Edge, Chrome, and IE 11.

Running applets seem to only be allowed in IE11, and as other have mentioned you have to add the applet to the exception list. My issue was since I am storing these locally, and opening them in IE, it opened with path starting with "C:\..." Adding the full path using, "file///..." like mentioned in one of the other answers didn't work for me.

The fix: So, I just added(without the quotes), "file:///" to the exception site list and finally got it working. This also allows me to run any applet stored locally, and I do not have to explicitly add an exception for each applet path.

I plan to remove the exception from the list once I am done using the programs, and only add it back as necessary.

How to Read from a Text File, Character by Character in C++

You could try something like:

char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
    cout << ch; // Or whatever
}

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

Add params to given URL in Python

python3, self explanatory I guess

from urllib.parse import urlparse, urlencode, parse_qsl

url = 'https://www.linkedin.com/jobs/search?keywords=engineer'

parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)

print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States

Get attribute name value of <input>

Use the attr method of jQuery like this:

alert($('input').attr('name'));

Note that you can also use attr to set the attribute values by specifying second argument:

$('input').attr('name', 'new_name')

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

Stop UIWebView from "bouncing" vertically?

Swift 3

webView.scrollView.bounces = false

Create a dropdown component

This is the code to create dropdown in Angular 7, 8, 9

.html file code

<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
  <option value="0">--All--</option>
  <option *ngFor="let item of items" value="{{item.Id.Value}}">
    {{item.Name}}
  </option>
</select>
</div>

.ts file code

SelectItem(filterVal: any)
{
    var id=filterVal;
    //code
}

items is an array which should be initialized in .ts file.

How do I see which version of Swift I'm using?

You will get this under the project setting

enter image description here

Android ImageView setImageResource in code

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

What's the difference between [ and [[ in Bash?

In bash, contrary to [, [[ prevents word splitting of variable values.

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

How to apply a patch generated with git format-patch?

If you're using a JetBrains IDE (like IntelliJ IDEA, Android Studio, PyCharm), you can drag the patch file and drop it inside the IDE, and a dialog will appear, showing the patch's content. All you have to do now is to click "Apply patch", and a commit will be created.

How to handle the click event in Listview in android?

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",   
 Toast.LENGTH_SHORT).show();
}

Resizing an Image without losing any quality

You can't resize an image without losing some quality, simply because you are reducing the number of pixels.

Don't reduce the size client side, because browsers don't do a good job of resizing images.

What you can do is programatically change the size before you render it, or as a user uploads it.

Here is an article that explains one way to do this in c#: http://www.codeproject.com/KB/GDI-plus/imageresize.aspx

What is a callback in java

A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".

In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

How can I manually generate a .pyc file from a .py file

It's been a while since I last used Python, but I believe you can use py_compile:

import py_compile
py_compile.compile("file.py")

What are projection and selection?

Exactly.

Projection means choosing which columns (or expressions) the query shall return.

Selection means which rows are to be returned.

if the query is

select a, b, c from foobar where x=3;

then "a, b, c" is the projection part, "where x=3" the selection part.

Rename a file using Java

For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.

Example:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.

EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.

How to measure elapsed time in Python?

Python 3 only:

Since time.clock() is deprecated as of Python 3.3, you will want to use time.perf_counter() for system-wide timing, or time.process_time() for process-wide timing, just the way you used to use time.clock():

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t

The new function process_time will not include time elapsed during sleep.

Using Google Text-To-Speech in Javascript

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

_x000D_
_x000D_
const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
_x000D_
_x000D_

SELECT inside a COUNT

You can move the count() inside your sub-select:

SELECT a AS current_a, COUNT(*) AS b,
   ( SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d,
   from t group by a order by b desc

'uint32_t' does not name a type

I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h> or <cstdint.h> to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h> which worked well for me!

How to get past the login page with Wget?

You can install this plugin in Firefox: https://addons.mozilla.org/en-US/firefox/addon/cliget/?src=cb-dl-toprated Start downloading what you want and click on the plugin. It gives you the whole command either for wget or curl to download the file on the serer. Very easy!

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;

Why does javascript replace only first instance when using replace?

You need to set the g flag to replace globally:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

Otherwise only the first occurrence will be replaced.

Set value for particular cell in pandas DataFrame with iloc

Another way is to get the row index and then use df.loc or df.at.

# get row index 'label' from row number 'irow'
label = df.index.values[irow] 
df.at[label, 'COL_NAME'] = x

How to add the text "ON" and "OFF" to toggle button

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 90px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ca2222;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(55px);_x000D_
  -ms-transform: translateX(55px);_x000D_
  transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  transform: translate(-50%,-50%);_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  font-size: 10px;_x000D_
  font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
_x000D_
_x000D_

How to get Latitude and Longitude of the mobile device in android?

Use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

How to set environment variables in Python?

It should be noted that if you try to set the environment variable to a bash evaluation it won't store what you expect. Example:

from os import environ

environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"

This won't evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home as a path you will get the literal expression $(/usr/libexec/java_home).

Make sure to evaluate it before setting the environment variable, like so:

from os import environ
from subprocess import Popen, PIPE

bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode

if return_code == 0:
    evaluated_env = std_out.decode().strip()
    environ["JAVA_HOME"] = evaluated_env
else:
    print(f"Error: Unable to find environment variable {bash_variable}")

Select and display only duplicate records in MySQL

SELECT id, payer_email FROM paypal_ipn_orders
WHERE payer_email IN (
    SELECT payer_email FROM papypal_ipn_orders GROUP BY payer_email HAVING COUNT(*) > 1)

Bootstrap 4, how to make a col have a height of 100%?

Although it is not a good solution but may solve your problem. You need to use position absolute in #yellow element!

_x000D_
_x000D_
#yellow {height: 100%; background: yellow; position: absolute; top: 0px; left: 0px;}_x000D_
.container-fluid {position: static !important;}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container-fluid">_x000D_
  <div class="row justify-content-center">_x000D_
_x000D_
    <div class="col-4" id="yellow">_x000D_
      XXXX_x000D_
    </div>_x000D_
_x000D_
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">_x000D_
      Form Goes Here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

How to check if a function exists on a SQL database

I tend to use the Information_Schema:

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'FUNCTION' ) 

for functions, and change Routine_Type for stored procedures

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'PROCEDURE' ) 

Get path of executable

I didn't read if my solution is already posted but on linux and osx you can read the 0 argument in your main function like this:

int main(int argument_count, char **argument_list) {
    std::string currentWorkingDirectoryPath(argument_list[currentWorkingDirectory]);
    std::size_t pos = currentWorkingDirectoryPath.rfind("/");      // position of "live" in str
    currentWorkingDirectoryPath = currentWorkingDirectoryPath.substr (0, pos);

In the first item of argument_list the name of the executable is integrated but removed by the code above.

How to get file path in iPhone app

You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.

Solution to "subquery returns more than 1 row" error

When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:

CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
    IN P_email VARCHAR(150),
    IN P_credentials VARCHAR(150)
)
BEGIN
    DECLARE V_user_id INT(11);
    SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
    SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
    vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
    FROM make
    LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
    LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
    WHERE vehicles_in.user_id = V_user_id;
END

In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.

It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).

Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt. Hope this helps.

What does android:layout_weight mean?

As the name suggests, Layout weight specifies what amount or percentage of space a particular field or widget should occupy the screen space.
If we specify weight in horizontal orientation, then we must specify layout_width = 0px.
Similarly, If we specify weight in vertical orientation, then we must specify layout_height = 0px.

How can I make a horizontal ListView in Android?

Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.

how to create inline style with :before and :after

The key is to use background-color: inherit; on the pseudo element.
See: http://jsfiddle.net/EdUmc/

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.

HTML:

<head>
  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
      <p>NW</p>
    </div>
    <div class="quarter" id="NE">
      <p>NE</p>
    </div>
    <div class="quarter" id="SE">
      <p>SE</p>
    </div>?
    <div class="quarter" id="SW">
      <p>SW</p>
    </div>
  </div>
</body>

</html>

CSS:

html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

http://jsfiddle.net/og0j2d3v/

GET and POST methods with the same Action name in the same Controller

You received the good answer to this question, but I want to add my two cents. You could use one method and process requests according to request type:

public ActionResult Index()
{
    if("GET"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for GET
    }
    else if("POST"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for POST
    }
    else
    {
        //exception
    }

    return View();
}

Tomcat in Intellij Idea Community Edition

VM :-Djava.endorsed.dirs="C:/Program Files/Apache Software Foundation/Tomcat 8.0/common/endorsed" 
    -Dcatalina.base="C:/Program Files/Apache Software Foundation/Tomcat 8.0"  
    -Dcatalina.home="C:/Program Files/Apache Software Foundation/Tomcat 8.0" 
    -Djava.io.tmpdir="C:/Program Files/Apache Software Foundation/Tomcat 8.0/temp" 
    -Xmx1024M

How to insert element into arrays at specific position?

Cleaner approach (based on fluidity of use and less code).

/**
 * Insert data at position given the target key.
 *
 * @param array $array
 * @param mixed $target_key
 * @param mixed $insert_key
 * @param mixed $insert_val
 * @param bool $insert_after
 * @param bool $append_on_fail
 * @param array $out
 * @return array
 */
function array_insert(
    array $array, 
    $target_key, 
    $insert_key, 
    $insert_val = null,
    $insert_after = true,
    $append_on_fail = false,
    $out = [])
{
    foreach ($array as $key => $value) {
        if ($insert_after) $out[$key] = $value;
        if ($key == $target_key) $out[$insert_key] = $insert_val;
        if (!$insert_after) $out[$key] = $value;
    }

    if (!isset($array[$target_key]) && $append_on_fail) {
        $out[$insert_key] = $insert_val;
    }

    return $out;
}

Usage:

$colors = [
    'blue' => 'Blue',
    'green' => 'Green',
    'orange' => 'Orange',
];

$colors = array_insert($colors, 'blue', 'pink', 'Pink');

die(var_dump($colors));

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

How to properly URL encode a string in PHP?

Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.

Use case description

Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto link that lets them do that.

PHP code

// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';

// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);

// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;

// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);

// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';

Note: the above assumes you are outputting to a text/html document. If your output media type is text/json then simply use $retval['url'] = $mailToUri; because output encoding is handled by json_encode().

Test case

  1. Run the code on a PHP test site (is there a canonical one I should mention here?)
  2. Click the link
  3. Send the email
  4. Get the email
  5. Click that link

You should see:

"args": {
  "token": "w%a&!e#\"^2(^@azW"
}, 

And of course this is the JSON representation of $token above.

Are vectors passed to functions by value or by reference in C++

A vector is functionally same as an array. But, to the language vector is a type, and int is also a type. To a function argument, an array of any type (including vector[]) is treated as pointer. A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.

So, you must use vector<int>& (preferably with const, if function isn't modifying it) to pass it as a reference.

Upload file to FTP using C#

The existing answers are valid, but why re-invent the wheel and bother with lower level WebRequest types while WebClient already implements FTP uploading neatly:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}

Get to UIViewController from UIView?

I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a PopoverController).

While this works fine in the iPad (the UIPopoverController presents itself, therefor needs no reference to a UIViewController), getting the same code to work means suddenly referencing your presentViewController from your UIViewController. Kinda inconsistent right?

Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.

Either way, here's a swift solution, which adds a new property to any UIView:

extension UIView {

    var viewController: UIViewController? {

        var responder: UIResponder? = self

        while responder != nil {

            if let responder = responder as? UIViewController {
                return responder
            }
            responder = responder?.nextResponder()
        }
        return nil
    }
}

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

How to use a decimal range() step value?

[x * 0.1 for x in range(0, 10)] 

in Python 2.7x gives you the result of:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

but if you use:

[ round(x * 0.1, 1) for x in range(0, 10)]

gives you the desired:

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

How to set DialogFragment's width and height?

This is the simplest solution

The best solution I have found is to override onCreateDialog() instead of onCreateView(). setContentView() will set the correct window dimensions before inflating. It removes the need to store/set a dimension, background color, style, etc in resource files and setting them manually.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new Dialog(getActivity());
    dialog.setContentView(R.layout.fragment_dialog);

    Button button = (Button) dialog.findViewById(R.id.dialog_button);
    // ...
    return dialog;
}

Load HTML file into WebView

The easiest way would probably be to put your web resources into the assets folder then call:

webView.loadUrl("file:///android_asset/filename.html");

For Complete Communication between Java and Webview See This

Update: The assets folder is usually the following folder: <project>/src/main/assets This can be changed in the asset folder configuration setting in your <app>.iml file as:

<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” /> See Article Where to place the assets folder in Android Studio

Can I concatenate multiple MySQL rows into one field?

I had a more complicated query, and found that I had to use GROUP_CONCAT in an outer query to get it to work:

Original Query:

SELECT DISTINCT userID 
FROM event GROUP BY userID 
HAVING count(distinct(cohort))=2);

Imploded:

SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ') 
FROM (SELECT DISTINCT userID FROM event 
GROUP BY userID HAVING count(distinct(cohort))=2) as sub;

Hope this might help someone.