Programs & Examples On #Query help

How to store Java Date to Mysql datetime with JPA

I still prefer the method in one line

new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())

SSRS the definition of the report is invalid

This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Another way to do is is to use file_get_contents() and have a template HTML page

TEMPLATE PAGE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>

PHP Function

function YOURFUNCTIONNAME($url){

$html_string = file_get_contents($url);
return $html_string;

}

JSHint and jQuery: '$' is not defined

You probably want to do the following,

const $ = window.$

to avoid it throwing linting error.

How to remove an item from an array in AngularJS scope?

I would use the Underscore.js library that has a list of useful functions.

without

without_.without(array, *values)

Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]

Example

var res = "deleteMe";

$scope.nodes = [
  {
    name: "Node-1-1"
  },
  {
    name: "Node-1-2"
  },
  {
    name: "deleteMe"
  }
];
    
$scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes, {
  name: res
}));

See Demo in JSFiddle.


filter

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

// => [2, 4, 6]

Example

$scope.newNodes = _.filter($scope.nodes, function(node) {
  return !(node.name == res);
});

See Demo in Fiddle.

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

Parse String to Date with Different Format in Java

tl;dr

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details

The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.

You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console.

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | output: mardi 19 mai 2009

See in action in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

refresh both the External data source and pivot tables together within a time schedule

I found this solution online, and it addressed this pretty well. My only concern is looping through all the pivots and queries might become time consuming if there's a lot of them:

Sub RefreshTables()

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim objList As ListObject
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each objList In ws.ListObjects
        If objList.SourceType = 3 Then
            With objList.QueryTable
                .BackgroundQuery = False
                .Refresh
            End With
        End If
    Next objList
Next ws

Call UpdateAllPivots

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Sub UpdateAllPivots()
Dim pt As PivotTable
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each pt In ws.PivotTables
        pt.RefreshTable
    Next pt
Next ws

End Sub

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

Smooth GPS data

One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing

For example

Smoothing at five sample points A, B, C, D, E

ATOTAL = SUM of distances AB AC AD AE

BTOTAL = SUM of distances AB BC BD BE

CTOTAL = SUM of distances AC BC CD CE

DTOTAL = SUM of distances DA DB DC DE

ETOTAL = SUM of distances EA EB EC DE

If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }

This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

How to get the part of a file after the first line that matches a regular expression?

If I understand your question correctly you do want the lines after TERMINATE, not including the TERMINATE-line. awk can do this in a simple way:

awk '{if(found) print} /TERMINATE/{found=1}' your_file

Explanation:

  1. Although not best practice you could rely on the fact that all vars defaults to 0 or the empty string if not defined. So the first expression (if(found) print) will not print anything to start off with.
  2. After the printing is done we check if the this is the starter-line (that should not be included).

This will print all lines after the TERMINATE-line.


Generalization:

  • You have a file with start- and end-lines and you want the lines between those lines excluding the start- and end-lines.
  • start- and end-lines could be defined by a regular expression matching the line.

Example:

$ cat ex_file.txt 
not this line
second line
START
A good line to include
And this line
Yep
END
Nope more
...
never ever
$ awk '/END/{found=0} {if(found) print} /START/{found=1}' ex_file.txt 
A good line to include
And this line
Yep
$

Explanation:

  1. If the end-line is found no printing should be done. Note that this check is done before the actual printing to exclude the end-line from the result.
  2. Print the current line if found is set.
  3. If the start-line is found then set found=1 so that the following lines are printed. Note that this check is done after the actual printing to exclude the start-line from the result.

Notes:

  • The code rely on the fact that all awk-vars defaults to 0 or the empty string if not defined. This is valid but may not be best practice so you could add a BEGIN{found=0} to the start of the awk-expression.
  • If multiple start-end-blocks is found they are all printed.

Composer install error - requires ext_curl when it's actually enabled

For anyone who encounters this issue on Windows i couldn't find my answer on google at all. I just tried running composer require ext-curl and this worked. Alternatively add the following in your composer.json file:

"require": {
"ext-curl": "^7.3"
}

Proper use of const for defining functions in JavaScript

There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.

A function declaration, that is:

function doSomething () {}

Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).

This means that the following will work:

doSomething() // works!
function doSomething() {}

A function expression, that is:

[const | let | var] = function () {} (or () =>

Is the creation of an anonymous function (function () {}) and the creation of a variable, and then the assignment of that anonymous function to that variable.

So the usual rules around variable hoisting within a scope -- block-scoped variables (let and const) do not hoist as undefined to the top of their block scope.

This means:

if (true) {
    doSomething() // will fail
    const doSomething = function () {}
}

Will fail since doSomething is not defined. (It will throw a ReferenceError)

If you switch to using var you get your hoisting of the variable, but it will be initialized to undefined so that block of code above will still not work. (This will throw a TypeError since doSomething is not a function at the time you call it)

As far as standard practices go, you should always use the proper tool for the job.

Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6

How do I specify a password to 'psql' non-interactively?

Set the PGPASSWORD environment variable inside the script before calling psql

PGPASSWORD=pass1234 psql -U MyUsername myDatabaseName

For reference, see http://www.postgresql.org/docs/current/static/libpq-envars.html


Edit

Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain the username and password.

Using that is a security risk because the password is visible in plain text when looking at the command line of a running process e.g. using ps (Linux), ProcessExplorer (Windows) or similar tools, by other users.

See also this question on Database Administrators

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

How can I merge two MySQL tables?

INSERT
INTO    first_table f
SELECT  *
FROM    second_table s
ON DUPLICATE KEY
UPDATE
        s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

Most of the solutions provided either don't use TRUNCATE, which is different from DELETE, or they don't deal with the issue of foreign key constraints. The solution provided by Chaitanya comes close, but it falls back to using DELETE, and it does it in a stored procedure, which seems to not fit a situation where you are nuking all data in a database.

So, below is my variation which does use TRUNCATE and does address the foreign key constraint problem.

    /* TRUNCATE ALL TABLES IN A DATABASE */

DECLARE @dropAndCreateConstraintsTable TABLE
        (
         DropStmt VARCHAR(MAX)
        ,CreateStmt VARCHAR(MAX)
        )
/* Gather information to drop and then recreate the current foreign key constraints  */
INSERT  @dropAndCreateConstraintsTable
        SELECT  DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
                + '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
                + ForeignKeys.ForeignKeyName + ']; '
               ,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
                + '].[' + ForeignKeys.ForeignTableName
                + '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
                + '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
                + ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
                + '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
                + ']); '
        FROM    sys.objects
        INNER JOIN sys.columns
                ON ( sys.columns.[object_id] = sys.objects.[object_id] )
        INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
                           ,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
                           ,sys.objects.[name] AS ForeignTableName
                           ,sys.columns.[name] AS ForeignTableColumn
                           ,sys.foreign_keys.referenced_object_id AS referenced_object_id
                           ,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
                     FROM   sys.foreign_keys
                     INNER JOIN sys.foreign_key_columns
                            ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
                     INNER JOIN sys.objects
                            ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
                     INNER JOIN sys.columns
                            ON ( sys.columns.[object_id] = sys.objects.[object_id] )
                               AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
                   ) ForeignKeys
                ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
                   AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
        WHERE   ( sys.objects.[type] = 'U' )
                AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )

/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT */

DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)

/* Drop Constraints */
DECLARE C1 CURSOR READ_ONLY
FOR
        SELECT  DropStmt
        FROM    @dropAndCreateConstraintsTable
OPEN C1

FETCH NEXT FROM C1 INTO @DropStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @DropStatement
            EXECUTE sp_executesql @DropStatement
            FETCH NEXT FROM C1 INTO @DropStatement
      END
CLOSE C1
DEALLOCATE C1

/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE C2 CURSOR READ_ONLY
FOR
        SELECT  'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE   TABLE_SCHEMA = 'dbo'
                AND TABLE_TYPE = 'BASE TABLE'
  /* Change your schema appropriately if you don't want to use dbo */
OPEN C2

FETCH NEXT FROM C2 INTO @DeleteTableStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @DeleteTableStatement
            EXECUTE sp_executesql @DeleteTableStatement
            FETCH NEXT FROM C2 INTO @DeleteTableStatement
      END
CLOSE C2
DEALLOCATE C2

/* Recreate foreign key constraints  */
DECLARE C3 CURSOR READ_ONLY
FOR
        SELECT  CreateStmt
        FROM    @dropAndCreateConstraintsTable
OPEN C3

FETCH NEXT FROM C3 INTO @RecreateStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @RecreateStatement
            EXECUTE sp_executesql @RecreateStatement
            FETCH NEXT FROM C3 INTO @RecreateStatement
      END
