Programs & Examples On #Mysqldump

A command-line interface for administrators or end users to export data from the server to files

How to use MySQL dump from a remote machine

If you haven't install mysql_client yet and using Docker container instead:

sudo docker exec MySQL_CONTAINER_NAME /usr/bin/mysqldump --host=192.168.1.1 -u username --password=password db_name > dump.sql

Enable binary mode while restoring a Database from an SQL dump

zcat /path/to/file.sql.gz | mysql -u 'root' -p your_database

Import MySQL database into a MS SQL Server

Use SQL Server Migration Assistant (SSMA)

In addition to MySQL it supports Oracle, Sybase and MS Access.

It appears to be quite smart and capable of handling even nontrivial transfers. It also got some command line interface (in addition to GUI) so theoretically it can be integrated into some batch load process.

This the current download link for MySQL version https://www.microsoft.com/en-us/download/details.aspx?id=54257

The current (June 2016) stable version 6.0.1 crashes with the current (5.3.6) MySQL ODBC driver while transferring data. Everything 64 bit. The 5.3 version with the 5.1.13 ODBC driver works fine.

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

How can I access the MySQL command line with XAMPP for Windows?

In terminal:

cd C:\xampp\mysql\bin

mysql -h 127.0.0.1 --port=3306 -u root --password

Hit ENTER if the password is an empty string. Now you are in. You can list all available databases, and select one using the fallowing:

SHOW DATABASES;
USE database_name_here;

SHOW TABLES
DESC table_name_here
SELECT * FROM table_name_here

Remember about the ";" at the end of each SQL statement.

Windows cmd terminal is not very nice and does not support Ctrl + C, Ctrl + V (copy, paste) shortcuts. If you plan to work a lot in terminal, consider installing an alternative terminal cmd line, I use cmder terminal - Download Page

how to mysqldump remote db from local machine

Bassed on this page here:

Compare two MySQL databases

I modified it so you can use ddbb in diferent hosts.


#!/bin/sh

echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2
}

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
  else
    echo "Ignored '$table'..."
  fi
done
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

Restore the mysql database from .frm files

create a new database with same name copy the .frm .ibd files into xampp/mysql/data/[databasename]/

you will need ibdata file as well which is found inside

xampp/mysql/data/ copy the previous ibdata1 file paste in the paste the file and replace it with the existing ibdata file

[caution: you may loose the contents of the database which are newly created in the new ibdata file]

Using a .php file to generate a MySQL dump

MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.

$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";

$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";

$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");

passthru("cat {$dir}{$filename}");

I hope it helps someone else!

Error importing SQL dump into MySQL: Unknown database / Can't create database

This is a known bug at MySQL.

bug 42996
bug 40477

As you can see this has been a known issue since 2008 and they have not fixed it yet!!!

WORK AROUND
You first need to create the database to import. It doesn't need any tables. Then you can import your database.

  1. first start your MySQL command line (apply username and password if you need to)
    C:\>mysql -u user -p

  2. Create your database and exit

    mysql> DROP DATABASE database;  
    mysql> CREATE DATABASE database;  
    mysql> Exit  
    
  3. Import your selected database from the dump file
    C:\>mysql -u user -p -h localhost -D database -o < dumpfile.sql

You can replace localhost with an IP or domain for any MySQL server you want to import to. The reason for the DROP command in the mysql prompt is to be sure we start with an empty and clean database.

#1071 - Specified key was too long; max key length is 1000 bytes

I was facing same issue, used below query to resolve it.

While creating DB you can use utf-8 encoding

eg. create database my_db character set utf8 collate utf8mb4;

EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4

mysqldump exports only one table

Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/

  • Exporting the Table

To export the table run the following command from the command line:

mysqldump -p --user=username dbname tableName > tableName.sql

This will export the tableName to the file tableName.sql.

  • Importing the Table

To import the table run the following command from the command line:

mysql -u username -p -D dbname < tableName.sql

The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.

Skip certain tables with mysqldump

To exclude some table data, but not the table structure. Here is how I do it:

Dump the database structure of all tables, without any data:

mysqldump -u user -p --no-data database > database_structure.sql

Then dump the database with data, except the excluded tables, and do not dump the structure:

mysqldump -u user -p --no-create-info \
    --ignore-table=database.table1 \
    --ignore-table=database.table2 database > database_data.sql

Then, to load it into a new database:

mysql -u user -p newdatabase < database_structure.sql
mysql -u user -p newdatabase < database_data.sql

How to take complete backup of mysql database using mysqldump command line utility

I am using MySQL 5.5.40. This version has the option --all-databases

mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql

This command will create a complete backup of all databases in MySQL server to file named to current date-time.

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

Automatic HTTPS connection/redirect with node.js/express

Ryan, thanks for pointing me in the right direction. I fleshed out your answer (2nd paragraph) a little bit with some code and it works. In this scenario these code snippets are put in my express app:

// set up plain http server
var http = express();

// set up a route to redirect http to https
http.get('*', function(req, res) {  
    res.redirect('https://' + req.headers.host + req.url);

    // Or, if you don't want to automatically detect the domain name from the request header, you can hard code it:
    // res.redirect('https://example.com' + req.url);
})

// have it listen on 8080
http.listen(8080);

The https express server listens ATM on 3000. I set up these iptables rules so that node doesn't have to run as root:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3000

All together, this works exactly as I wanted it to.

To prevent theft of cookies over HTTP, see this answer (from the comments) or use this code:

const session = require('cookie-session');
app.use(
  session({
    secret: "some secret",
    httpOnly: true,  // Don't let browser javascript access cookies.
    secure: true, // Only use cookies over https.
  })
);

Replace non-numeric with empty string

try this

public static string cleanPhone(string inVal)
        {
            char[] newPhon = new char[inVal.Length];
            int i = 0;
            foreach (char c in inVal)
                if (c.CompareTo('0') > 0 && c.CompareTo('9') < 0)
                    newPhon[i++] = c;
            return newPhon.ToString();
        }

What are Java command line options to set to allow JVM to be remotely debugged?

For java 1.5 or greater:

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.4:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.3:

java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

Here is output from a simple program:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled

Python Pandas replicate rows in dataframe

You can put df_try inside a list and then do what you have in mind:

>>> df.append([df_try]*5,ignore_index=True)

    Store  Dept       Date  Weekly_Sales IsHoliday
0       1     1 2010-02-05      24924.50     False
1       1     1 2010-02-12      46039.49      True
2       1     1 2010-02-19      41595.55     False
3       1     1 2010-02-26      19403.54     False
4       1     1 2010-03-05      21827.90     False
5       1     1 2010-03-12      21043.39     False
6       1     1 2010-03-19      22136.64     False
7       1     1 2010-03-26      26229.21     False
8       1     1 2010-04-02      57258.43     False
9       1     1 2010-02-12      46039.49      True
10      1     1 2010-02-12      46039.49      True
11      1     1 2010-02-12      46039.49      True
12      1     1 2010-02-12      46039.49      True
13      1     1 2010-02-12      46039.49      True

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Alternatively - make sure that Resharper is enabled. My visual studio didn't update my Resharper license information, so when opening the resharper menu (after trying to figure out why my shortcuts stopped working!), the was a menu item "Why is Resharper disabled?" Clicking on the menu item opens up a dialog, which then automatically resolved the license. The next question for Jetbrains is why do I have to open the dialog for the thing to automatically renew??

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

Just in case anyone else visits this post I thought I'd describe what I did.

  1. Right click on res folder > New image asset

  2. browser to the icon. Click next

  3. By default the icon goes to src/debug/res- keep this

  4. In the project hierarchy, browse to src/debug/res and copy the files from the drawable* directories to the same directories in src/main and src/main

  5. copy the src/debug/res/icon_name.png to the src/main and src/release directories

Finish an activity from another activity

I've just applied Nepster's solution and works like a charm. There is a minor modification to run it from a Fragment.

To your Fragment

// sending intent to onNewIntent() of MainActivity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("transparent_nav_changed", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

And to your OnNewIntent() of the Activity you would like to restart.

// recreate activity when transparent_nav was just changed
if (getIntent().getBooleanExtra("transparent_nav_changed", false)) {
    finish(); // finish and create a new Instance
    Intent restarter = new Intent(MainActivity.this, MainActivity.class);
    startActivity(restarter);
}

git ignore exception

!foo.dll in .gitignore, or (every time!) git add -f foo.dll

How to use .htaccess in WAMP Server?

RewriteEngine on
RewriteBase /basic_test/

RewriteRule ^index.php$ test.php

How to change text and background color?

`enter code here`#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
#include <conio.h> // Just for WaitKey() routine
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()

void WaitKey();

int main()
{

    int len = 0,x, y=240; // 240 = white background, black foreground 

    string text = "Hello World. I feel pretty today!";
    len = text.length();
    cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
    for ( x=0;x<len;x++)
    {
        SetConsoleTextAttribute(console, y); // set color for the next print
        cout << text[x];
        y++; // add 1 to y, for a new color
        if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
            y=240; // if y > 254, start colors back at white background, black chars
        Sleep(250); // Pause between letters 
    }

    SetConsoleTextAttribute(console, 15); // set color to black background, white chars
    WaitKey(); // Program over, wait for a keypress to close program
}


void WaitKey()
{
    cout  << endl << endl << endl << "\t\t\tPress any key";
    while (_kbhit()) _getch(); // Empty the input buffer
    _getch(); // Wait for a key
    while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
}

How do you send a Firebase Notification to all devices via CURL?

One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.

How to use SortedMap interface in Java?

A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

Quickly reading very large tables as dataframes

Often times I think it is just good practice to keep larger databases inside a database (e.g. Postgres). I don't use anything too much larger than (nrow * ncol) ncell = 10M, which is pretty small; but I often find I want R to create and hold memory intensive graphs only while I query from multiple databases. In the future of 32 GB laptops, some of these types of memory problems will disappear. But the allure of using a database to hold the data and then using R's memory for the resulting query results and graphs still may be useful. Some advantages are:

(1) The data stays loaded in your database. You simply reconnect in pgadmin to the databases you want when you turn your laptop back on.

(2) It is true R can do many more nifty statistical and graphing operations than SQL. But I think SQL is better designed to query large amounts of data than R.

# Looking at Voter/Registrant Age by Decade

library(RPostgreSQL);library(lattice)

con <- dbConnect(PostgreSQL(), user= "postgres", password="password",
                 port="2345", host="localhost", dbname="WC2014_08_01_2014")