CLOSE C3
DEALLOCATE C3

GO

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

Creating an array from a text file in Bash

mapfile and readarray (which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array:

arr=()
while IFS= read -r line; do
  arr+=("$line")
done < file

In case the file has an incomplete (missing newline) last line, you could use this alternative:

arr=()
while IFS= read -r line || [[ "$line" ]]; do
  arr+=("$line")
done < file

Related:

Check if year is leap year in javascript

My Code Is Very Easy To Understand

var year = 2015;
var LeapYear = year % 4;

if (LeapYear==0) {
    alert("This is Leap Year");
} else {
    alert("This is not leap year");
}

XML element with attribute and content using JAXB

The correct scheme should be:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport" 
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
jaxb:version="2.0">

<complexType name="sportType">
    <simpleContent>
        <extension base="string">
            <attribute name="type" type="string" />
            <attribute name="gender" type="string" />
        </extension>
    </simpleContent>
</complexType>

<element name="sports">
    <complexType>
        <sequence>
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />
        </sequence>
    </complexType>
</element>

Code generated for SportType will be:

package org.example.sport;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
    @XmlValue
    protected String value;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String gender;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
    return type;
    }


    public void setType(String value) {
        this.type = value;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String value) {
        this.gender = value;
    }
}

Meaning of tilde in Linux bash (not home directory)

If you're using autofs then the expansion might actually be coming from /etc/auto.home (or similar for your distro). For example, my /etc/auto.master looks like:

/home2 auto.home --timeout 60

and /etc/auto.home looks like:

mgalgs -rw,noquota,intr space:/space/mgalgs

How to establish a connection pool in JDBC?

In the app server we use where I work (Oracle Application Server 10g, as I recall), pooling is handled by the app server. We retrieve a javax.sql.DataSource using a JNDI lookup with a javax.sql.InitialContext.

it's done something like this

try {     
   context = new InitialContext();
   jdbcURL = (DataSource) context.lookup("jdbc/CachedDS");
   System.out.println("Obtained Cached Data Source ");
}
catch(NamingException e)   
{  
    System.err.println("Error looking up Data Source from Factory: "+e.getMessage());
}

(We didn't write this code, it's copied from this documentation.)

Specify an SSH key for git push for a given domain

I am using Git Bash on Win7. The following worked for me.

Create a config file at ~/.ssh/config or c:/users/[your_user_name]/.ssh/config. In the file enter:

Host your_host.com
     IdentityFile [absolute_path_to_your_.ssh]\id_rsa

I guess the host has to be a URL and not just a "name" or ref for your host. For example,

Host github.com
     IdentityFile c:/users/[user_name]/.ssh/id_rsa

The path can also be written in /c/users/[user_name]/.... format

The solution provided by Giordano Scalzo is great too. https://stackoverflow.com/a/9149518/1738546

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

ng-change get new value and original value

You can always do:

... ng-model="file.PLIK_STATUS" ng-change="file.PLIK_STATUS = setFileStatus(file.PLIK_ID,file.PLIK_STATUS,'{{file.PLIK_STATUS}}')" ...

and in controller:

$scope.setFileStatus = function (plik_id, new_status, old_status) {
    var answer = confirm('Czy na pewno zmienic status dla pliku ?');
    if (answer) {
        podasysService.setFileStatus(plik_id, new_status).then(function (result) {
            return new_status;
        });
    }else{
        return old_status;
    }
};

How to detect if CMD is running as Administrator/has elevated privileges?

the solution:

at >nul
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

does not work under Windows 10

for all versions of Windows can be do so:

openfiles >nul 2>&1
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

How to style a JSON block in Github Wiki?

I encountered the same problem. So, I tried representing the JSON in different Language syntax formats.But all time favorites are Perl, js, python, & elixir.

This is how it looks.

The following screenshots are from the Gitlab in a markdown file. This may vary based on the colors using for syntax in MARKDOWN files.

JsonasPerl

JsonasPython

JsonasJs

JsonasElixir

Why is NULL undeclared?

Don't use NULL, C++ allows you to use the unadorned 0 instead:

previous = 0;
next = 0;

And, as at C++11, you generally shouldn't be using either NULL or 0 since it provides you with nullptr of type std::nullptr_t, which is better suited to the task.

Copying from one text file to another using Python

Safe and memory-saving:

with open("out1.txt", "w") as fw, open("in.txt","r") as fr: 
    fw.writelines(l for l in fr if "tests/file/myword" in l)

It doesn't create temporary lists (what readline and [] would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with blocks ensure that the files are closed on exit.

Create excel ranges using column numbers in vba?

These answers seem strangely convoluted. Unless I'm missing something...if you want to convert numbers to letters, you can just stock them all in an array using a for loop then call on the number associated with that column letter. Like so

For intloop = 1 To 26
    colcheck(intloop) = Chr$(64 + intloop)
    For lenloop = 1 To 26
        colcheck((intloop * 26) + lenloop) = Chr$(64 + intloop) & Chr$(64 + lenloop)
        For terloop = 1 To 26
            colcheck((intloop * 676) + (lenloop * 26) + terloop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop)
            For qualoop = 1 To 26
                colcheck((intloop * 17576) + (lenloop * 676) + (terloop * 26) + qualoop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop) & Chr$(64 + qualoop)
            Next qualoop
        Next terloop
    Next lenloop
Next intloop

Then just use colcheck(yourcolumnnumberhere) and you will get the column heading associated with that letter (i.e. colcheck(703) = AAA

Detecting touch screen devices with Javascript

Google Chrome seems to return false positives on this one:

var isTouch = 'ontouchstart' in document.documentElement;

I suppose it has something to do with its ability to "emulate touch events" (F12 -> settings at lower right corner -> "overrides" tab -> last checkbox). I know it's turned off by default but that's what I connect the change in results with (the "in" method used to work in Chrome). However, this seems to be working, as far as I have tested:

var isTouch = !!("undefined" != typeof document.documentElement.ontouchstart);

All browsers I've run that code on state the typeof is "object" but I feel more certain knowing that it's whatever but undefined :-)

Tested on IE7, IE8, IE9, IE10, Chrome 23.0.1271.64, Chrome for iPad 21.0.1180.80 and iPad Safari. It would be cool if someone made some more tests and shared the results.

How to detect the physical connected state of a network cable/connector?

On OpenWRT the only way to reliably do this, at least for me, is by running these commands:

# Get switch name
swconfig list

# assuming switch name is "switch0"
swconfig dev switch0 show | grep link:

# Possible output
root@OpenWrt:~# swconfig dev switch0 show | grep link:
        link: port:0 link:up speed:1000baseT full-duplex txflow rxflow
        link: port:1 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
        link: port:2 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
        link: port:3 link:down
        link: port:4 link:up speed:1000baseT full-duplex eee100 eee1000 auto
        link: port:5 link:down
        link: port:6 link:up speed:1000baseT full-duplex txflow rxflow

This will show either "link:down" or "link:up" on every port of your switch.

Multi-select dropdown list in ASP.NET

jQuery Dropdown Check List can be used to transform a regular multiple select html element into a dropdown checkbox list, it works on client so can be used with any server side technology:

alt text
(source: googlecode.com)

How to change Apache Tomcat web server port number

Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.

Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)

    <Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Going to give the port number to 9090

     <Connector port="9090" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Save the file and restart the server. Now the tomcat will listen at port 9090

How to change Java version used by TOMCAT?

On Linux, Tomcat7 has a configuration file located at:

/etc/sysconfig/tomcat7

... which is where server specific configurations should be made. You can set the JAVA_HOME env variable here w/o needing to create a profile.d/ script.

This worked for me.

getting JRE system library unbound error in build path

I too faced the same issue. I followed the following steps to resolve my issue -

  • Right click on your project -> Properties
  • Select Java Build Path in the left menu
  • Select Libraries tab
  • Under the module path, select the troublesome JRE entry
  • Click on Edit button
  • Select Workspace default JRE.
  • Click on Finish button

If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.

Script parameters in Bash

The arguments that you provide to a bashscript will appear in the variables $1 and $2 and $3 where the number refers to the argument. $0 is the command itself.

The arguments are seperated by spaces, so if you would provide the -from and -to in the command, they will end up in these variables too, so for this:

./ocrscript.sh -from /home/kristoffer/test.png -to /home/kristoffer/test.txt

You'll get:

$0    # ocrscript.sh
$1    # -from
$2    # /home/kristoffer/test.png
$3    # -to
$4    # /home/kristoffer/test.txt

It might be easier to omit the -from and the -to, like:

ocrscript.sh /home/kristoffer/test.png /home/kristoffer/test.txt