Decade_BD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from Birthdate) from voterdb where extract(DECADE from Birthdate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

Decade_RD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from RegistrationDate) from voterdb where extract(DECADE from RegistrationDate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

with(Decade_BD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Birthdays later than 1980 by Precinct",side=1,line=0)

with(Decade_RD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Registration Dates later than 1980 by Precinct",side=1,line=0)

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

Can't subtract offset-naive and offset-aware datetimes

The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

On older Python versions, you could define the utc tzinfo object yourself (example from datetime docs):

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):
  def utcoffset(self, dt):
    return ZERO
  def tzname(self, dt):
    return "UTC"
  def dst(self, dt):
    return ZERO

utc = UTC()

then:

now = datetime.now(utc)

Where does linux store my syslog?

You have to tell the system what information to log and where to put the info. Logging is configured in the /etc/rsyslog.conf file, then restart rsyslog to load the new config. The default logging rules are usually in a /etc/rsyslog.d/50-default.conf file.

Why does DEBUG=False setting make my django Static Files Access fail?

Just open your project urls.py, then find this if statement.

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.

if True:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

In django 1.10 you can write so:

urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]

What is the most accurate way to retrieve a user's correct IP address in PHP?

Just a VB.NET version of the answer:

Private Function GetRequestIpAddress() As IPAddress
    Dim serverVariables = HttpContext.Current.Request.ServerVariables
    Dim headersKeysToCheck = {"HTTP_CLIENT_IP", _
                              "HTTP_X_FORWARDED_FOR", _
                              "HTTP_X_FORWARDED", _
                              "HTTP_X_CLUSTER_CLIENT_IP", _
                              "HTTP_FORWARDED_FOR", _
                              "HTTP_FORWARDED", _
                              "REMOTE_ADDR"}
    For Each thisHeaderKey In headersKeysToCheck
        Dim thisValue = serverVariables.Item(thisHeaderKey)
        If thisValue IsNot Nothing Then
            Dim validAddress As IPAddress = Nothing
            If IPAddress.TryParse(thisValue, validAddress) Then
                Return validAddress
            End If
        End If
    Next
    Return Nothing
End Function

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

How to detect installed version of MS-Office?

If you've installed 32-bit Office on a 64-bit machine, you may need to check for the presence of "SOFTWARE\Wow6432Node\Microsoft\Office\12.0\", substituting the 12.0 with the appropriate version. This is certainly the case for Office 2007 installed on 64-bit Windows 7.

Note that Office 2010 (== 14.0) is the first Office for which a 64-bit version exists.

Android Fragment onAttach() deprecated

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity activity = context instanceof Activity ? (Activity) context : null;
}

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

removeEventListener has the same signature as addEventListener. All of the arguments must be exactly the same for it to remove the listener.

var onEnded = () => {};
audioNode.addEventListener('ended', onEnded, false);

this.cleanup = () => {
  audioNode.removeEventListener('ended', onEnded, false);
}

And in componentWillUnmount call this.cleanup().

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

builder for HashMap

There is no such thing for HashMaps, but you can create an ImmutableMap with a builder:

final Map<String, Integer> m = ImmutableMap.<String, Integer>builder().
      put("a", 1).
      put("b", 2).
      build();

And if you need a mutable map, you can just feed that to the HashMap constructor.

final Map<String, Integer> m = Maps.newHashMap(
    ImmutableMap.<String, Integer>builder().
        put("a", 1).
        put("b", 2).
        build());

Convert from DateTime to INT

select DATEDIFF(dd, '12/30/1899', mydatefield)

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How to implement a Boolean search with multiple columns in pandas

You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&) and or (|) operators:

foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

If you use and or or, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all or np.any to specify the matching criteria.

There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html

but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.

Passing two command parameters using a WPF binding

This task can also be solved with a different approach. Instead of programming a converter and enlarging the code in the XAML, you can also aggregate the various parameters in the ViewModel. As a result, the ViewModel then has one more property that contains all parameters.

An example of my current application, which also let me deal with the topic. A generic RelayCommand is required: https://stackoverflow.com/a/22286816/7678085

The ViewModelBase is extended here by a command SaveAndClose. The generic type is a named tuple that represents the various parameters.

public ICommand SaveAndCloseCommand => saveAndCloseCommand ??= new RelayCommand<(IBaseModel Item, Window Window)>
    (execute =>
    {
        execute.Item.Save();
        execute.Window?.Close(); // if NULL it isn't closed.
    },
    canExecute =>
    {
        return canExecute.Item?.IsItemValide ?? false;
    });
private ICommand saveAndCloseCommand;

Then it contains a property according to the generic type:

public (IBaseModel Item, Window Window) SaveAndCloseParameter 
{ 
    get => saveAndCloseParameter ; 
    set 
    {
        SetProperty(ref saveAndCloseParameter, value);
    }
}
private (IBaseModel Item, Window Window) saveAndCloseParameter;

The XAML code of the view then looks like this: (Pay attention to the classic click event)

<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonApply_Click" 
    Content="Apply"
    Height="25" Width="100" />
<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonSave_Click" 
    Content="Save"
    Height="25" Width="100" />

and in the code behind of the view, then evaluating the click events, which then set the parameter property.

private void ButtonApply_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, null);
}

private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, this);
}

Personally, I think that using the click events is not a break with the MVVM pattern. The program flow control is still located in the area of ??the ViewModel.

fopen deprecated warning

I'am using VisualStdio 2008. In this case I often set Preprocessor Definitions

Menu \ Project \ [ProjectName] Properties... Alt+F7

If click this menu or press Alt + F7 in project window, you can see "Property Pages" window.

Then see menu on left of window.

Configuration Properties \ C/C++ \ Preprocessor

Then add _CRT_SECURE_NO_WARNINGS to \ Preprocessor Definitions.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Spring MVC: How to return image in @ResponseBody?

I prefere this one:

private ResourceLoader resourceLoader = new DefaultResourceLoader();

@ResponseBody
@RequestMapping(value = "/{id}",  produces = "image/bmp")
public Resource texture(@PathVariable("id") String id) {
    return resourceLoader.getResource("classpath:images/" + id + ".bmp");
}

Change the media type to what ever image format you have.

What is difference between functional and imperative programming languages?

Most modern languages are in varying degree both imperative and functional but to better understand functional programming, it will be best to take an example of pure functional language like Haskell in contrast of imperative code in not so functional language like java/C#. I believe it is always easy to explain by example, so below is one.

Functional programming: calculate factorial of n i.e n! i.e n x (n-1) x (n-2) x ...x 2 X 1

-- | Haskell comment goes like
-- | below 2 lines is code to calculate factorial and 3rd is it's execution  

factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 3

-- | for brevity let's call factorial as f; And x => y shows order execution left to right
-- | above executes as := f(3) as 3 x f(2) => f(2) as 2 x f(1) => f(1) as 1 x f(0) => f(0) as 1  
-- | 3 x (2 x (1 x (1)) = 6

Notice that Haskel allows function overloading to the level of argument value. Now below is example of imperative code in increasing degree of imperativeness:

//somewhat functional way
function factorial(n) {
  if(n < 1) {
     return 1;
  }
  return n * factorial(n-1);   
}
factorial(3);

//somewhat more imperative way
function imperativeFactor(n) {
  int f = 1;
  for(int i = 1; i <= n; i++) {
     f = f * i;
  }
  return f;
}

This read can be a good reference to understand that how imperative code focus more on how part, state of machine (i in for loop), order of execution, flow control.

The later example can be seen as java/C# lang code roughly and first part as limitation of the language itself in contrast of Haskell to overload the function by value (zero) and hence can be said it is not purist functional language, on the other hand you can say it support functional prog. to some extent.

Disclosure: none of the above code is tested/executed but hopefully should be good enough to convey the concept; also I would appreciate comments for any such correction :)

How to capture no file for fs.readFileSync()?

Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:

const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);

const readContentFile = async (filePath) => {
  // Eureka, you are using good code practices here!
  const content = await readFileAsync(path.join(__dirname, filePath), {
    encoding: 'utf8'
  })
  return content;
}

Later can use this async function with try/catch from any other function:

const anyOtherFun = async () => {
  try {
    const fileContent = await readContentFile('my-file.txt');
  } catch (err) {
    // Here you get the error when the file was not found,
    // but you also get any other error
  }
}

Happy Coding!

JavaScript variable assignments from tuples

Here is a version of Matthew James Davis's answer with the Python tuple methods added in:

_x000D_
_x000D_
class Tuple extends Array { 
  constructor(...items) { 
    super(...items); 
    Object.freeze(this);
  }
  toArray() {
    return [...this];
  }
  toString() {
    return '('+super.toString()+')';
  }
  count(item) {
    var arr = this.toArray();
    var result = 0;
    for(var i = 0; i < arr.length; i++) {
       if(arr[i] === item) {
         result++;
       }
    }
    return result;
  }

  

  
}

   let tuple = new Tuple("Jim", 35);
   let [name,age] = tuple;

console.log("tuple:"+tuple)
console.log("name:"+name)
console.log("age:"+age)
_x000D_
_x000D_
_x000D_

findViewByID returns null

Possibly, you are calling findViewById before calling setContentView? If that's the case, try calling findViewById AFTER calling setContentView

PHP Error: Function name must be a string

Using parenthesis in a programming language or a scripting language usually means that it is a function.

However $_COOKIE in php is not a function, it is an Array. To access data in arrays you use square braces ('[' and ']') which symbolize which index to get the data from. So by doing $_COOKIE['test'] you are basically saying: "Give me the data from the index 'test'.

Now, in your case, you have two possibilities: (1) either you want to see if it is false--by looking inside the cookie or (2) see if it is not even there.

For this, you use the isset function which basically checks if the variable is set or not.

Example

if ( isset($_COOKIE['test'] ) )

And if you want to check if the value is false and it is set you can do the following:

if ( isset($_COOKIE['test']) && $_COOKIE['test'] == "false" )

One thing that you can keep in mind is that if the first test fails, it wont even bother checking the next statement if it is AND ( && ).

And to explain why you actually get the error "Function must be a string", look at this page. It's about basic creation of functions in PHP, what you must remember is that a function in PHP can only contain certain types of characters, where $ is not one of these. Since in PHP $ represents a variable.

A function could look like this: _myFunction _myFunction123 myFunction and in many other patterns as well, but mixing it with characters like $ and % will not work.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How could I use requests in asyncio?

To use requests (or any other blocking libraries) with asyncio, you can use BaseEventLoop.run_in_executor to run a function in another thread and yield from it to get the result. For example:

import asyncio
import requests

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = yield from future1
    response2 = yield from future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

This will get both responses in parallel.

With python 3.5 you can use the new await/async syntax:

import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

See PEP0492 for more.

Removing body margin in CSS

You can use body or * to make margin and padding 0px;

*{
margin: 0px;
padding:0px;
}

Clear Application's Data Programmatically

What I use everywhere :

 Runtime.getRuntime().exec("pm clear me.myapp");

Executing above piece of code closes application and removes all databases and shared preferences

How to Parse JSON Array with Gson

To conver in Object Array

Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);

To convert as post type

Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);

To read it as List of objects TypeToken can be used