Then you'll have:

$1    # /home/kristoffer/test.png
$2    # /home/kristoffer/test.txt

The downside is that you'll have to supply it in the right order. There are libraries that can make it easier to parse named arguments on the command line, but usually for simple shell scripts you should just use the easy way, if it's no problem.

Then you can do:

/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1

The double quotes around the $1 and the $2 are not always necessary but are adviced, because some strings won't work if you don't put them between double quotes.

How to exit from ForEach-Object in PowerShell

I found this question while looking for a way to have fine grained flow control to break from a specific block of code. The solution I settled on wasn't mentioned...

Using labels with the break keyword

From: about_break

A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script.

Here's a simple example

:myLabel for($i = 1; $i -le 2; $i++) {
        Write-Host "Iteration: $i"
        break myLabel
}

Write-Host "After for loop"

# Results:
# Iteration: 1
# After for loop

And then a more complicated example that shows the results with nested labels and breaking each one.

:outerLabel for($outer = 1; $outer -le 2; $outer++) {

    :innerLabel for($inner = 1; $inner -le 2; $inner++) {
        Write-Host "Outer: $outer / Inner: $inner"
        #break innerLabel
        #break outerLabel
    }

    Write-Host "After Inner Loop"
}

Write-Host "After Outer Loop"

# Both breaks commented out
# Outer: 1 / Inner: 1
# Outer: 1 / Inner: 2
# After Inner Loop
# Outer: 2 / Inner: 1
# Outer: 2 / Inner: 2
# After Inner Loop
# After Outer Loop

# break innerLabel Results
# Outer: 1 / Inner: 1
# After Inner Loop
# Outer: 2 / Inner: 1
# After Inner Loop
# After Outer Loop

# break outerLabel Results
# Outer: 1 / Inner: 1
# After Outer Loop

You can also adapt it to work in other situations by wrapping blocks of code in loops that will only execute once.

:myLabel do {
    1..2 | % {

        Write-Host "Iteration: $_"
        break myLabel

    }
} while ($false)

Write-Host "After do while loop"

# Results:
# Iteration: 1
# After do while loop

Select unique or distinct values from a list in UNIX shell script

Pipe them through sort and uniq. This removes all duplicates.

uniq -d gives only the duplicates, uniq -u gives only the unique ones (strips duplicates).

How do you get a string from a MemoryStream?

Only use method Convert.ToBase64String

Convert.ToBase64String(inputStream.ToArray());

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Could not create work tree dir 'example.com'.: Permission denied

Tested On Ubuntu 20, sudo chown -R $USER:$USER /var/www

How to select the Date Picker In Selenium WebDriver

try to SendKeys instead of picking the date

driver.FindElement(yourBy).SendKeys(yourDateTime.ToString("ddd, dd.MM.yyyy",CultureInfo.CreateSpecificCulture("en-US")));

If it does not work, try to send native 'tab'

element.SendKeys(OpenQA.Selenium.Keys.Tab);

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

Scroll part of content in fixed position container

I changed scrollable div to be with absolute position, and everything works for me

div.sidebar {
    overflow: hidden;
    background-color: green;
    padding: 5px;
    position: fixed;
    right: 20px;
    width: 40%;
    top: 30px;
    padding: 20px;
    bottom: 30%;
}
div#fixed {
    background: #76a7dc;
    color: #fff;
    height: 30px;
}

div#scrollable {
    overflow-y: scroll;
    background: lightblue;

    position: absolute;
    top:55px; 
    left:20px;
    right:20px;
    bottom:10px;
}

DEMO with two scrollable divs

How to check if a String is numeric in Java

Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:

NumberUtils.isNumber(myStringValue);

Edit:

Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.

NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

ShowAllData method of Worksheet class failed

I have just experienced the same problem. After some trial-and-error I discovered that if the selection was to the right of my filter area AND the number of shown records was zero, ShowAllData would fail.

A little more context is probably relevant. I have a number of sheets, each with a filter. I would like to set up some standard filters on all sheets, therefore I use some VBA like this

Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"

This code will adjust the filter on the column with heading "In Selected SLA", and leave all other filters unchanged. This has the unfortunate side effect that I can create a filter that shows zero records. This is not possible using the UI alone.

To avoid that situation, I would like to reset all filters before I apply the filtering above. My reset code looked like this

Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

Note how I did not move the selected cell. If the selection was to the right, it would not remove filters, thus letting the filter code build a zero-row filter. The second time the code is run (on a zero-row filter) ShowAllData will fail.

The workaround is simple: Move the selection inside the filter columns before calling ShowAllData

Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

This was on Excel version 14.0.7128.5000 (32-bit) = Office 2010

ggplot combining two plots from different data.frames

You can take this trick to use only qplot. Use inner variable $mapping. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.

cpu_metric2 <- qplot(y=Y2,x=X1) 

cpu_metric1 <- qplot(y=Y1, 
                    x=X1, 
                    xlab="Time", ylab="%") 

combined_cpu_plot <- cpu_metric1 + 
  geom_line() +
  geom_point(mapping=cpu_metric2$mapping)+
  geom_line(mapping=cpu_metric2$mapping)

Get absolute path of initially run script

try this on your script

echo getcwd() . "\n";

How to get out of while loop in java with Scanner method "hasNext" as condition?

When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:

String s1 = sc.next();
if (s1.equals("exit")) {
    break;
}

Break will get you out of the loop.

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Create dataframe from a matrix

Using dplyr and tidyr:

library(dplyr)
library(tidyr)

df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
  gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
  select(name, time, val)         # reorder the columns

df
# A tibble: 6 x 3
   name  time   val
  <chr> <dbl> <dbl>
1   C_0   0.0   0.1
2   C_0   0.5   0.2
3   C_0   1.0   0.3
4   C_1   0.0   0.3
5   C_1   0.5   0.4
6   C_1   1.0   0.5

"Operation must use an updateable query" error in MS Access

UPDATE [GS] INNER JOIN [Views] ON 
([Views].Hostname = [GS].Hostname) 
AND ([GS].APPID = [Views].APPID) <------------ This is the difference 
SET 
    [GS].APPID = [Views].APPID, 
    [GS].[Name] = [Views].[Name], 
    [GS].Hostname = [Views].Hostname, 
    [GS].[Date] = [Views].[Date], 
    [GS].[Unit] = [Views].[Unit], 
    [GS].[Owner] = [Views].[Owner];

Invoke native date picker from web-app on iOS/Android

You could use Trigger.io's UI module to use the native Android date / time picker with a regular HTML5 input. Doing that does require using the overall framework though (so won't work as a regular mobile web page).

You can see before and after screenshots in this blog post: date time picker

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

How to make a div have a fixed size?

Try the following css:

#innerbox
{
   width:250px; /* or whatever width you want. */
   max-width:250px; /* or whatever width you want. */
   display: inline-block;
}

This makes the div take as little space as possible, and its width is defined by the css.

// Expanded answer

To make the buttons fixed widths do the following :

#innerbox input
{
   width:150px; /* or whatever width you want. */
   max-width:150px; /* or whatever width you want. */
}

However, you should be aware that as the size of the text changes, so does the space needed to display it. As such, it's natural that the containers need to expand. You should perhaps review what you are trying to do; and maybe have some predefined classes that you alter on the fly using javascript to ensure the content placement is perfect.

How do I make an auto increment integer field in Django?

What I needed: A document number with a fixed number of integers that would also act like an AutoField.

My searches took me all over incl. this page.

Finally I did something like this:

I created a table with a DocuNumber field as an IntegerField with foll. attributes:

  • max_length=6
  • primary_key=True
  • unique=True
  • default=100000

The max_length value anything as required (and thus the corresponding default= value).

A warning is issued while creating the said model, which I could ignore.

Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.

Afterwards changed the model key field as:

  • Changed the field type as: AutoField
  • Got rid of the max_length And defaultattributes
  • Retained the primary_key = True attribute

The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.

So far so good.

Is Tomcat running?

Here are my two cents.

I have multiple tomcat instances running on different ports for my cluster setup. I use the following command to check each processes running on different ports.

/sbin/fuser 8080/tcp

Replace the port number as per your need.

And to kill the process use -k in the above command.

  • This is much faster than the ps -ef way or any other commands where you call a command and call another grep on top of it.
  • Works well with multiple installations of tomcat ,Or any other server that uses a port as a matter of fact running on the same server.

The equivalent command on BSD operating systems is fstat

JOptionPane - input dialog box program

After that you have to parse the results. Suppose results are in integers, then

int testint1 = Integer.parse(test1);

Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.

What is the difference between Bootstrap .container and .container-fluid classes?