List<Post> posts=(List<Post>)gson.fromJson(jsonString, 
                     new TypeToken<List<Post>>(){}.getType());

Adding three months to a date in PHP

The following should work,Please Try this:

$effectiveDate = strtotime("+1 months", strtotime(date("y-m-d")));
echo $time = date("y/m/d", $effectiveDate);

String is immutable. What exactly is the meaning?

Before proceeding further with the fuss of immutability, let's just take a look into the String class and its functionality a little before coming to any conclusion.

This is how String works:

String str = "knowledge";

This, as usual, creates a string containing "knowledge" and assigns it a reference str. Simple enough? Lets perform some more functions:

 String s = str;     // assigns a new reference to the same string "knowledge"

Lets see how the below statement works:

  str = str.concat(" base");

This appends a string " base" to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.

When the above statement is executed, the VM takes the value of String str, i.e. "knowledge" and appends " base", giving us the value "knowledge base". Now, since Strings are immutable, the VM can't assign this value to str, so it creates a new String object, gives it a value "knowledge base", and gives it a reference str.

An important point to note here is that, while the String object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String object.

At this point in the example above, we have two String objects: the first one we created with value "knowledge", pointed to by s, and the second one "knowledge base", pointed to by str. But, technically, we have three String objects, the third one being the literal "base" in the concat statement.

Important Facts about String and Memory usage

What if we didn't have another reference s to "knowledge"? We would have lost that String. However, it still would have existed, but would be considered lost due to having no references. Look at one more example below

String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1);  // Yes, s1 still refers to "java"

What's happening:

  1. The first line is pretty straightforward: create a new String "java" and refer s1 to it.
  2. Next, the VM creates another new String "java rules", but nothing refers to it. So, the second String is instantly lost. We can't reach it.

The reference variable s1 still refers to the original String "java".

Almost every method, applied to a String object in order to modify it, creates new String object. So, where do these String objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.

As applications grow, it's very common for String literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".

When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:

In the String constant pool, a String object is likely to have one or many references. If several references point to same String without even knowing it, it would be bad if one of the references modified that String value. That's why String objects are immutable.

Well, now you could say, what if someone overrides the functionality of String class? That's the reason that the String class is marked final so that nobody can override the behavior of its methods.

Best way to convert text files between character sets?

As described on How do I correct the character encoding of a file? Synalyze It! lets you easily convert on OS X between all encodings supported by the ICU library.

Additionally you can display some bytes of a file translated to Unicode from all the encodings to see quickly which is the right one for your file.

Get a particular cell value from HTML table using JavaScript

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

How to list all properties of a PowerShell object

If you want to know what properties (and methods) there are:

Get-WmiObject -Class "Win32_computersystem" | Get-Member

How to sort an array of associative arrays by value of a given key in PHP?

$arr1 = array(

    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$result1 = array_msort($arr1, array('name'=>SORT_DESC);

$result2 = array_msort($arr1, array('cat'=>SORT_ASC);

$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));


function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
    $colarr[$col] = array();
    foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}

$eval = 'array_multisort(';

foreach ($cols as $col => $order) {
    $eval .= '$colarr[\''.$col.'\'],'.$order.',';
}

$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
    foreach ($arr as $k => $v) {
        $k = substr($k,1);
        if (!isset($ret[$k])) $ret[$k] = $array[$k];
        $ret[$k][$col] = $array[$k][$col];
    }
}
return $ret;


} 

What does flex: 1 mean?

flex: 1 means the following:

flex-grow : 1;    ? The div will grow in same proportion as the window-size       
flex-shrink : 1;  ? The div will shrink in same proportion as the window-size 
flex-basis : 0;   ? The div does not have a starting value as such and will 
                     take up screen as per the screen size available for
                     e.g:- if 3 divs are in the wrapper then each div will take 33%.

Inline SVG in CSS

For people who are still struggling, I managed to get this working on all modern browsers IE11 and up.

base64 was no option for me because I wanted to use SASS to generate SVG icons based on any given color. For example: @include svg_icon(heart, #FF0000); This way I can create a certain icon in any color, and only have to embed the SVG shape once in the CSS. (with base64 you'd have to embed the SVG in every single color you want to use)

There are three things you need be aware of:

  1. URL ENCODE YOUR SVG As others have suggested, you need to URL encode your entire SVG string for it to work in IE11. In my case, I left out the color values in fields such as fill="#00FF00" and stroke="#FF0000" and replaced them with a SASS variable fill="#{$color-rgb}" so these can be replaced with the color I want. You can use any online converter to URL encode the rest of the string. You'll end up with an SVG string like this:

    %3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%2041.012%2010.535%2079.541%2028.973%20113.104L3.825%20464.586c345%2012.797%2041.813%2012.797%2015.467%200%2029.872-4.721%2041.813-12.797v158.184z%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E


  1. OMIT THE UTF8 CHARSET IN THE DATA URL When creating your data URL, you need to leave out the charset for it to work in IE11.

    NOT background-image: url( data:image/svg+xml;utf-8,%3Csvg%2....)
    BUT background-image: url( data:image/svg+xml,%3Csvg%2....)


  1. USE RGB() INSTEAD OF HEX colors Firefox does not like # in the SVG code. So you need to replace your color hex values with RGB ones.

    NOT fill="#FF0000"
    BUT fill="rgb(255,0,0)"

In my case I use SASS to convert a given hex to a valid rgb value. As pointed out in the comments, it's best to URL encode your RGB string as well (so comma becomes %2C)

@mixin svg_icon($id, $color) {
   $color-rgb: "rgb(" + red($color) + "%2C" + green($color) + "%2C" + blue($color) + ")";
   @if $id == heart {
      background-image: url('data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%204%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E');
   }
}

I realize this might not be the best solution for very complex SVG's (inline SVG never is in that case), but for flat icons with only a couple of colors this really works great.

I was able to leave out an entire sprite bitmap and replace it with inline SVG in my CSS, which turned out to only be around 25kb after compression. So it's a great way to limit the amount of requests your site has to do, without bloating your CSS file.

How to find path of active app.config file?

One more option that I saw is missing here:

const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);

VB.NET Connection string (Web.Config, App.Config)

Public Function connectDB() As OleDbConnection

        Dim Con As New OleDbConnection
        'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
        Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
        Try
            Con.Open()
        Catch ex As Exception
            showMessage(ex)
        End Try
        Return Con
    End Function

How To Auto-Format / Indent XML/HTML in Notepad++

I'm using Notepad 7.6 with "Plugin Admin" and I could not find XML Tools.
I had to install it manually like @some-java-guy did in his answer except that my plugins folder was located here: C:\Users\<my username>\AppData\Local\Notepad++\plugins
In that directory I created a new directory (named XmlTools) and copied XMLTools.dll there. (And I copied all dependencies to the Notepad++ directory in Program files.)

How do I raise the same Exception with a custom message in Python?

Python 3 built-in exceptions have the strerror field:

except ValueError as err:
  err.strerror = "New error message"
  raise err

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

Here are the commands to restore the old behavior:

# create a script that calls launchctl iterating through /etc/launchd.conf
echo '#!/bin/sh

while read line || [[ -n $line ]] ; do launchctl $line ; done < /etc/launchd.conf;
' > /usr/local/bin/launchd.conf.sh

# make it executable
chmod +x /usr/local/bin/launchd.conf.sh

# launch the script at startup
echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>launchd.conf</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>/usr/local/bin/launchd.conf.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>
' > /Library/LaunchAgents/launchd.conf.plist

Now you can specify commands like setenv JAVA_HOME /Library/Java/Home in /etc/launchd.conf.

Checked on El Capitan.

Add space between <li> elements

Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:

_x000D_
_x000D_
li {_x000D_
  background: red;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
 margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background: silver;_x000D_
  padding: 1px;  _x000D_
  padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Npm Please try using this command again as root/administrator

For those doing this on a MAC. Simply put sudo in front of the command. It will ask you for your password and then run fine. Cheers

How to refresh activity after changing language (Locale) inside application

You can use recreate(); to restart your activity when Language change.

I am using following code to restart activity when language change:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();

String lang = settings.getString("lang_list", "");

if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
      recreate();  //this is used for recreate activity
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

How can I read large text files in Python, line by line, without loading it into memory?

Here's what you do if you dont have newlines in the file:

with open('large_text.txt') as f:
  while True:
    c = f.read(1024)
    if not c:
      break
    print(c)

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

How can I get nth element from a list?

Look here, the operator used is !!.

I.e. [1,2,3]!!1 gives you 2, since lists are 0-indexed.

How to access Session variables and set them in javascript?

<?php
    session_start();
    $_SESSION['mydata']="some text";
?>

<script>
    var myfirstdata="<?php echo $_SESSION['mydata'];?>";
</script>

How can I read inputs as numbers?

I encountered a problem of taking integer input while solving a problem on CodeChef, where two integers - separated by space - should be read from one line.

While int(input()) is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

Now I use num1 and num2 as integers. Hope this helps.

Detailed 500 error message, ASP + IIS 7.5

I have come to the same problem and fixed the same way as Alex K.

So if "Send Errors To Browser" is not working set also this:

Error Pages -> 500 -> Edit Feature Settings -> "Detailed Errors"

enter image description here

Also note that if the content of the error page sent back is quite short and you're using IE, IE will happily ignore the useful content sent back by the server and show you its own generic error page instead. You can turn this off in IE's options, or use a different browser.

Print a file's last modified date in Bash

Best is

date -r filename +"%Y-%m-%d %H:%M:%S"

How do I disable "missing docstring" warnings at a file-level in Pylint?

Just put the following lines at the beginning of any file you want to disable these warnings for.

# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

SQL query question: SELECT ... NOT IN

Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)

But I would also suggest adding the DATEPART ( hour, insertDate) column for debug

SELECT idCustomer FROM reservations 
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2

How do I reference the input of an HTML <textarea> control in codebehind?

Missed property runat="server" or in code use Request.Params["TextArea1"]

How enable auto-format code for Intellij IDEA?

The formatting shortcuts in Intellij IDEA are :

  • For Windows : Ctrl + Alt + L
  • For Ubuntu : Ctrl + Alt + Windows + L
  • For Mac : ? (Option) + ? (Command) + L

how to fix java.lang.IndexOutOfBoundsException

for ( int i=0 ; i<=list.size() ; i++){
....}

By executing this for loop , the loop will execute with a thrown exception as IndexOutOfBoundException cause, suppose list size is 10 , so when index i will get to 10 i.e when i=10 the exception will be thrown cause index=size, i.e. i=size and as known that Java considers index starting from 0,1,2...etc the expression which Java agrees upon is index < size. So the solution for such exception is to make the statement in loop as i<list.size()

for ( int i=0 ; i<list.size() ; i++){
...}

How to create an array of object literals in a loop?