Quick version: .container has one fixed width for each screen size in bootstrap (xs,sm,md,lg); .container-fluid expands to fill the available width.


The difference between container and container-fluid comes from these lines of CSS:

@media (min-width: 568px) {
  .container {
    width: 550px;
  }
}
@media (min-width: 992px) {
  .container {
    width: 970px;
  }
}
@media (min-width: 1200px) {
  .container {
    width: 1170px;
  }
}

Depending on the width of the viewport that the webpage is being viewed on, the container class gives its div a specific fixed width. These lines don't exist in any form for container-fluid, so its width changes every time the viewport width changes.

So for example, say your browser window is 1000px wide. As it's greater than the min-width of 992px, your .container element will have a width of 970px. You then slowly widen your browser window. The width of your .container won't change until you get to 1200px, at which it will jump to 1170px wide and stay that way for any larger browser widths.

Your .container-fluid element, on the other hand, will constantly resize as you make even the smallest changes to your browser width.

Get filename and path from URI from mediastore

Here you get the name of the file

String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
                    Uri uri = data.getData();
                    String fileName = null;
                    ContentResolver cr = getActivity().getApplicationContext().getContentResolver();

                    Cursor metaCursor = cr.query(uri,
                            projection, null, null, null);
                    if (metaCursor != null) {
                        try {
                            if (metaCursor.moveToFirst()) {
                                fileName = metaCursor.getString(0);
                            }
                        } finally {
                            metaCursor.close();
                        }
                    }

How to input a regex in string.replace?

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

Node.js – events js 72 throw er unhandled 'error' event

I had the same problem. I closed terminal and restarted node. This worked for me.

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

Where Sticky Notes are saved in Windows 10 1607

Use this document to transfer Sticky Notes data file StickyNotes.snt to the new format

http://www.winhelponline.com/blog/recover-backup-sticky-notes-data-file-windows-10/

Restore:

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

  • Close Sticky Notes
  • Create a new folder named Legacy
  • Under the Legacy folder, copy your existing StickyNotes.snt, and rename it to ThresholdNotes.snt
  • Start the Sticky Notes app. It reads the legacy .snt file and transfers the content to the database file automatically.

Backup

just backup following file.

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Since SQL Server Version 2012 you can use:

SELECT format(getdate(),'yyyyMMddHHmmssffff')

jQuery: how do I animate a div rotation?

Based on Peter Ajtai answer, here is a small jquery plugin that may help others. I didn't test on Opera and IE9 but is should work on these browsers too.

$.fn.rotate = function(until, step, initial, elt) {
    var _until = (!until)?360:until;
    var _step = (!step)?1:step;
    var _initial = (!initial)?0:initial;
    var _elt = (!elt)?$(this):elt;

    var deg = _initial + _step;

    var browser_prefixes = ['-webkit', '-moz', '-o', '-ms'];
    for (var i=0, l=browser_prefixes.length; i<l; i++) {
      var pfx = browser_prefixes[i]; 
      _elt.css(pfx+'-transform', 'rotate('+deg+'deg)');
    }

    if (deg < _until) {
      setTimeout(function() {
          $(this).rotate(_until, _step, deg, _elt); //recursive call
      }, 5);
    }
};

$('.my-elt').rotate()

Check if registry key exists using VBScript

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

Android Camera : data intent returns null

The following code works for me:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);

And here is the result:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{ 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(resultCode == RESULT_OK)
    {
        Uri selectedImage = imageReturnedIntent.getData();
        ImageView photo = (ImageView) findViewById(R.id.add_contact_label_photo);
        Bitmap mBitmap = null;
        try
        {
            mBitmap = Media.getBitmap(this.getContentResolver(), selectedImage);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Switch case with fallthrough?

  • Do not use () behind function names in bash unless you like to define them.
  • use [23] in case to match 2 or 3
  • static string cases should be enclosed by '' instead of ""

If enclosed in "", the interpreter (needlessly) tries to expand possible variables in the value before matching.

case "$C" in
'1')
    do_this
    ;;
[23])
    do_what_you_are_supposed_to_do
    ;;
*)
    do_nothing
    ;;
esac

For case insensitive matching, you can use character classes (like [23]):

case "$C" in

# will match C='Abra' and C='abra'
[Aa]'bra')
    do_mysterious_things
    ;;

# will match all letter cases at any char like `abra`, `ABRA` or `AbRa`
[Aa][Bb][Rr][Aa])
    do_wild_mysterious_things
    ;;

esac

But abra didn't hit anytime because it will be matched by the first case.

If needed, you can omit ;; in the first case to continue testing for matches in following cases too. (;; jumps to esac)

Why is January month 0 in Java Calendar?

Because doing math with months is much easier.

1 month after December is January, but to figure this out normally you would have to take the month number and do math

12 + 1 = 13 // What month is 13?

I know! I can fix this quickly by using a modulus of 12.

(12 + 1) % 12 = 1

This works just fine for 11 months until November...

(11 + 1) % 12 = 0 // What month is 0?

You can make all of this work again by subtracting 1 before you add the month, then do your modulus and finally add 1 back again... aka work around an underlying problem.

((11 - 1 + 1) % 12) + 1 = 12 // Lots of magical numbers!

Now let's think about the problem with months 0 - 11.

(0 + 1) % 12 = 1 // February
(1 + 1) % 12 = 2 // March
(2 + 1) % 12 = 3 // April
(3 + 1) % 12 = 4 // May
(4 + 1) % 12 = 5 // June
(5 + 1) % 12 = 6 // July
(6 + 1) % 12 = 7 // August
(7 + 1) % 12 = 8 // September
(8 + 1) % 12 = 9 // October
(9 + 1) % 12 = 10 // November
(10 + 1) % 12 = 11 // December
(11 + 1) % 12 = 0 // January

All of the months work the same and a work around isn't necessary.

Create a date time with month and day only, no year

Anyway you need 'Year'.

In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.

You can create a custom combobox using this: Customizable ComboBox Drop-Down.

1- In VS create a user control.

2- See the code in the link above for impelemnting that control.

3- Create another user control and place in it 31 button or label and above them place a label to show months.

4- Place the control in step 3 in your custom combobox.

5- Place the control in setp 4 in step 1.

You now have a control with only days and months. You can use any year that you have in your database or ....

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

concatenate char array in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

Differences between JDK and Java SDK

My initial guess would be that the Java SDK is for building the JVM while the JDK is for building apps for the JVM.

Edit: Although this looks to be incorrect at the moment. Sun are in the process of opensourcing the JVM (perhaps they've even finished, now) so I wouldn't be too surprised if my answer does become correct... But at the moment, the SDK and JDK are the same thing.

Waiting for background processes to finish before exiting script

GNU parallel and xargs

These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:

seq 10 | xargs -P4 -I'{}' echo '{}'

or:

seq 10 | parallel -j4  echo '{}'

See also: how to write a process-pool bash shell

Responsive font size in CSS

I've been playing around with ways to overcome this issue, and believe I have found a solution:

If you can write your application for Internet Explorer 9 (and later) and all other modern browsers that support CSS calc(), rem units, and vmin units. You can use this to achieve scalable text without media queries:

body {
  font-size: calc(0.75em + 1vmin);
}

Here it is in action: http://codepen.io/csuwldcat/pen/qOqVNO

Could not find method compile() for arguments Gradle

In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...

If you experienced this issue in a git project, do git status and remove the unrevisioned files. (For me elasticsearch had a problem with plugins/analysis-icu).

Gradle Version : 5.1.1

How to tell whether a point is to the right or left side of a line

The vector (y1 - y2, x2 - x1) is perpendicular to the line, and always pointing right (or always pointing left, if you plane orientation is different from mine).

You can then compute the dot product of that vector and (x3 - x1, y3 - y1) to determine if the point lies on the same side of the line as the perpendicular vector (dot product > 0) or not.

Floating elements within a div, floats outside of div. Why?

Reason

The problem is that floating elements are out-of-flow:

An element is called out of flow if it is floated, absolutely positioned, or is the root element.

Therefore, they don't impact surrounding elements as an in-flow element would.

This is explained in 9.5 Floats:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

enter image description here

_x000D_
_x000D_
html {_x000D_
  width: 550px;_x000D_
  border: 1px solid;_x000D_
}_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
div:after {_x000D_
  font-size: 200%;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  text-align: center;_x000D_
}_x000D_
.block-sibling {_x000D_
  border: 3px solid green;_x000D_
}_x000D_
.block-sibling:after {_x000D_
  content: 'Block sibling';_x000D_
  color: green;_x000D_
}_x000D_
.float {_x000D_
  float: left;_x000D_
  border: 3px solid red;_x000D_
  height: 90px;_x000D_
  width: 150px;_x000D_
  z-index: 1;_x000D_
}_x000D_
.float:after {_x000D_
  content: 'Float';_x000D_
  color: red;_x000D_
}
_x000D_
<div class="float"></div>_x000D_
<div class="block-sibling">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor._x000D_
</div>
_x000D_
_x000D_
_x000D_

This is also specified in 10.6 Calculating heights and margins. For "normal" blocks,

Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored […])