This will work:

 var myColumnDefs = new Object();
 for (var i = 0; i < oFullResponse.results.length; i++) {
     myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
  }

Is Fortran easier to optimize than C for heavy calculations?

Using modern standards and compiler, no!

Some of the folks here have suggested that FORTRAN is faster because the compiler doesn't need to worry about aliasing (and hence can make more assumptions during optimisation). However, this has been dealt with in C since the C99 (I think) standard with the inclusion of the restrict keyword. Which basically tells the compiler, that within a give scope, the pointer is not aliased. Furthermore C enables proper pointer arithmetic, where things like aliasing can be very useful in terms of performance and resource allocation. Although I think more recent version of FORTRAN enable the use of "proper" pointers.

For modern implementations C general outperforms FORTRAN (although it is very fast too).

http://benchmarksgame.alioth.debian.org/u64q/fortran.html

EDIT:

A fair criticism of this seems to be that the benchmarking may be biased. Here is another source (relative to C) that puts result in more context:

http://julialang.org/benchmarks/

You can see that C typically outperforms Fortran in most instances (again see criticisms below that apply here too); as others have stated, benchmarking is an inexact science that can be easily loaded to favour one language over others. But it does put in context how Fortran and C have similar performance.

Make a div fill up the remaining width

Flex-boxes are the solution - and they're fantastic. I've been wanting something like this out of css for a decade. All you need is to add display: flex to your style for "Main" and flex-grow: 100 (where 100 is arbitrary - its not important that it be exactly 100). Try adding this style (colors added to make the effect visible):

<style>
    #Main {
        background-color: lightgray;
        display: flex;
    }

    #div1 {
        border: 1px solid green;   
        height: 50px; 
        display: inline-flex; 
    }
    #div2 {
        border: 1px solid blue;    
        height: 50px;
        display: inline-flex;
        flex-grow: 100;
    }
    #div3 {
        border: 1px solid orange;        
        height: 50px;
        display: inline-flex;
    }
</style>

More info about flex boxes here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Pandas: convert dtype 'object' to int

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

No newline at end of file

The only reason is that Unix historically had a convention of all human-readable text files ending in a newline. At the time, this avoided extra processing when displaying or joining text files, and avoided treating text files differently to files containing other kinds of data (eg raw binary data which isn't human-readable).

Because of this convention, many tools from that era expect the ending newline, including text editors, diffing tools, and other text processing tools. Mac OS X was built on BSD Unix, and Linux was developed to be Unix-compatible, so both operating systems have inherited the same convention, behaviour and tools.

Windows wasn't developed to be Unix-compatible, so it doesn't have the same convention, and most Windows software will deal just fine with no trailing newline.

But, since Git was developed for Linux first, and a lot of open-source software is built on Unix-compatible systems like Linux, Mac OS X, FreeBSD, etc, most open-source communities and their tools (including programming languages) continue to follow these conventions.

There are technical reasons which made sense in 1971, but in this era it's mostly convention and maintaining compatibility with existing tools.

Clear text input on click with AngularJS

Inspired from Robert's answer, but when we use,

ng-click="searchAll = null" in the filter, it makes the model values as null and in-turn the search doesn't work with its normal functionality, so it would be better enough to use ng-click="searchAll = ''" instead

How do I make Visual Studio pause after executing a console application in debug mode?

Prompt for user input.

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

shows how to do this for C++. For Node.js, this is taken right from the docs (and it works):

'use strict';

console.log('Hello world');

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Press enter to continue...', (answer) => {
    rl.close(); /* discard the answer */
});

change cursor from block or rectangle to line?

please Press fn +ins key together

CSS endless rotation animation

Works in all modern browsers

.rotate{
 animation: loading 3s linear infinite;
 @keyframes loading {
  0% { 
    transform: rotate(0); 
  }
  100% { 
    transform: rotate(360deg);
  }
 }
}

Insert/Update/Delete with function in SQL Server

You can't update tables from a function like you would a stored procedure, but you CAN update table variables.

So for example, you can't do this in your function:

create table MyTable
(
    ID int,
    column1 varchar(100)
)
update [MyTable]
set column1='My value'

but you can do:

declare @myTable table
(
    ID int,
    column1 varchar(100)
)

Update @myTable
set column1='My value'

How to prevent page scrolling when scrolling a DIV element?

just offering this up as a possible solution if you don't think the user will have a negative experience on the obvious change. I simply changed the body's class of overflow to hidden when the mouse was over the target div; then I changed the body's div to hidden overflow when the mouse leaves.

Personally I don't think it looks bad, my code could use toggle to make it cleaner, and there are obvious benefits for making this effect possible without the user being aware. So this is probably the hackish-last-resort answer.

//listen mouse on and mouse off for the button
pxMenu.addEventListener("mouseover", toggleA1);
pxOptContainer.addEventListener("mouseout", toggleA2);
//show / hide the pixel option menu
function toggleA1(){
  pxOptContainer.style.display = "flex";
  body.style.overflow = "hidden";
}
function toggleA2(){
  pxOptContainer.style.display = "none";
  body.style.overflow = "hidden scroll";
}

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

Loop timer in JavaScript

I believe you are looking for setInterval()

Integrating Dropzone.js into existing HTML form with other fields

In order to submit all files alongside with other form data in a single request you can copy Dropzone.js temporary hidden input nodes into your form. You can do this within addedfiles event handler:

var myDropzone = new Dropzone("myDivSelector", { url: "#", autoProcessQueue: false });
myDropzone.on("addedfiles", () => {
  // Input node with selected files. It will be removed from document shortly in order to
  // give user ability to choose another set of files.
  var usedInput = myDropzone.hiddenFileInput;
  // Append it to form after stack become empty, because if you append it earlier
  // it will be removed from its parent node by Dropzone.js.
  setTimeout(() => {
    // myForm - is form node that you want to submit.
    myForm.appendChild(usedInput);
    // Set some unique name in order to submit data.
    usedInput.name = "foo";
  }, 0);
});

Obviosly this is a workaround dependent on implementation details. Related source code.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

@denver_citizen and @Peter Szanto's answers didn't quite work for me, but I modified them to account for:

  1. Composite Keys
  2. On Delete and On Update actions
  3. Checking the index when re-adding
  4. Schemas other than dbo
  5. Multiple tables at once
DECLARE @Debug bit = 0;

-- List of tables to truncate
select
    SchemaName, Name
into #tables
from (values 
    ('schema', 'table')
    ,('schema2', 'table2')
) as X(SchemaName, Name)


BEGIN TRANSACTION TruncateTrans;

with foreignKeys AS (
     SELECT 
        SCHEMA_NAME(fk.schema_id) as SchemaName
        ,fk.Name as ConstraintName
        ,OBJECT_NAME(fk.parent_object_id) as TableName
        ,SCHEMA_NAME(t.SCHEMA_ID) as ReferencedSchemaName
        ,OBJECT_NAME(fk.referenced_object_id) as ReferencedTableName
        ,fc.constraint_column_id
        ,COL_NAME(fk.parent_object_id, fc.parent_column_id) AS ColumnName
        ,COL_NAME(fk.referenced_object_id, fc.referenced_column_id) as ReferencedColumnName
        ,fk.delete_referential_action_desc
        ,fk.update_referential_action_desc
    FROM sys.foreign_keys AS fk
        JOIN sys.foreign_key_columns AS fc
            ON fk.object_id = fc.constraint_object_id
        JOIN #tables tbl 
            ON OBJECT_NAME(fc.referenced_object_id) = tbl.Name
        JOIN sys.tables t on OBJECT_NAME(t.object_id) = tbl.Name 
            and SCHEMA_NAME(t.schema_id) = tbl.SchemaName
            and t.OBJECT_ID = fc.referenced_object_id
)



select
    quotename(fk.ConstraintName) AS ConstraintName
    ,quotename(fk.SchemaName) + '.' + quotename(fk.TableName) AS TableName
    ,quotename(fk.ReferencedSchemaName) + '.' + quotename(fk.ReferencedTableName) AS ReferencedTableName
    ,replace(fk.delete_referential_action_desc, '_', ' ') AS DeleteAction
    ,replace(fk.update_referential_action_desc, '_', ' ') AS UpdateAction
    ,STUFF((
        SELECT ',' + quotename(fk2.ColumnName)
        FROM foreignKeys fk2 
        WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
        ORDER BY fk2.constraint_column_id
        FOR XML PATH('')
    ),1,1,'') AS ColumnNames
    ,STUFF((
        SELECT ',' + quotename(fk2.ReferencedColumnName)
        FROM foreignKeys fk2 
        WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
        ORDER BY fk2.constraint_column_id
        FOR XML PATH('')
    ),1,1,'') AS ReferencedColumnNames
into #FKs
from foreignKeys fk
GROUP BY fk.SchemaName, fk.ConstraintName, fk.TableName, fk.ReferencedSchemaName, fk.ReferencedTableName, fk.delete_referential_action_desc, fk.update_referential_action_desc



-- Drop FKs
select 
    identity(int,1,1) as ID,
    'ALTER TABLE ' + fk.TableName + ' DROP CONSTRAINT ' + fk.ConstraintName AS script
into #scripts
from #FKs fk

-- Truncate 
insert into #scripts
select distinct 
    'TRUNCATE TABLE ' + quotename(tbl.SchemaName) + '.' + quotename(tbl.Name) AS script
from #tables tbl

-- Recreate
insert into #scripts
select 
    'ALTER TABLE ' + fk.TableName + 
    ' WITH CHECK ADD CONSTRAINT ' + fk.ConstraintName + 
    ' FOREIGN KEY ('+ fk.ColumnNames +')' + 
    ' REFERENCES ' + fk.ReferencedTableName +' ('+ fk.ReferencedColumnNames +')' +
    ' ON DELETE ' + fk.DeleteAction COLLATE Latin1_General_CI_AS_KS_WS + ' ON UPDATE ' + fk.UpdateAction COLLATE Latin1_General_CI_AS_KS_WS AS script
from #FKs fk


DECLARE @script nvarchar(MAX);

DECLARE curScripts CURSOR FOR 
    select script
    from #scripts
    order by ID

OPEN curScripts

WHILE 1=1 BEGIN
    FETCH NEXT FROM curScripts INTO @script
    IF @@FETCH_STATUS != 0 BREAK;

    print @script;
    IF @Debug = 0
        EXEC (@script);
END
CLOSE curScripts
DEALLOCATE curScripts


drop table #scripts
drop table #FKs
drop table #tables


COMMIT TRANSACTION TruncateTrans;

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

Property 'map' does not exist on type 'Observable<Response>'

just install rxjs-compat by typing in terminal:

npm install --save rxjs-compat

then import :