enter image description here

_x000D_
_x000D_
html {_x000D_
  width: 550px;_x000D_
  border: 1px solid;_x000D_
}_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
div:after {_x000D_
  font-size: 200%;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
  border: 3px solid blue;_x000D_
}_x000D_
.block-parent:after {_x000D_
  content: 'Block parent';_x000D_
  color: blue;_x000D_
}_x000D_
.float {_x000D_
  float: left;_x000D_
  border: 3px solid red;_x000D_
  height: 130px;_x000D_
  width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
  content: 'Float';_x000D_
  color: red;_x000D_
}
_x000D_
<div class="block-parent">_x000D_
  <div class="float"></div>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
</div>
_x000D_
_x000D_
_x000D_

Hacky solution: clearance

A way to solve the problem is forcing some in-flow element to be placed below all floats. Then, the height of the parent will grow to wrap that element (and thus the floats too).

This can be achieved using the clear property:

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.

enter image description here

_x000D_
_x000D_
html {_x000D_
  width: 550px;_x000D_
  border: 1px solid;_x000D_
}_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
div:after {_x000D_
  font-size: 200%;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
  border: 3px solid blue;_x000D_
}_x000D_
.block-parent:after {_x000D_
  content: 'Block parent';_x000D_
  color: blue;_x000D_
}_x000D_
.float {_x000D_
  float: left;_x000D_
  border: 3px solid red;_x000D_
  height: 84px;_x000D_
  width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
  content: 'Float';_x000D_
  color: red;_x000D_
}_x000D_
.clear {_x000D_
  clear: both;_x000D_
  text-align: center;_x000D_
  height: 37px;_x000D_
  border: 3px dashed pink;_x000D_
}_x000D_
.clear:after {_x000D_
  position: static;_x000D_
  content: 'Block sibling with clearance';_x000D_
  color: pink;_x000D_
}
_x000D_
<div class="block-parent">_x000D_
  <div class="float"></div>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra._x000D_
  <div class="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So a solution is adding an empty element with clear: both as the last sibling of the floats

<div style="clear: both"></div>

However, that is not semantic. So better generate a pseudo-element at the end of the parent:

.clearfix::after {
  clear: both;
  display: block;
}

There are multiple variants of this approach, e.g. using the deprecated single colon syntax :after to support old browsers, or using other block-level displays like display: table.

Solution: BFC roots

There is an exception to the problematic behavior defined at the beginning: if a block element establishes a Block Formatting Context (is a BFC root), then it will also wrap its floating contents.

According to 10.6.7 'Auto' heights for block formatting context roots,

If the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges.

enter image description here

_x000D_
_x000D_
html {_x000D_
  width: 550px;_x000D_
  border: 1px solid;_x000D_
}_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
div:after {_x000D_
  font-size: 200%;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
  border: 3px solid blue;_x000D_
}_x000D_
.block-parent.bfc-root:after {_x000D_
  content: 'BFC parent';_x000D_
  color: blue;_x000D_
}_x000D_
.float {_x000D_
  float: left;_x000D_
  border: 3px solid red;_x000D_
  height: 127px;_x000D_
  width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
  content: 'Float';_x000D_
  color: red;_x000D_
}_x000D_
.bfc-root {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="block-parent bfc-root">_x000D_
  <div class="float"></div>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
</div>
_x000D_
_x000D_
_x000D_

Additionally, as explained 9.5 Floats, BFC roots are also useful because of the following:

The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context […] must not overlap the margin box of any floats in the same block formatting context as the element itself.

enter image description here

_x000D_
_x000D_
html {_x000D_
  width: 550px;_x000D_
  border: 1px solid;_x000D_
}_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
div:after {_x000D_
  font-size: 200%;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  text-align: center;_x000D_
}_x000D_
.block-sibling {_x000D_
  border: 3px solid green;_x000D_
}_x000D_
.block-sibling.bfc-root:after {_x000D_
  content: 'BFC sibling';_x000D_
  color: green;_x000D_
}_x000D_
.float {_x000D_
  float: left;_x000D_
  border: 3px solid red;_x000D_
  height: 90px;_x000D_
  width: 150px;_x000D_
  z-index: 1;_x000D_
}_x000D_
.float:after {_x000D_
  content: 'Float';_x000D_
  color: red;_x000D_
}_x000D_
.bfc-root {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="float"></div>_x000D_
<div class="block-sibling bfc-root">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur._x000D_
</div>
_x000D_
_x000D_
_x000D_

A block formatting context is established by

  • Block boxes with overflow other than visible, e.g. hidden

    .bfc-root {
      overflow: hidden;
      /* display: block; */
    }
    
  • Block containers that are not block boxes: when display is set to inline-block, table-cell or table-caption.

    .bfc-root {
      display: inline-block;
    }
    
  • Floating elements: when float is set to left or right.

    .bfc-root {
      float: left;
    }
    
  • Absolutely positioned elements: when position is set to absolute or fixed.

    .bfc-root {
      position: absolute;
    }
    

Note those may have undesired collateral effects, like clipping overflowing content, calculating auto widths with the shrink-to-fit algorithm, or becoming out-of-flow. So the problem is that it's not possible to have an in-flow block-level element with visible overflow that establishes a BFC.

Display L3 addresses these issues:

Created the flow and flow-root inner display types to better express flow layout display types and to create an explicit switch for making an element a BFC root. (This should eliminate the need for hacks like ::after { clear: both; } and overflow: hidden […])

Sadly, there is no browser support yet. Eventually we may be able to use

.bfc-root {
  display: flow-root;
}

DisplayName attribute from Resources?

How about writing a custom attribute:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}

javax.persistence.NoResultException: No entity found for query

Another option is to use uniqueResultOptional() method, which gives you Optional in result:

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());

Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();

Wireshark localhost traffic capture

For Windows,

You cannot capture packets for Local Loopback in Wireshark however, you can use a very tiny but useful program called RawCap;

RawCap

Run RawCap on command prompt and select the Loopback Pseudo-Interface (127.0.0.1) then just write the name of the packet capture file (.pcap)

A simple demo is as below;

C:\Users\Levent\Desktop\rawcap>rawcap
Interfaces:
 0.     169.254.125.51  Local Area Connection* 12       Wireless80211
 1.     192.168.2.254   Wi-Fi   Wireless80211
 2.     169.254.214.165 Ethernet        Ethernet
 3.     192.168.56.1    VirtualBox Host-Only Network    Ethernet
 4.     127.0.0.1       Loopback Pseudo-Interface 1     Loopback
Select interface to sniff [default '0']: 4
Output path or filename [default 'dumpfile.pcap']: test.pcap
Sniffing IP : 127.0.0.1
File        : test.pcap
Packets     : 48^C

How to update Ruby with Homebrew?

I would use ruby-build with rbenv. The following lines install Ruby 3.0.0 and set it as your default Ruby version:

$ brew update
$ brew install ruby-build
$ brew install rbenv

$ rbenv install 3.0.0
$ rbenv global 3.0.0

Using Page_Load and Page_PreRender in ASP.Net

The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.

Class is inaccessible due to its protection level

I'm guessing public Method AddMethod(string aName) is defined on a public interface that FBlock implements. Consumers of that interface are not guaranteed to have access to Method.

Python Pandas: Get index of rows which column matches certain value

Can be done using numpy where() function:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

Though you don't always need index for a match, but incase if you need:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

How to convert a list into data table

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.

Laravel 5.4 redirection to custom url after login

You should set $redirectTo value to route that you want redirect

$this->redirectTo = route('dashboard');

inside AuthController constructor.

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    $this->redirectTo = route('dashboard');
}

clear data inside text file in c++

As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.

ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append

The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.

How to adjust text font size to fit textview

I've been working on improving the excellent solution from speedplane, and came up with this. It manages the height, including setting the margin such that the text should be centered correctly vertically.

This uses the same function to get the width, as it seems to work the best, but it uses a different function to get the height, as the height isn't provided anywhere. There are some corrections that need to be made, but I figured out a way to do that, while looking pleasing to the eye.

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialize();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    private void initialize() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());

        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth,int textHeight) 
    { 
        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom();
        float hi = Math.min(targetHeight,100);
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        Rect bounds = new Rect();

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            mTestPaint.setTextSize(size);
            mTestPaint.getTextBounds(text, 0, text.length(), bounds);
            if((mTestPaint.measureText(text)) >= targetWidth || (1+(2*(size+(float)bounds.top)-bounds.bottom)) >=targetHeight) 
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX,(float) lo);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth,height);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth(),this.getHeight());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {

        if (w != oldw) {
            refitText(this.getText().toString(), w,h);
        }
    }

    //Attributes
    private Paint mTestPaint;
}

How to deal with page breaks when printing a large HTML table

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tbody>
        <tr>
            <td>x</td>
        </tr>
        <tr>
            <td>x</td>
        </tr>
        <!-- 500 more rows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>

Searching a string in eclipse workspace

In your Eclipse editor screen, try Control + Shift + R buttons.

Crystal Reports 13 And Asp.Net 3.5

I have same problem. I solved install this setup. (I use vs 2015 (4.6))

Mobile website "WhatsApp" button to send message to a specific number