import 'rxjs/Rx';

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think that it's around 2GB. While the answer by Pete Kirkham is very interesting and probably holds truth, I have allocated upwards of 3GB without error, however it did not use 3GB in practice. That might explain why you were able to allocate 2.5 GB on 2GB RAM with no swap space. In practice, it wasn't using 2.5GB.

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Had the same issue on Windows7 64bit. The reason why it didn't was missing emulator-x86.exe file under sdk/tools. Fixed it by deleting Android SDK Tools using Android SDK Manager and installing it again. The file now exists and emulator works as expected.

Hunk #1 FAILED at 1. What's that mean?

In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.

This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.

BTW ignore-whitespace did not help.

How to remove application from app listings on Android Developer Console

enter image description here

From Google Play Console, Select your app. Select Store Presence and select Pricing and Distribution from the side menu. There is a toggle switch to Publish and Unpublish app. Select UnPublish and click Submit Update Button in the top right corner.

MVC ajax post to controller action method

Your Action is expecting string parameters, but you're sending a composite object.

You need to create an object that matches what you're sending.

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

In addition, toStringify() is probably not what you want here. Just send the object itself.

data: data,

MySQL: @variable vs. variable. What's the difference?

@variable is very useful if calling stored procedures from an application written in Java , Python etc. There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.

Side-note on PL/SQL (Oracle)

The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:

  • Function variable for which the scope ends when function exits.
  • Package body variables defined at the top of package and outside all functions whose scope is the session and visibility is package.
  • Package variable whose variable is session and visibility is global.

My Experience in PL/SQL

I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.

I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.

Opinion towards @ in MySQL

I am happy to see that at least this @ facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.

UIAlertView first deprecated IOS 9

Use UIAlertController instead of UIAlertView

-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert=   [UIAlertController
                              alertControllerWithTitle:title
                              message:message
                              preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

    //do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}

Programmatically get height of navigation bar

UIImage*image = [UIImage imageNamed:@"logo"];

float targetHeight = self.navigationController.navigationBar.frame.size.height;
float logoRatio = image.size.width / image.size.height;
float targetWidth = targetHeight * logoRatio;

UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
// X or Y position can not be manipulated because autolayout handles positions.
//[logoView setFrame:CGRectMake((self.navigationController.navigationBar.frame.size.width - targetWidth) / 2 , (self.navigationController.navigationBar.frame.size.height - targetHeight) / 2 , targetWidth, targetHeight)];
[logoView setFrame:CGRectMake(0, 0, targetWidth, targetHeight)];
self.navigationItem.titleView = logoView;

// How much you pull out the strings and struts, with autolayout, your image will fill the width on navigation bar. So setting only height and content mode is enough/
[logoView setContentMode:UIViewContentModeScaleAspectFit];

/* Autolayout constraints also can not be manipulated since navigation bar has  immutable constraints
self.navigationItem.titleView.translatesAutoresizingMaskIntoConstraints = false;

NSDictionary*metricsArray = @{@"width":[NSNumber numberWithFloat:targetWidth],@"height":[NSNumber numberWithFloat:targetHeight],@"margin":[NSNumber numberWithFloat:20]};
NSDictionary*viewsArray = @{@"titleView":self.navigationItem.titleView};

[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>margin=)-H:[titleView(width)]-(>margin=)-|" options:NSLayoutFormatAlignAllCenterX metrics:metricsArray views:viewsArray]];
[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[titleView(height)]" options:0 metrics:metricsArray views:viewsArray]];

NSLog(@"%f", self.navigationItem.titleView.width );
*/

So all we actually need is

UIImage*image = [UIImage imageNamed:@"logo"];
UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
float targetHeight = self.navigationController.navigationBar.frame.size.height;
[logoView setFrame:CGRectMake(0, 0, 0, targetHeight)];
[logoView setContentMode:UIViewContentModeScaleAspectFit];

self.navigationItem.titleView = logoView;

Convert DataTable to IEnumerable<T>

        PagedDataSource objPage = new PagedDataSource();

        DataView dataView = listData.DefaultView;
        objPage.AllowPaging = true;
        objPage.DataSource = dataView;
        objPage.PageSize = PageSize;

        TotalPages = objPage.PageCount;

        objPage.CurrentPageIndex = CurrentPage - 1;

        //Convert PagedDataSource to DataTable
        System.Collections.IEnumerator pagedData = objPage.GetEnumerator();

        DataTable filteredData = new DataTable();
        bool flagToCopyDTStruct = false;
        while (pagedData.MoveNext())
        {
            DataRowView rowView = (DataRowView)pagedData.Current;
            if (!flagToCopyDTStruct)
            {
                filteredData = rowView.Row.Table.Clone();
                flagToCopyDTStruct = true;
            }
            filteredData.LoadDataRow(rowView.Row.ItemArray, true);
        }

        //Here is your filtered DataTable
        return filterData; 

Clear the form field after successful submission of php form

I was facing this similiar problem and did not want to use header() to redirect to another page.

Solution:

Use $_POST = array(); to reset the $_POST array at the top of the form, along with the code used to process the form.

The error or success messages can be conditionally added after the form. Hope this helps :)

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

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

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

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

malloc for struct and pointer in C

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retVal == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

Currency format for display

If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.

public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
    NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
    localFormat.CurrencySymbol = currencySymbol;
    localFormat.CurrencyDecimalDigits = decPlaces;
    return currency.ToString("c", localFormat);
}

CSS vertical alignment of inline/inline-block elements

vertical-align applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:

div > * {
    vertical-align:middle;  // Align children to middle of line
}

See: http://jsfiddle.net/dfmx123/TFPx8/1186/

NOTE: vertical-align is relative to the current text line, not the full height of the parent div. If you wanted the parent div to be taller and still have the elements vertically centered, set the div's line-height property instead of its height. Follow jsfiddle link above for an example.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

In my case it was a breakpoint set in my own page source. If I removed or disabled the breakpoint then the error would clear up.

The breakpoint was in a moderately complex chunk of rendering code. Other breakpoints in different parts of the page had no such effect. I was not able to work out a simple test case that always trigger this error.

How do I handle the window close event in Tkinter?

Try The Simple Version:

import tkinter

window = Tk()

closebutton = Button(window, text='X', command=window.destroy)
closebutton.pack()

window.mainloop()

Or If You Want To Add More Commands:

import tkinter

window = Tk()


def close():
    window.destroy()
    #More Functions


closebutton = Button(window, text='X', command=close)
closebutton.pack()

window.mainloop()

Binding an enum to a WinForms combo box, and then setting it

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

comboBox1.SelectedIndex = (int)MyEnum.Something;

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something);

Both of these work for me are you sure there isn't something else wrong?

Babel command not found

This is what I've done to automatically add my local project node_modules/.bin path to PATH. In ~/.profile I added:

if [ -d "$PWD/node_modules/.bin" ]; then 
    PATH="$PWD/node_modules/.bin"
fi

Then reload your bash profile: source ~/.profile

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Can attributes be added dynamically in C#?

You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.

Row count with PDO

I tried $count = $stmt->rowCount(); with Oracle 11.2 and it did not work. I decided to used a for loop as show below.

   $count =  "";
    $stmt =  $conn->prepare($sql);
    $stmt->execute();
   echo "<table border='1'>\n";
   while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
        $count++;
        echo "<tr>\n";
    foreach ($row as $item) {
    echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):"&nbsp;")."</td>\n";
        } //foreach ends
        }// while ends
        echo "</table>\n";
       //echo " no of rows : ". oci_num_rows($stmt);
       //equivalent in pdo::prepare statement
       echo "no.of rows :".$count;

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

Most efficient way to check for DBNull and then assign to a variable?

You should use the method:

Convert.IsDBNull()

Considering it's built-in to the Framework, I would expect this to be the most efficient.

I'd suggest something along the lines of:

int? myValue = (Convert.IsDBNull(row["column"]) ? null : (int?) Convert.ToInt32(row["column"]));

And yes, the compiler should cache it for you.

Can I have multiple primary keys in a single table?

Some people use the term "primary key" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example AUTO_INCREMENT in MySQL or IDENTITY in Microsoft SQL Server. Are you using primary key in this sense?

If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:

mysql> create table foo (
  id int primary key auto_increment, 
  id2 int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; 
there can be only one auto column and it must be defined as a key

In some other brands of database, you are able to define more than one auto-generating column in a table.

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Determine the type of an object?

type() is a better solution than isinstance(), particularly for booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)

and

isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

Matplotlib scatterplot; colour as a function of a third variable

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

Mongoose.js: Find user by username LIKE value

The following query will find the documents with required string case insensitively and with global occurrence also

var name = 'Peter';
    db.User.find({name:{
                         $regex: new RegExp(name, "ig")
                     }
                },function(err, doc) {
                                     //Your code here...
              });

How do I remove a MySQL database?

From the MySQL prompt:

mysql> drop database <db_name>;

Removing all empty elements from a hash / YAML?

In Simple one liner for deleting null values in Hash,

rec_hash.each {|key,value| rec_hash.delete(key) if value.blank? } 

Can we have multiple "WITH AS" in single sql - Oracle SQL

Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,

with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
     t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)

I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.

The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.

Convert a Python int into a big-endian string of bytes

Single-source Python 2/3 compatible version based on @pts' answer:

#!/usr/bin/env python
import binascii

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

print(int2bytes(1245427))
# -> b'\x13\x00\xf3'

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

In NHibernate (with NHibernate.Linq) you could do it as follows:

return session.Query<T>()
              .Single(a => a.Filter == filter &&
                           a.Id == session.Query<T>()
                                          .Where(a2 => a2.Filter == filter)
                                          .Max(a2 => a2.Id));

Which will generate SQL like follows:

select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
              from TableName bar
              where bar.Name = 'Filter On String')

Which seems pretty efficient to me.

How to do 3 table JOIN in UPDATE query?

Yes, you can do a 3 table join for an update statement. Here is an example :

    UPDATE customer_table c 

      JOIN  
          employee_table e
          ON c.city_id = e.city_id  
      JOIN 
          anyother_ table a
          ON a.someID = e.someID

    SET c.active = "Yes"

    WHERE c.city = "New york";

C# error: Use of unassigned local variable

The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue to null when you declare it.

Queue queue = null;

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

MySQL - UPDATE multiple rows with different values in one query

update table_name
set cod_user = 
    CASE 
    WHEN user_rol = 'student' THEN '622057'
    WHEN user_rol = 'assistant' THEN '2913659'
    WHEN user_rol = 'admin' THEN '6160230'?
    END,date = '12082014'

WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';

Different font size of strings in the same TextView

I have written my own function which takes 2 strings and 1 int (text size)

The full text and the part of the text you want to change the size of it.