Format to send a WhatsApp message to a specific number (updated Nov 2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

where

whatsappphonenumber is a full phone number in international format

urlencodedtext is the URL-encoded pre-filled message.


Example:

  1. Create a link with a pre-filled message that will automatically appear in the text field of a chat, to be sent to a specific number

    Send I am interested in your car for sale to +001-(555)1234567

    https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20car%20for%20sale

    Note :

    Use: https://wa.me/15551234567

    Don't use: https://wa.me/+001-(555)1234567

  2. Create a link with just a pre-filled message that will automatically appear in the text field of a chat, number will be chosen by the user

    Send I am enquiring about the apartment listing

    https://wa.me/?text=I%20am%20enquiring%20about%20the%20apartment%20listing

    After clicking on the link, user will be shown a list of contacts they can send the pre-filled message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

--

P.S : Older format (before updation) for reference

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

Count the number of items in my array list

The number of itemIds in your list will be the same as the number of elements in your list:

int itemCount = list.size();

However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.

Set<String> itemIds = new HashSet<String>();

//...
itemId = p.getItemId();
itemIds.add(itemId);

//... later ...
int uniqueItemIdCount = itemIds.size();

Draw an X in CSS

You can use the CSS property "content":

div {
    height: 100px;
    width: 100px;
    background-color: #FA6900;
    border-radius: 5px;
}

div:after {
    content: "X";
    font-size: 2em; 
    color: #FFF;
}

Like this: http://jsfiddle.net/HKtFV/

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

How to update large table with millions of rows in SQL Server?

WHILE EXISTS (SELECT * FROM TableName WHERE Value <> 'abc1' AND Parameter1 = 'abc' AND Parameter2 = 123)
BEGIN
UPDATE TOP (1000) TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 AND Value <> 'abc1'
END

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

.NET / C# - Convert char[] to string

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Modern rewrite of @johann-echavarria's answer:

_x000D_
_x000D_
console.log(_x000D_
    Array(256)_x000D_
        .fill()_x000D_
        .map((ignore, i) => String.fromCharCode(i))_x000D_
        .filter(_x000D_
            (char) =>_x000D_
                encodeURI(char) !== encodeURIComponent(char)_x000D_
                    ? {_x000D_
                          character: char,_x000D_
                          encodeURI: encodeURI(char),_x000D_
                          encodeURIComponent: encodeURIComponent(char)_x000D_
                      }_x000D_
                    : false_x000D_
        )_x000D_
)
_x000D_
_x000D_
_x000D_

Or if you can use a table, replace console.log with console.table (for the prettier output).

How can I use the python HTMLParser library to extract data from a specific div tag?

This works perfectly:

print (soup.find('the tag').text)

How to call Stored Procedure in Entity Framework 6 (Code-First)?

object[] xparams = {
            new SqlParameter("@ParametterWithNummvalue", DBNull.Value),
            new SqlParameter("@In_Parameter", "Value"),
            new SqlParameter("@Out_Parameter", SqlDbType.Int) {Direction = ParameterDirection.Output}};

        YourDbContext.Database.ExecuteSqlCommand("exec StoreProcedure_Name @ParametterWithNummvalue, @In_Parameter, @Out_Parameter", xparams);
        var ReturnValue = ((SqlParameter)params[2]).Value;  

WindowsError: [Error 126] The specified module could not be found

If you are using GCC to compile it for Windows, it's possible that the error is because dependent libraries can't be found.

Using the -static flag if linking with GCC might fix that.

How to send cookies in a post request with the Python Requests library?

Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:

import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  ...
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

Swift - iOS - Dates and times in different format

new Date(year,month,day,0,0,0,0) is local time (as input) new Date(year,month,day) is UTC

I was using a function to attain YYYY-MM-DD format to be compatible on iOS web, but that is also UTC when used in comparisons (not chained by getFullYear or similar) I've found it is best to use only the above with strong (hours,minutes,seconds,milliseconds) building a calendar, calculating with a Date objects and local references

export const zeroPad = (num) => {
  var res = "0";
  if (String(num).length === 1) {
    res = `0${num}`;
  } else {
    res = num;
  }
  return res;
};

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

PHP - define constant inside a class

This is a pretty old question, but perhaps this answer can still help someone else.

You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

class Foo {

    // This is a private constant
    final public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

To get nearly exactly what Alex was looking for the following code can be used:

final class Constants {

    public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

class Foo {

    static public app()
    {
        return new Constants();
    }
}

The emulated constant value would be accessible like this:

Foo::app()->MYCONSTANT();

CSS animation delay in repeating

I would rather write a little JavaScript than make the CSS less manageable.

First, only apply the CSS animation on a data attribute change:

.progbar[data-animation="barshine"] {
    animation: barshine 1s linear;
}

Then add javascript to toggle the animation at half the delay amount.

var progbar = document.querySelector('.progbar');
var on = false;

setInterval(function () {
    progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
    on = !on;
}, 3000);

Or if you don't want the animation to run when the tab is hidden:

var progbar = document.querySelector('.progbar');
var on = false;

var update = function () {
    progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
    on = !on;
    setTimer();
};

var setTimer = function () {
    setTimeout(function () {
        requestAnimationFrame(update);
    }, 3000);
};

setTimer();

Trying Gradle build - "Task 'build' not found in root project"

run

gradle clean 

then try

gradle build 

it worked for me

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

How do I remove the non-numeric character from a string in java?

Simple way without using Regex:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

Python: download a file from an FTP server

Try using the wget library for python. You can find the documentation for it here.

import wget
link = 'ftp://example.com/foo.txt'
wget.download(link)

Deleting queues in RabbitMQ

I've generalized Piotr Stapp's JavaScript/jQuery method a bit further, encapsulating it into a function and generalizing it a bit.

This function uses the RabbitMQ HTTP API to query available queues in a given vhost, and then delete them based on an optional queuePrefix:

function deleteQueues(vhost, queuePrefix) {
    if (vhost === '/') vhost = '%2F';  // html encode forward slashes
    $.ajax({
        url: '/api/queues/'+vhost, 
        success: function(result) {
            $.each(result, function(i, queue) {
                if (queuePrefix && !queue.name.startsWith(queuePrefix)) return true;
                $.ajax({
                    url: '/api/queues/'+vhost+'/'+queue.name, 
                    type: 'DELETE', 
                    success: function(result) { console.log('deleted '+ queue.name)}
                });
            });
        }
    });
};

Once you paste this function in your browser's JavaScript console while on your RabbitMQ management page, you can use it like this:

Delete all queues in '/' vhost

deleteQueues('/');

Delete all queues in '/' vhost beginning with 'test'

deleteQueues('/', 'test');

Delete all queues in 'dev' vhost beginning with 'foo'

deleteQueues('dev', 'foo');

Please use this at your own risk!

How to validate date with format "mm/dd/yyyy" in JavaScript?

Moment is really a good one to resolve it. I don't see reason to add complexity just to check date... take a look on moment : http://momentjs.com/

HTML :

<input class="form-control" id="date" name="date" onchange="isValidDate(this);" placeholder="DD/MM/YYYY" type="text" value="">

Script :

 function isValidDate(dateString)  {
    var dateToValidate = dateString.value
    var isValid = moment(dateToValidate, 'MM/DD/YYYY',true).isValid()
    if (isValid) {
        dateString.style.backgroundColor = '#FFFFFF';
    } else {
        dateString.style.backgroundColor = '#fba';
    }   
};

HTTP test server accepting GET/POST requests

I have created an open-source hackable local testing server that you can get running in minutes. You can create new API's, define your own response and hack it in any ways you wish to.

Github Link : https://github.com/prabodhprakash/localTestingServer

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

Difference between static class and singleton pattern?

To expand on Jon Skeet's Answer

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.

How can I get the last character in a string?

Use the charAt method. This function accepts one argument: The index of the character.

var lastCHar = myString.charAt(myString.length-1);

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

What are the most-used vim commands/keypresses?

Go to Efficient Editing with vim and learn what you need to get started. Not everything on that page is essential starting off, so cherry pick what you want.

From there, use vim for everything. "hjkl", "y", and "p" will get you a long way, even if it's not the most efficient way. When you come up against a task for which you don't know the magic key to do it efficiently (or at all), and you find yourself doing it more than a few times, go look it up. Little by little it will become second nature.

I found vim daunting many moons ago (back when it didn't have the "m" on the end), but it only took about a week of steady use to get efficient. I still find it the quickest editor in which to get stuff done.

get all characters to right of last dash

YourString.Substring(YourString.LastIndexOf("-"));

Multiple try codes in one block

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

Extend contigency table with proportions (percentages)

I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.

set.seed(1234)

total_bill <- rnorm(50, 25, 3)
tip <- 0.15 * total_bill + rnorm(50, 0, 1)
sex <- rbinom(50, 1, 0.5)
smoker <- rbinom(50, 1, 0.3)
day <- ceiling(runif(50, 0,7))
time <- ceiling(runif(50, 0,3))
size <- 1 + rpois(50, 2)
my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
my.data

my.table <- table(my.data$smoker)

my.prop <- prop.table(my.table)

cbind(my.table, my.prop)

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

Bootstrap 4 Dropdown Menu not working?

Edit: In case anyone else is having this problem, I believe the solution for OP was that he had not imported popper.js.

Check that jQuery and all the relevant Bootstrap components are there. Also check the console and make sure there are no errors.

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Features</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Pricing</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<-- Always remember to call the above files first before calling the bootstrap.min.js file -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to put a tooltip on a user-defined function

I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.

Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin is picked up by the addin framework and has AutoOpen() and AutoClose() run when you open/close the add in. So you just need this:

namespace MyNameSpace {
    public class Intellisense : IExcelAddIn {
        public void AutoClose() {
        }
        public void AutoOpen() {
            IntelliSenseServer.Register();
        }
    }
}

and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:

[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
    [ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")] 
    double v1,
    [ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]     
    double v2)
{
    return v1 + v2;
}

which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.

enter image description here enter image description here

There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.

Plot a horizontal line using matplotlib

If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 21, 200)
y = np.exp(-x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')

plt.show()

The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

enter image description here

How to disable scrolling in UITableView table when the content fits on the screen

You can edit this in your storyboard (if you are using one). Under the table view there is a checkbox that says "Scrolling Enabled". Uncheck it and you're done.

Spring JPA selecting specific columns

You can use JPQL:

TypedQuery <Object[]> query = em.createQuery(
  "SELECT p.projectId, p.projectName FROM projects AS p", Object[].class);

List<Object[]> results = query.getResultList();

or you can use native sql query.

Query query = em.createNativeQuery("sql statement");
List<Object[]> results = query.getResultList();

How to convert buffered image to image and vice-versa?

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.

Firefox setting to enable cross domain Ajax request

For modern browsers, you may try the following approach:

https://developer.mozilla.org/en/HTTP_access_control

In short, you need to add the following into the SERVER response header (the following allows access from foo.example):

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

Note that the X-PINGOTHER is the custom header that is inserted by JavaScript, and should differ from site to site.

If you want any site access your server in Ajax, use * instead.


Edit:

When I first answered the question by 2009, I actually hit the same problem, and I worked around it using the server side config.

There was no plugin on FF or Chrome by then.

However, now we do have alternatives using the browser side plugin, please check the answer of tsds

How to truncate string using SQL server

You can also use the Cast() operation :

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name

Display text from .txt file in batch file

Just set the time and date to variables if it will be something that will be in a loop then

:top
set T=%time%
set D=%Date%

echo %T%>>log.txt
echo %d%>>log.txt
echo time:%T%
echo date:%D%
pause
goto top

I suggest making it nice and clean by putting:

@echo off

in front of every thing it get rid of the rubbish C:/users/example/...

and putting

cls

after the :top to clear the screen before it add the new date and time to the display

SSH to Vagrant box in Windows?

Another solution here but only for the virtual box of windows 10 to test explorer. ssh user: IEUser ssh pass:Passw0rd!

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Converting List<Integer> to List<String>

Instead of using String.valueOf I'd use .toString(); it avoids some of the auto boxing described by @johnathan.holland

The javadoc says that valueOf returns the same thing as Integer.toString().

List<Integer> oldList = ...
List<String> newList = new ArrayList<String>(oldList.size());

for (Integer myInt : oldList) { 
  newList.add(myInt.toString()); 
}

Check if a string contains an element from a list (of strings)

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

Undefined reference to static class member

Aaa.h

class Aaa {

protected:

    static Aaa *defaultAaa;

};

Aaa.cpp

// You must define an actual variable in your program for the static members of the classes

static Aaa *Aaa::defaultAaa;

How to see indexes for a database or table in MySQL?

SHOW INDEX FROM mytable FROM mydb;

SHOW INDEX FROM mydb.mytable;

See documentation.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

Illustrated at http://jsfiddle.net/H3y8j/

How can prepared statements protect from SQL injection attacks?

I read through the answers and still felt the need to stress the key point which illuminates the essence of Prepared Statements. Consider two ways to query one's database where user input is involved:

Naive Approach

One concatenates user input with some partial SQL string to generate a SQL statement. In this case the user can embed malicious SQL commands, which will then be sent to the database for execution.

String SQLString = "SELECT * FROM CUSTOMERS WHERE NAME='"+userInput+"'"

For example, malicious user input can lead to SQLString being equal to "SELECT * FROM CUSTOMERS WHERE NAME='James';DROP TABLE CUSTOMERS;'

Due to the malicious user, SQLString contains 2 statements, where the 2nd one ("DROP TABLE CUSTOMERS") will cause harm.

Prepared Statements

In this case, due to the separation of the query & data, the user input is never treated as a SQL statement, and thus is never executed. It is for this reason, that any malicious SQL code injected would cause no harm. So the "DROP TABLE CUSTOMERS" would never be executed in the case above.

In a nutshell, with prepared statements malicious code introduced via user input will not be executed!

Redirecting to a new page after successful login

May be use like this

if($match > 0){
 $msg = 'Login Complete! Thanks';
 echo "<a href='".$link_address."'>link</a>";
 }
else{
 $msg = 'Login Failed!<br /> Please make sure that you enter the correct  details and that you have activated your account.';
}

Make an html number input always display 2 decimal places

an inline solution combines Groot and Ivaylo suggestions in the format below:

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"

What is the difference between null=True and blank=True in Django?

null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.

blank determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True then the field will not be required, whereas if it's False the field cannot be blank.

The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL values for that field. The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').

A few examples:

models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)

models.CharField(blank=True) # No problem, blank is stored as ''

models.CharField(null=True) # NULL allowed, but will never be set as NULL

CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.

Disable automatic sorting on the first column when using jQuery DataTables

Add

"aaSorting": []

And check if default value is not null only set sortable column then

if ($('#table').DataTable().order().length == 1) {
    d.SortColumn = $('#table').DataTable().order()[0][0];
    d.SortOrder = $('#table').DataTable().order()[0][1];
}

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Have a look at the GROUP_CONCAT project on Github, I think I does exactly what you are searching for:

This project contains a set of SQLCLR User-defined Aggregate functions (SQLCLR UDAs) that collectively offer similar functionality to the MySQL GROUP_CONCAT function. There are multiple functions to ensure the best performance based on the functionality required...

Laravel 5.4 Specific Table Migration

Just wanted to post another solution, which i think is worth mentioning.

  1. Find row with your migration name in migrations table and DELETE it. It should look like this: 2016_06_01_000001_create_oauth_auth_codes_table
  2. Remove your table from database e.g. DROP TABLE oauth_auth_codes
  3. Run php artisan migrate

It will migrate only the table you need, and won't touch anything else

Location of hibernate.cfg.xml in project?

Using configure() method two times is responsible the problem for me. Instead of using like this :

    Configuration configuration = new Configuration().configure();
    configuration.configure("/main/resources/hibernate.cfg.xml");

Now, I am using like this, problem does not exist anymore.

    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");

P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5

public class HibernateUtil {

 private static SessionFactory sessionFactory ;


 static {
     try{
    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
     catch(Exception e){
         e.printStackTrace();
     }
     }

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}  

Android MediaPlayer Stop and Play

I may have not got your answer correct, but you can try this:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

Force page scroll position to top at page refresh in HTML

<script> location.hash = (location.hash) ? location.hash : " "; </script>

Put the above script in <head> tag of your html. Not sure how single page apps behave! But sure works like charm in regular pages.

How can jQuery deferred be used?

I've just used Deferred in real code. In project jQuery Terminal I have function exec that call commands defined by user (like he was entering it and pressing enter), I've added Deferreds to the API and call exec with arrays. like this:

terminal.exec('command').then(function() {
   terminal.echo('command finished');
});

or

terminal.exec(['command 1', 'command 2', 'command 3']).then(function() {
   terminal.echo('all commands finished');
});

the commands can run async code, and exec need to call user code in order. My first api use pair of pause/resume calls and in new API I call those automatic when user return promise. So user code can just use

return $.get('/some/url');

or

var d = new $.Deferred();
setTimeout(function() {
    d.resolve("Hello Deferred"); // resolve value will be echoed
}, 500);
return d.promise();

I use code like this:

exec: function(command, silent, deferred) {
    var d;
    if ($.isArray(command)) {
        return $.when.apply($, $.map(command, function(command) {
            return self.exec(command, silent);
        }));
    }
    // both commands executed here (resume will call Term::exec)
    if (paused) {
        // delay command multiple time
        d = deferred || new $.Deferred();
        dalyed_commands.push([command, silent, d]);
        return d.promise();
    } else {
        // commands may return promise from user code
        // it will resolve exec promise when user promise
        // is resolved
        var ret = commands(command, silent, true, deferred);
        if (!ret) {
            if (deferred) {
                deferred.resolve(self);
                return deferred.promise();
            } else {
                d = new $.Deferred();
                ret = d.promise();
                ret.resolve();
            }
        }
        return ret;
    }
},

dalyed_commands is used in resume function that call exec again with all dalyed_commands.

and part of the commands function (I've stripped not related parts)

function commands(command, silent, exec, deferred) {

    var position = lines.length-1;
    // Call user interpreter function
    var result = interpreter.interpreter(command, self);
    // user code can return a promise
    if (result != undefined) {
        // new API - auto pause/resume when using promises
        self.pause();
        return $.when(result).then(function(result) {
            // don't echo result if user echo something
            if (result && position === lines.length-1) {
                display_object(result);
            }
            // resolve promise from exec. This will fire
            // code if used terminal::exec('command').then
            if (deferred) {
                deferred.resolve();
            }
            self.resume();
        });
    }
    // this is old API
    // if command call pause - wait until resume
    if (paused) {
        self.bind('resume.command', function() {
            // exec with resume/pause in user code
            if (deferred) {
                deferred.resolve();
            }
            self.unbind('resume.command');
        });
    } else {
        // this should not happen
        if (deferred) {
            deferred.resolve();
        }
    }
}

Best Practices: working with long, multiline strings in PHP?

I use templates for long text:

email-template.txt contains

hello {name}!
how are you? 

In PHP I do this:

$email = file_get_contents('email-template.txt');
$email = str_replace('{name},', 'Simon', $email);

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I solved this issue by downgrading classpath 'com.android.tools.build:gradle:3.2.1' and distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

MongoDB/Mongoose querying at a specific date?

You can use following approach for API method to get results from specific day:

# [HTTP GET]
getMeals: (req, res) ->
  options = {}
  # eg. api/v1/meals?date=Tue+Jan+13+2015+00%3A00%3A00+GMT%2B0100+(CET)
  if req.query.date?
    date = new Date req.query.date
    date.setHours 0, 0, 0, 0
    endDate = new Date date
    endDate.setHours 23, 59, 59, 59
    options.date =
      $lt: endDate
      $gte: date

  Meal.find options, (err, meals) ->
      if err or not meals
        handleError err, meals, res
      else
        res.json createJSON meals, null, 'meals'

Generic List - moving an item within the list

Is more simple guys just do this

    public void MoveUp(object item,List Concepts){

        int ind = Concepts.IndexOf(item.ToString());

        if (ind != 0)
        {
            Concepts.RemoveAt(ind);
            Concepts.Insert(ind-1,item.ToString());
            obtenernombres();
            NotifyPropertyChanged("Concepts");
        }}

Do the same with MoveDown but change the if for "if (ind !=Concepts.Count())" and the Concepts.Insert(ind+1,item.ToString());

Error handling in Bash

I've used

die() {
        echo $1
        kill $$
}

before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.

Remove gutter space for a specific div only

To add to Skelly's Bootstrap 3 no-gutter answer above (https://stackoverflow.com/a/21282059/662883)

Add the following to prevent gutters on a row containing only one column (useful when using column-wrapping: http://getbootstrap.com/css/#grid-example-wrapping):

.row.no-gutter [class*='col-']:only-child,
.row.no-gutter [class*='col-']:only-child
{
    padding-right: 0;
    padding-left: 0;
}

move_uploaded_file gives "failed to open stream: Permission denied" error

I have tried all the solutions above, but the following solved my problem

chcon -R -t httpd_sys_rw_content_t your_file_directory

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

Most efficient way to find smallest of 3 numbers Java?

Math.min uses a simple comparison to do its thing. The only advantage to not using Math.min is to save the extra function calls, but that is a negligible saving.

If you have more than just three numbers, having a minimum method for any number of doubles might be valuable and would look something like:

public static double min(double ... numbers) {
    double min = numbers[0];
    for (int i=1 ; i<numbers.length ; i++) {
        min = (min <= numbers[i]) ? min : numbers[i];
    }
    return min;
}

For three numbers this is the functional equivalent of Math.min(a, Math.min(b, c)); but you save one method invocation.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

Oracle sqlldr TRAILING NULLCOLS required, but why?

I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,

You can not see those if open in Excel. Please check in Notepad and delete those records

How to read a file into a variable in shell?

With bash you may use read like tis:

#!/usr/bin/env bash

{ IFS= read -rd '' value <config.txt;} 2>/dev/null

printf '%s' "$value"

Notice that:

  • The last newline is preserved.

  • The stderr is silenced to /dev/null by redirecting the whole commands block, but the return status of the read command is preserved, if one needed to handle read error conditions.

Command to find information about CPUs on a UNIX machine

My favorite is to look at the boot messages. If it's been recently booted try running /etc/dmesg. Otherwise find the boot messages, logged in /var/adm or some place in /var.

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

How to focus on a form input text field on page load using jQuery?

This is what I prefer to use:

<script type="text/javascript">
    $(document).ready(function () {
        $("#fieldID").focus(); 
    });
</script>

How to make matrices in Python?

Looping helps:

for row in matrix:
    print ' '.join(row)

or use nested str.join() calls:

print '\n'.join([' '.join(row) for row in matrix])

Demo:

>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
...     print ' '.join(row)
... 
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

If you wanted to show the rows and columns transposed, transpose the matrix by using the zip() function; if you pass each row as a separate argument to the function, zip() recombines these value by value as tuples of columns instead. The *args syntax lets you apply a whole sequence of rows as separate arguments:

>>> for cols in zip(*matrix):  # transposed
...     print ' '.join(cols)
... 
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

Finding local maxima/minima with Numpy in a 1D numpy array

import numpy as np
x=np.array([6,3,5,2,1,4,9,7,8])
y=np.array([2,1,3,5,3,9,8,10,7])
sortId=np.argsort(x)
x=x[sortId]
y=y[sortId]
minm = np.array([])
maxm = np.array([])
i = 0
while i < length-1:
    if i < length - 1:
        while i < length-1 and y[i+1] >= y[i]:
            i+=1

        if i != 0 and i < length-1:
            maxm = np.append(maxm,i)

        i+=1

    if i < length - 1:
        while i < length-1 and y[i+1] <= y[i]:
            i+=1

        if i < length-1:
            minm = np.append(minm,i)
        i+=1


print minm
print maxm

minm and maxm contain indices of minima and maxima, respectively. For a huge data set, it will give lots of maximas/minimas so in that case smooth the curve first and then apply this algorithm.

How to remove all numbers from string?

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

Use grep to report back only line numbers

To count the number of lines matched the pattern:

grep -n "Pattern" in_file.ext | wc -l 

To extract matched pattern

sed -n '/pattern/p' file.est

To display line numbers on which pattern was matched

grep -n "pattern" file.ext | cut -f1 -d:

"RangeError: Maximum call stack size exceeded" Why?

Browsers can't handle that many arguments. See this snippet for example:

alert.apply(window, new Array(1000000000));

This yields RangeError: Maximum call stack size exceeded which is the same as in your problem.

To solve that, do:

var arr = [];
for(var i = 0; i < 1000000; i++){
    arr.push(Math.random());
}