It returns a SpannableStringBuilder which you can use it in text view.

  public static SpannableStringBuilder setSectionOfTextSize(String text, String textToChangeSize, int size){

        SpannableStringBuilder builder=new SpannableStringBuilder();

        if(textToChangeSize.length() > 0 && !textToChangeSize.trim().equals("")){

            //for counting start/end indexes
            String testText = text.toLowerCase(Locale.US);
            String testTextToBold = textToChangeSize.toLowerCase(Locale.US);
            int startingIndex = testText.indexOf(testTextToBold);
            int endingIndex = startingIndex + testTextToBold.length();
            //for counting start/end indexes

            if(startingIndex < 0 || endingIndex <0){
                return builder.append(text);
            }
            else if(startingIndex >= 0 && endingIndex >=0){

                builder.append(text);
                builder.setSpan(new AbsoluteSizeSpan(size, true), startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }else{
            return builder.append(text);
        }

        return builder;
    }

UITextField border color

Update for swift 5.0

textField.layer.masksToBounds = true
textField.layer.borderColor = UIColor.blue.cgColor
textField.layer.borderWidth = 1.0

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

Get HTML code from website in C#

Better you can use the Webclient class to simplify your task:

using System.Net;

using (WebClient client = new WebClient())
{
    string htmlCode = client.DownloadString("http://somesite.com/default.html");
}

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

This error is caused by corrupted proj file.

Visual Studio always has backup project file at specific folder.

Please browse to:

C:\Users\<Your user>\Documents\Visual Studio <Vs version>\Backup Files\<your project>

You should see 2 files like this:

Original-May-18-2018-1209PM.<your project>.csproj
Recovered-May-18-2018-1209PM.<your project>.csproj

You only need copy file:

Original-May-18-2018-1209PM.<your project>.csproj

And re-name as

<your project>.csproj 

and override at root project folder.

Problem is solved!

Convert iterator to pointer?

Vector is a template class and it is not safe to convert the contents of a class to a pointer : You cannot inherit the vector class to add this new functionality. and changing the function parameter is actually a better idea. Jst create another vector of int vector temp_foo (foo.begin[X],foo.end()); and pass this vector to you functions

Set Google Chrome as the debugging browser in Visual Studio

  1. Go to the visual studio toolbar and click on the dropdown next to CPU (where it says IIS Express in the screenshot). One of the choices should be "Browse With..."

    Visual Studio Toolbar

  2. Select a browser, e.g. Google Chrome, then click Set as Default

    Browse With...

  3. Click Browse or Cancel.

Determining if an Object is of primitive type

I'm late to the show, but if you're testing a field, you can use getGenericType:

import static org.junit.Assert.*;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Test;

public class PrimitiveVsObjectTest {

    private static final Collection<String> PRIMITIVE_TYPES = 
            new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));

    private static boolean isPrimitive(Type type) {
        return PRIMITIVE_TYPES.contains(type.getTypeName());
    }

    public int i1 = 34;
    public Integer i2 = 34;

    @Test
    public void primitive_type() throws NoSuchFieldException, SecurityException {
        Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
        Type genericType1 = i1Field.getGenericType();
        assertEquals("int", genericType1.getTypeName());
        assertNotEquals("java.lang.Integer", genericType1.getTypeName());
        assertTrue(isPrimitive(genericType1));
    }

    @Test
    public void object_type() throws NoSuchFieldException, SecurityException {
        Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
        Type genericType2 = i2Field.getGenericType();
        assertEquals("java.lang.Integer", genericType2.getTypeName());
        assertNotEquals("int", genericType2.getTypeName());
        assertFalse(isPrimitive(genericType2));
    }
}

The Oracle docs list the 8 primitive types.

Navigation bar with UIImage for title

You can use custom UINavigationItem so, you only need to change "Navigation Item" as YourCustomClass on the Main.storyboard.

In Swift 3

class FixedImageNavigationItem: UINavigationItem {

private let fixedImage : UIImage = UIImage(named: "your-header-logo.png")!
private let imageView : UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 37.5))

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    imageView.contentMode = .scaleAspectFit
    imageView.image = fixedImage
    self.titleView = imageView

}

}

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

@EH_warch You need to use the Complete callback to generate your base64:

onAnimationComplete: function(){
    console.log(this.toBase64Image())
}

If you see a white image, it means you called the toBase64Image before it finished rendering.

Repeat string to certain length

i use this:

def extend_string(s, l):
    return (s*l)[:l]

Access mysql remote database from command line

I was too getting the same error. But found it useful by creating new mysql user on remote mysql server ans then connect. Run following command on remote server:

CREATE USER 'openvani'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'openvani'@'localhost WITH GRANT 
OPTION;
CREATE USER 'openvani'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'openvani'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Now you can connect with remote mysql with following command.

mysql -u openvani -h 'any ip address'-p

Here is the full post:

http://openvani.com/blog/connect-remotely-mysql-server/

How can I catch all the exceptions that will be thrown through reading and writing a file?

Catch the base exception 'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }

Does Android support near real time push notification?

Firebase Cloud Messaging FCM FAQ is the new version of GCM. It inherits GCM’s core infrastructure to deliver messages reliably on Android, iOS and Chrome. However they'll continue to support GCM because lot of developers are using GCM SDKs today to handle notifications, and client app upgrade takes time.

As of June 26, 2012, Google Cloud Messaging is the preferred way of sending messages to applications running on devices.

Previously (and now deprecated), the service was called Cloud To Device Messaging.

How do I download the Android SDK without downloading Android Studio?

I downloaded Android Studio and installed it. The installer said:-

Android Studio => ( 500 MB )

Android SDK => ( 2.3 GB )

Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".

Most importantly:- Android Studio Installer will not just install the SDK. It will also:-

  • Install the latest build-tools.
  • Install the latest platform-tools.
  • Install the latest AVD Manager which you cannot do without.

Things which you will have to do manually if you install the SDK from its zip file.

Just take it easy. Install the Android Studio.

****************************** Edit ******************************

So, being inspired by the responses in the comments I would like to update my answer.

The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.

Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.

Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.

I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).

SQL Query for Selecting Multiple Records

Try the following code:

SELECT *
FROM users
WHERE firstname IN ('joe','jane');

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

Disabling enter key for form

The solution is so simple:

Replace type "Submit" with button

<input type="button" value="Submit" onclick="this.form.submit()" />

forEach loop Java 8 for Map entry set

HashMap<String,Integer> hm = new HashMap();

 hm.put("A",1);
 hm.put("B",2);
 hm.put("C",3);
 hm.put("D",4);

 hm.forEach((key,value)->{
     System.out.println("Key: "+key + " value: "+value);
 });

Read a javascript cookie by name

document.cookie="MYBIGCOOKIE=1";

Your cookies would look like:

"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"

first of all read all cookies:

var read_cookies = document.cookie;

then split all cookies with ";":

var split_read_cookie = read_cookies.split(";");

then use for loop to read each value. Into loop each value split again with "=":

for (i=0;i<split_read_cookie.length;i++){
    var value=split_read_cookie[i];
    value=value.split("=");
    if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
        alert('it is 1');
    }
}

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

MacOSX homebrew mysql root password

Running these lines in the terminal did the trick for me and several others who had the same problem. These instructions are listed in the terminal after brew installs mysql sucessfully.

mkdir -p ~/Library/LaunchAgents

cp /usr/local/Cellar/mysql/5.5.25a/homebrew.mxcl.mysql.plist ~/Library/LaunchAgents/

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

/usr/local/Cellar/mysql/5.5.25a/bin/mysqladmin -u root password 'YOURPASSWORD'

where YOURPASSWORD is the password for root.

Updating property value in properties file without deleting other values

Open the output stream and store properties after you have closed the input stream.

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();

FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

How to get current timestamp in milliseconds since 1970 just the way Java gets

use <sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

refer this.

How to make vim paste from (and copy to) system's clipboard?

With Vim 8+ on Linux or Mac, you can now simply use the OS' native paste (ctrl+shift+V on Linux, cmd+V on Mac). Do not press i for Insert Mode.

It will paste the contents of your OS clipboard, preserving the spaces and tabs without adding autoindenting. It's equivalent to the old :set paste, i, ctrl+shift+V, esc, :set nopaste method.

You don't even need the +clipboard or +xterm_clipboard vim features installed anymore. This feature is called "bracketed paste". For more details, see Turning off auto indent when pasting text into vim

Call Stored Procedure within Create Trigger in SQL Server

finally...

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

GO
ALTER TRIGGER [dbo].[RA2Newsletter] 
   ON  [dbo].[Reiseagent] 
   AFTER INSERT
 AS
    declare
    @rAgent_Name nvarchar(50),
    @rAgent_Email nvarchar(50),
    @rAgent_IP nvarchar(50),
    @hotelID int,
    @retval int


BEGIN
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    Select @rAgent_Name=rAgent_Name,@rAgent_Email=rAgent_Email,@rAgent_IP=rAgent_IP,@hotelID=hotelID  From Inserted
    EXEC insert2Newsletter '','',@rAgent_Name,@rAgent_Email,@rAgent_IP,@hotelID,'RA', @retval

END

Visual Studio Code - Convert spaces to tabs

Ctrl+Shift+P, then "Convert Indentation to Tabs"

CSS position:fixed inside a positioned element

Seems, css transforms can be used

"‘transform’ property establishes a new local coordinate system at the element",

but ... this is not cross-browser, seems only Opera works correctly

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

Setting a spinner onClickListener() in Android

I suggest that all events for Spinner are divided on two types:

  1. User events (you meant as "click" event).

  2. Program events.

I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:

private void setSelectionWithoutDispatch(Spinner spinner, int position) {
    AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
    spinner.setOnItemSelectedListener(null);
    spinner.setSelection(position, false);
    spinner.setOnItemSelectedListener(onItemSelectedListener);
}

There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.

Storing and displaying unicode string (??????) using PHP and MySQL

CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');

Find duplicate lines in a file and count how many time each line was duplicated?

Via :

awk '{dups[$1]++} END{for (num in dups) {print num,dups[num]}}' data

In awk 'dups[$1]++' command, the variable $1 holds the entire contents of column1 and square brackets are array access. So, for each 1st column of line in data file, the node of the array named dups is incremented.

And at the end, we are looping over dups array with num as variable and print the saved numbers first then their number of duplicated value by dups[num].

Note that your input file has spaces on end of some lines, if you clear up those, you can use $0 in place of $1 in command above :)

Create hyperlink to another sheet

The "!" sign is the key element. If you have a cell object (like "mycell" in following code sample) and link a cell to this object you must pay attention to ! element.

You must do something like this:

.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
     SubAddress:= "'" & ws.Name & "'" & _
     "!" & mycell.Address

LINQ Joining in C# with multiple conditions

As far as I know you can only join this way:

var query = from obj_i in set1
join obj_j in set2 on 
    new { 
      JoinProperty1 = obj_i.SomeField1,
      JoinProperty2 = obj_i.SomeField2,
      JoinProperty3 = obj_i.SomeField3,
      JoinProperty4 = obj_i.SomeField4
    } 
    equals 
    new { 
      JoinProperty1 = obj_j.SomeOtherField1,
      JoinProperty2 = obj_j.SomeOtherField2,
      JoinProperty3 = obj_j.SomeOtherField3,
      JoinProperty4 = obj_j.SomeOtherField4
    }

The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.

You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.

More advanced stuff in this LinqPad example:

class c1 
    {
    public int someIntField;
    public string someStringField;
    }
    
class c2 
    {
    public Int64 someInt64Property {get;set;}
    private object someField;
    public string someStringFunction(){return someField.ToString();}
    }
    
void Main()
{
    var set1 = new List<c1>();
    var set2 = new List<c2>();
    
    var query = from obj_i in set1
    join obj_j in set2 on 
        new { 
                JoinProperty1 = (Int64) obj_i.someIntField,
                JoinProperty2 = obj_i.someStringField
            } 
        equals 
        new { 
                JoinProperty1 = obj_j.someInt64Property,
                JoinProperty2 = obj_j.someStringFunction()
            }
    select new {obj1 = obj_i, obj2 = obj_j};
}

Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.

How do you get AngularJS to bind to the title attribute of an A tag?

The issue here is your version of AngularJS; ng-attr is not working due to the fact that it was introduced in version 1.1.4. I am unsure as to why title="{{product.shortDesc}}" isn't working for you, but I imagine it is for similar reasons (old Angular version). I tested this on 1.2.9 and it is working for me.

As for the other answers here, this is NOT among the few use cases for ng-attr! This is a simple double-curly-bracket situation:

<a title="{{product.shortDesc}}" ng-bind="product.shortDesc" />

Batch file to delete files older than N days

There are very often relative date/time related questions to solve with batch file. But command line interpreter cmd.exe has no function for date/time calculations. Lots of good working solutions using additional console applications or scripts have been posted already here, on other pages of Stack Overflow and on other websites.

Common for operations based on date/time is the requirement to convert a date/time string to seconds since a determined day. Very common is 1970-01-01 00:00:00 UTC. But any later day could be also used depending on the date range required to support for a specific task.

Jay posted 7daysclean.cmd containing a fast "date to seconds" solution for command line interpreter cmd.exe. But it does not take leap years correct into account. J.R. posted an add-on for taking leap day in current year into account, but ignoring the other leap years since base year, i.e. since 1970.

I use since 20 years static tables (arrays) created once with a small C function for quickly getting the number of days including leap days from 1970-01-01 in date/time conversion functions in my applications written in C/C++.

This very fast table method can be used also in batch code using FOR command. So I decided to code the batch subroutine GetSeconds which calculates the number of seconds since 1970-01-01 00:00:00 UTC for a date/time string passed to this routine.

Note: Leap seconds are not taken into account as the Windows file systems also do not support leap seconds.

First, the tables:

  1. Days since 1970-01-01 00:00:00 UTC for each year including leap days.

    1970 - 1979:     0   365   730  1096  1461  1826  2191  2557  2922  3287
    1980 - 1989:  3652  4018  4383  4748  5113  5479  5844  6209  6574  6940
    1990 - 1999:  7305  7670  8035  8401  8766  9131  9496  9862 10227 10592
    2000 - 2009: 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245
    2010 - 2019: 14610 14975 15340 15706 16071 16436 16801 17167 17532 17897
    2020 - 2029: 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550
    2030 - 2039: 21915 22280 22645 23011 23376 23741 24106 24472 24837 25202
    2040 - 2049: 25567 25933 26298 26663 27028 27394 27759 28124 28489 28855
    2050 - 2059: 29220 29585 29950 30316 30681 31046 31411 31777 32142 32507
    2060 - 2069: 32872 33238 33603 33968 34333 34699 35064 35429 35794 36160
    2070 - 2079: 36525 36890 37255 37621 37986 38351 38716 39082 39447 39812
    2080 - 2089: 40177 40543 40908 41273 41638 42004 42369 42734 43099 43465
    2090 - 2099: 43830 44195 44560 44926 45291 45656 46021 46387 46752 47117
    2100 - 2106: 47482 47847 48212 48577 48942 49308 49673
    

    Calculating the seconds for year 2039 to 2106 with epoch beginning 1970-01-01 is only possible with using an unsigned 32-bit variable, i.e. unsigned long (or unsigned int) in C/C++.

    But cmd.exe use for mathematical expressions a signed 32-bit variable. Therefore the maximum value is 2147483647 (0x7FFFFFFF) which is 2038-01-19 03:14:07.

  2. Leap year information (No/Yes) for the years 1970 to 2106.

    1970 - 1989: N N Y N N N Y N N N Y N N N Y N N N Y N
    1990 - 2009: N N Y N N N Y N N N Y N N N Y N N N Y N
    2010 - 2029: N N Y N N N Y N N N Y N N N Y N N N Y N
    2030 - 2049: N N Y N N N Y N N N Y N N N Y N N N Y N
    2050 - 2069: N N Y N N N Y N N N Y N N N Y N N N Y N
    2070 - 2089: N N Y N N N Y N N N Y N N N Y N N N Y N
    2090 - 2106: N N Y N N N Y N N N N N N N Y N N
                                     ^ year 2100
    
  3. Number of days to first day of each month in current year.

                       Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
    Year with 365 days:  0  31  59  90 120 151 181 212 243 273 304 334
    Year with 366 days:  0  31  60  91 121 152 182 213 244 274 305 335
    

Converting a date to number of seconds since 1970-01-01 is quite easy using those tables.

Attention please!

The format of date and time strings depends on Windows region and language settings. The delimiters and the order of tokens assigned to the environment variables Day, Month and Year in first FOR loop of GetSeconds must be adapted to local date/time format if necessary.

It is necessary to adapt the date string of the environment variable if date format in environment variable DATE is different to date format used by command FOR on %%~tF.

For example when %DATE% expands to Sun 02/08/2015 while %%~tF expands to 02/08/2015 07:38 PM the code below can be used with modifying line 4 to:

call :GetSeconds "%DATE:~4% %TIME%"

This results in passing to subroutine just 02/08/2015 - the date string without the 3 letters of weekday abbreviation and the separating space character.

Alternatively following could be used to pass current date in correct format:

call :GetSeconds "%DATE:~-10% %TIME%"

Now the last 10 characters from date string are passed to function GetSeconds and therefore it does not matter if date string of environment variable DATE is with or without weekday as long as day and month are always with 2 digits in expected order, i.e. in format dd/mm/yyyy or dd.mm.yyyy.

Here is the batch code with explaining comments which just outputs which file to delete and which file to keep in C:\Temp folder tree, see code of first FOR loop.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Get seconds since 1970-01-01 for current date and time.
call :GetSeconds "%DATE% %TIME%"
rem Subtract seconds for 7 days from seconds value.
set /A "LastWeek=Seconds-7*86400"

rem For each file in each subdirectory of C:\Temp get last modification date
rem (without seconds -> append second 0) and determine the number of seconds
rem since 1970-01-01 for this date/time. The file can be deleted if seconds
rem value is lower than the value calculated above.

for /F "delims=" %%# in ('dir /A-D-H-S /B /S "C:\Temp"') do (
    call :GetSeconds "%%~t#:0"
    set "FullFileName=%%#"
    setlocal EnableDelayedExpansion
    rem if !Seconds! LSS %LastWeek% del /F "!FullFileName!"
    if !Seconds! LEQ %LastWeek% (
        echo Delete "!FullFileName!"
    ) else (
        echo Keep   "!FullFileName!"
    )
    endlocal
)
endlocal
goto :EOF


rem No validation is made for best performance. So make sure that date
rem and hour in string is in a format supported by the code below like
rem MM/DD/YYYY hh:mm:ss or M/D/YYYY h:m:s for English US date/time.

:GetSeconds
rem If there is " AM" or " PM" in time string because of using 12 hour
rem time format, remove those 2 strings and in case of " PM" remember
rem that 12 hours must be added to the hour depending on hour value.

set "DateTime=%~1"
set "Add12Hours=0"
if not "%DateTime: AM=%" == "%DateTime%" (
    set "DateTime=%DateTime: AM=%"
) else if not "%DateTime: PM=%" == "%DateTime%" (
    set "DateTime=%DateTime: PM=%"
    set "Add12Hours=1"
)

rem Get year, month, day, hour, minute and second from first parameter.

for /F "tokens=1-6 delims=,-./: " %%A in ("%DateTime%") do (
    rem For English US date MM/DD/YYYY or M/D/YYYY
    set "Day=%%B" & set "Month=%%A" & set "Year=%%C"
    rem For German date DD.MM.YYYY or English UK date DD/MM/YYYY
    rem set "Day=%%A" & set "Month=%%B" & set "Year=%%C"
    set "Hour=%%D" & set "Minute=%%E" & set "Second=%%F"
)
rem echo Date/time is: %Year%-%Month%-%Day% %Hour%:%Minute%:%Second%

rem Remove leading zeros from the date/time values or calculation could be wrong.
if "%Month:~0,1%"  == "0" if not "%Month:~1%"  == "" set "Month=%Month:~1%"
if "%Day:~0,1%"    == "0" if not "%Day:~1%"    == "" set "Day=%Day:~1%"
if "%Hour:~0,1%"   == "0" if not "%Hour:~1%"   == "" set "Hour=%Hour:~1%"
if "%Minute:~0,1%" == "0" if not "%Minute:~1%" == "" set "Minute=%Minute:~1%"
if "%Second:~0,1%" == "0" if not "%Second:~1%" == "" set "Second=%Second:~1%"

rem Add 12 hours for time range 01:00:00 PM to 11:59:59 PM,
rem but keep the hour as is for 12:00:00 PM to 12:59:59 PM.
if %Add12Hours% == 1 if %Hour% LSS 12 set /A Hour+=12

set "DateTime="
set "Add12Hours="

rem Must use two arrays as more than 31 tokens are not supported
rem by command line interpreter cmd.exe respectively command FOR.
set /A "Index1=Year-1979"
set /A "Index2=Index1-30"

if %Index1% LEQ 30 (
    rem Get number of days to year for the years 1980 to 2009.
    for /F "tokens=%Index1% delims= " %%Y in ("3652 4018 4383 4748 5113 5479 5844 6209 6574 6940 7305 7670 8035 8401 8766 9131 9496 9862 10227 10592 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245") do set "Days=%%Y"
    for /F "tokens=%Index1% delims= " %%L in ("Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N") do set "LeapYear=%%L"
) else (
    rem Get number of days to year for the years 2010 to 2038.
    for /F "tokens=%Index2% delims= " %%Y in ("14610 14975 15340 15706 16071 16436 16801 17167 17532 17897 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550 21915 22280 22645 23011 23376 23741 24106 24472 24837") do set "Days=%%Y"
    for /F "tokens=%Index2% delims= " %%L in ("N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N") do set "LeapYear=%%L"
)

rem Add the days to month in year.
if "%LeapYear%" == "N" (
    for /F "tokens=%Month% delims= " %%M in ("0 31 59 90 120 151 181 212 243 273 304 334") do set /A "Days+=%%M"
) else (
    for /F "tokens=%Month% delims= " %%M in ("0 31 60 91 121 152 182 213 244 274 305 335") do set /A "Days+=%%M"
)

rem Add the complete days in month of year.
set /A "Days+=Day-1"

rem Calculate the seconds which is easy now.
set /A "Seconds=Days*86400+Hour*3600+Minute*60+Second"

rem Exit this subroutine.
goto :EOF

For optimal performance it would be best to remove all comments, i.e. all lines starting with rem after 0-4 leading spaces.

And the arrays can be made also smaller, i.e. decreasing the time range from 1980-01-01 00:00:00 to 2038-01-19 03:14:07 as currently supported by the batch code above for example to 2015-01-01 to 2019-12-31 as the code below uses which really deletes files older than 7 days in C:\Temp folder tree.

Further the batch code below is optimized for 24 hours time format.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
call :GetSeconds "%DATE:~-10% %TIME%"
set /A "LastWeek=Seconds-7*86400"

for /F "delims=" %%# in ('dir /A-D-H-S /B /S "C:\Temp"') do (
    call :GetSeconds "%%~t#:0"
    set "FullFileName=%%#"
    setlocal EnableDelayedExpansion
    if !Seconds! LSS %LastWeek% del /F "!FullFileName!"
    endlocal
)
endlocal
goto :EOF

:GetSeconds
for /F "tokens=1-6 delims=,-./: " %%A in ("%~1") do (
    set "Day=%%B" & set "Month=%%A" & set "Year=%%C"
    set "Hour=%%D" & set "Minute=%%E" & set "Second=%%F"
)
if "%Month:~0,1%"  == "0" if not "%Month:~1%"  == "" set "Month=%Month:~1%"
if "%Day:~0,1%"    == "0" if not "%Day:~1%"    == "" set "Day=%Day:~1%"
if "%Hour:~0,1%"   == "0" if not "%Hour:~1%"   == "" set "Hour=%Hour:~1%"
if "%Minute:~0,1%" == "0" if not "%Minute:~1%" == "" set "Minute=%Minute:~1%"
if "%Second:~0,1%" == "0" if not "%Second:~1%" == "" set "Second=%Second:~1%"
set /A "Index=Year-2014"
for /F "tokens=%Index% delims= " %%Y in ("16436 16801 17167 17532 17897") do set "Days=%%Y"
for /F "tokens=%Index% delims= " %%L in ("N Y N N N") do set "LeapYear=%%L"
if "%LeapYear%" == "N" (
    for /F "tokens=%Month% delims= " %%M in ("0 31 59 90 120 151 181 212 243 273 304 334") do set /A "Days+=%%M"
) else (
    for /F "tokens=%Month% delims= " %%M in ("0 31 60 91 121 152 182 213 244 274 305 335") do set /A "Days+=%%M"
)
set /A "Days+=Day-1"
set /A "Seconds=Days*86400+Hour*3600+Minute*60+Second"
goto :EOF

For even more information about date and time formats and file time comparisons on Windows see my answer on Find out if file is older than 4 hours in batch file with lots of additional information about file times.

Detect click inside/outside of element with single event handler

This question can be answered with X and Y coordinates and without JQuery:

       var isPointerEventInsideElement = function (event, element) {
            var pos = {
                x: event.targetTouches ? event.targetTouches[0].pageX : event.pageX,
                y: event.targetTouches ? event.targetTouches[0].pageY : event.pageY
            };
            var rect = element.getBoundingClientRect();
            return  pos.x < rect.right && pos.x > rect.left && pos.y < rect.bottom && pos.y > rect.top;
        };

        document.querySelector('#my-element').addEventListener('click', function (event) {
           console.log(isPointerEventInsideElement(event, document.querySelector('#my-any-child-element')))
        });

Suppress command line output

Because error messages often go to stderr not stdout.

Change the invocation to this:

taskkill /im "test.exe" /f >nul 2>&1

and all will be better.

That works because stdout is file descriptor 1, and stderr is file descriptor 2 by convention. (0 is stdin, incidentally.) The 2>&1 copies output file descriptor 2 from the new value of 1, which was just redirected to the null device.

This syntax is (loosely) borrowed from many Unix shells, but you do have to be careful because there are subtle differences between the shell syntax and CMD.EXE.

Update: I know the OP understands the special nature of the "file" named NUL I'm writing to here, but a commenter didn't and so let me digress with a little more detail on that aspect.

Going all the way back to the earliest releases of MSDOS, certain file names were preempted by the file system kernel and used to refer to devices. The earliest list of those names included NUL, PRN, CON, AUX and COM1 through COM4. NUL is the null device. It can always be opened for either reading or writing, any amount can be written on it, and reads always succeed but return no data. The others include the parallel printer port, the console, and up to four serial ports. As of MSDOS 5, there were several more reserved names, but the basic convention was very well established.

When Windows was created, it started life as a fairly thin application switching layer on top of the MSDOS kernel, and thus had the same file name restrictions. When Windows NT was created as a true operating system in its own right, names like NUL and COM1 were too widely assumed to work to permit their elimination. However, the idea that new devices would always get names that would block future user of those names for actual files is obviously unreasonable.

Windows NT and all versions that follow (2K, XP, 7, and now 8) all follow use the much more elaborate NT Namespace from kernel code and to carefully constructed and highly non-portable user space code. In that name space, device drivers are visible through the \Device folder. To support the required backward compatibility there is a special mechanism using the \DosDevices folder that implements the list of reserved file names in any file system folder. User code can brows this internal name space using an API layer below the usual Win32 API; a good tool to explore the kernel namespace is WinObj from the SysInternals group at Microsoft.

For a complete description of the rules surrounding legal names of files (and devices) in Windows, this page at MSDN will be both informative and daunting. The rules are a lot more complicated than they ought to be, and it is actually impossible to answer some simple questions such as "how long is the longest legal fully qualified path name?".

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

Creating a "logical exclusive or" operator in Java

This is an example of using XOR(^), from this answer

byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };

byte[] array_3 = new byte[6];

int i = 0;
for (byte b : array_1)
    array_3[i] = b ^ array_2[i++];

Output

0 0 1 1 1 0

How to set background image of a view?

It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.

The best design would be to have the labels on a constant background with the images changing behind that.

You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.

To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.

The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.

Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.

Rename master branch for both local and remote Git repositories

Good. My 2 cents. How about loggin in at the server, going to the git directory and renaming the branch in the bare repository. This does not have all the problems associated with reuploading the same branch. Actually, the 'clients' will automatically recognize the modified name and change their remote reference. Afterwards (or before) you can also modify the local name of the branch.

How to generate a random number between a and b in Ruby?

And here is a quick benchmark for both #sample and #rand:

irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1*   x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1>   x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
       user     system      total        real
sample  3.870000   0.020000   3.890000 (  3.888147)
rand  0.150000   0.000000   0.150000 (  0.153557)

So, doing rand(a..b) is the right thing

Filter Java Stream to 1 and only 1 element

Using reduce

This is the simpler and flexible way I found (based on @prunge answer)

Optional<User> user = users.stream()
        .filter(user -> user.getId() == 1)
        .reduce((a, b) -> {
            throw new IllegalStateException("Multiple elements: " + a + ", " + b);
        })

This way you obtain:

  • the Optional - as always with your object or Optional.empty() if not present
  • the Exception (with eventually YOUR custom type/message) if there's more than one element

Proxy Basic Authentication in C#: HTTP 407 error

This method may avoid the need to hard code or configure proxy credentials, which may be desirable.

Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
</configuration>

Connecting to Oracle Database through C#?

Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

I cannot start SQL Server browser

right click on SQL Server browser and properties, then Connection tab and chose open session with system account and not this account. then apply and chose automatic and finally run the server.

Android center view in FrameLayout doesn't work

Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MovieActivity"
    android:id="@+id/mainContainerMovie"
    >


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3a3f51b5"
       />

    <ProgressBar
        android:id="@+id/movieprogressbar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>

How to run a jar file in a linux commandline

sudo -sH
java -jar filename.jar

Keep in mind to never run executable file in as root.

Sql connection-string for localhost server

Data Source=HARIHARAN-PC\SQLEXPRESS; Initial Catalog=Your_DataBase_name; Integrated Security=true/false; User ID=your_Username;Password=your_Password;

To know more about connection string Click here

Passing a 2D array to a C++ function

You can do something like this...

#include<iostream>

using namespace std;

//for changing values in 2D array
void myFunc(double *a,int rows,int cols){
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            *(a+ i*rows + j)+=10.0;
        }
    }
}

//for printing 2D array,similar to myFunc
void printArray(double *a,int rows,int cols){
    cout<<"Printing your array...\n";
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            cout<<*(a+ i*rows + j)<<"  ";
        }
    cout<<"\n";
    }
}

int main(){
    //declare and initialize your array
    double a[2][2]={{1.5 , 2.5},{3.5 , 4.5}};

    //the 1st argument is the address of the first row i.e
    //the first 1D array
    //the 2nd argument is the no of rows of your array
    //the 3rd argument is the no of columns of your array
    myFunc(a[0],2,2);

    //same way as myFunc
    printArray(a[0],2,2);

    return 0;
}

Your output will be as follows...

11.5  12.5
13.5  14.5

Mount current directory as a volume in Docker on Windows 10

Here is mine which is compatible for both Win10 docker-ce & Win7 docker-toolbox. At las at the time I'm writing this :).

You can notice I prefer use /host_mnt/c instead of c:/ because I sometimes encountered trouble on docker-ce Win 10 with c:/

$WIN_PATH=Convert-Path .

#Convert for docker mount to be OK on Windows10 and Windows 7 Powershell
#Exact conversion is : remove the ":" symbol, replace all "\" by "/", remove last "/" and minor case only the disk letter
#Then for Windows10, add a /host_mnt/" at the begin of string => this way : c:\Users is translated to /host_mnt/c/Users
#For Windows7, add "//" => c:\Users is translated to //c/Users
$MOUNT_PATH=(($WIN_PATH -replace "\\","/") -replace ":","").Trim("/")

[regex]$regex='^[a-zA-Z]/'
$MOUNT_PATH=$regex.Replace($MOUNT_PATH, {$args[0].Value.ToLower()})

#Win 10
if ([Environment]::OSVersion.Version -ge (new-object 'Version' 10,0)) {
$MOUNT_PATH="/host_mnt/$MOUNT_PATH"
}
elseif ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)) {
$MOUNT_PATH="//$MOUNT_PATH"
}

docker run -it -v "${MOUNT_PATH}:/tmp/test" busybox ls /tmp/test