Programs & Examples On #Staging

Staging is the process of deploying to an intermediate, usually internal, repository so that deployed artifacts can be tested and later promoted to higher levels so that they can finally be release to public repositories

git add only modified changes and ignore untracked files

You didn't say what's currently your .gitignore, but a .gitignore with the following contents in your root directory should do the trick.

.metadata
build

How do I remove a single file from the staging area (undo git add)?

My sample:

$ git status
On branch feature/wildfire/VNL-425-update-wrong-translation
Your branch and 'origin/feature/wildfire/VNL-425-update-wrong-translation' have diverged,
and have 4 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   ShopBack/Source/Date+Extension.swift
    modified:   ShopBack/Source/InboxData.swift
    modified:   ShopBack/en.lproj/Localizable.strings

As you may notice

> Changes to be committed:
>       (use "git reset HEAD <file>..." to unstage)

Entity Framework : How do you refresh the model when the db changes?

Update CodeFirst Model is not possible automatically. I don't recommend either. Because one of the benefits of code first is you can work with POCO classes. If you changed this POCO classes you don't want some auto generated code to destroy your work.

But you can create some template solution add your updated/added entity to the new model. then collect and move your new cs file to your working project. this way you will not have a conflict if it is a new entity you can simply adding related cs file to the existing project. if it is an update just add a new property from the file. If you just adding some couple of columns to one or two of your tables you can manually add them to your POCO class you don't need any extra works and that is the beauty of Working with Code-First and POCO classes.

How to resolve "must be an instance of string, string given" prior to PHP 7?

As of PHP 7.0 type declarations allow scalar types, so these types are now available: self, array, callable, bool, float, int, string. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer or boolean) that will be interpreted as a class name.

See the PHP manual for more information.

How to list the tables in a SQLite database file that was opened with ATTACH?

According to the documentation, the equivalent of MySQLs' SHOW TABLES; is:

The ".tables" command is similar to setting list mode then executing the following query:

SELECT name FROM sqlite_master
  WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
  WHERE type IN ('table','view')
ORDER BY 1;

However, if you are checking if a single table exists (or to get its details), see @LuizGeron answer.

PHP Curl And Cookies

First create temporary cookie using tempnam() function:

$ckfile = tempnam ("/tmp", "CURLCOOKIE");

Then execute curl init witch saves the cookie as a temporary file:

$ch = curl_init ("http://uri.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

Or visit a page using the cookie stored in the temporary file:

$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

This will initialize the cookie for the page:

curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript Src Path

The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:

/js/clock.js

then you could add this code to the top of any page in your site and it would just work:

<script src="/js/clock.js" type="text/javascript"></script>

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

How to use jQuery with Angular?

//installing jquerynpm install jquery --save

//installing type defintion for the jquerytypings install dt~jquery --global --save

//adding jquery library into build configuration file as specified(in "angular-cli-build.js" file)

vendorNpmFiles: [
  .........
  .........
  'jquery/dist/jquery.min.js'
]

//run the build to add the jquery library in the build ng build

//adding the relative path configuration(in system-config.js) /** Map relative paths to URLs. */ const map: any = { ....., ......., 'jquery': 'vendor/jquery/dist' };

/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};

//import the jquery library in your component file

import 'jquery';

below is the code snipppet of my sample component

import { Component } from '@angular/core';
import 'jquery';
@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',  
  styleUrls: ['app.component.css']
})
export class AppComponent {
  list:Array<number> = [90,98,56,90];
  title = 'app works!';
  isNumber:boolean = jQuery.isNumeric(89)  
  constructor(){}
}

How to order citations by appearance using BibTeX?

If you happen to be using amsrefs they will override all the above - so comment out:

\usepackage{amsrefs}

Call a python function from jinja2

from jinja2 import Template

def custom_function(a):
    return a.replace('o', 'ay')

template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function

You can also give the function in the fields as per Matroskin's answer

fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)

Will output:

Hey, my name is Jay Kay

Works with Jinja2 version 2.7.3

And if you want a decorator to ease defining functions on template.globals check out Bruno Bronosky's answer

How to parse a JSON object to a TypeScript Object

The reason that the compiler lets you cast the object returned from JSON.parse to a class is because typescript is based on structural subtyping.
You don't really have an instance of an Employee, you have an object (as you see in the console) which has the same properties.

A simpler example:

class A {
    constructor(public str: string, public num: number) {}
}

function logA(a: A) {
    console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);
}

let a1 = { str: "string", num: 0, boo: true };
let a2 = new A("stirng", 0);
logA(a1); // no errors
logA(a2);

(code in playground)

There's no error because a1 satisfies type A because it has all of its properties, and the logA function can be called with no runtime errors even if what it receives isn't an instance of A as long as it has the same properties.

That works great when your classes are simple data objects and have no methods, but once you introduce methods then things tend to break:

class A {
    constructor(public str: string, public num: number) { }

    multiplyBy(x: number): number {
        return this.num * x;
    }
}

// this won't compile:
let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'

// but this will:
let a2 = { str: "string", num: 0 } as A;

// and then you get a runtime error:
a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function

(code in playground)


Edit

This works just fine:

const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';
let employee1 = JSON.parse(employeeString);
console.log(employee1);

(code in playground)

If you're trying to use JSON.parse on your object when it's not a string:

let e = {
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 3,
    "username": "<anystring>",
    "permissions": "<anystring>",
    "lastUpdate": "<anydate>"
}
let employee2 = JSON.parse(e);

Then you'll get the error because it's not a string, it's an object, and if you already have it in this form then there's no need to use JSON.parse.

But, as I wrote, if you're going with this way then you won't have an instance of the class, just an object that has the same properties as the class members.

If you want an instance then:

let e = new Employee();
Object.assign(e, {
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 3,
    "username": "<anystring>",
    "permissions": "<anystring>",
    "lastUpdate": "<anydate>"
});

PHP equivalent of .NET/Java's toString()

This is done with typecasting:

$strvar = (string) $var; // Casts to string
echo $var; // Will cast to string implicitly
var_dump($var); // Will show the true type of the variable

In a class you can define what is output by using the magical method __toString. An example is below:

class Bottles {
    public function __toString()
    {
        return 'Ninety nine green bottles';
    }
}

$ex = new Bottles;
var_dump($ex, (string) $ex);
// Returns: instance of Bottles and "Ninety nine green bottles"

Some more type casting examples:

$i = 1;

// int 1
var_dump((int) $i);

// bool true
var_dump((bool) $i);

// string "1"
var_dump((string) 1);

How to create a windows service from java app

I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.

How to simulate a mouse click using JavaScript?

You can use elementFromPoint:

document.elementFromPoint(x, y);

supported in all browsers: https://caniuse.com/#feat=element-from-point

How do I put a variable inside a string?

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

How to solve maven 2.6 resource plugin dependency?

Right Click on Project go to -> Maven -> Update project ->select Force update project check box and click on Finish.

Is there a simple way to remove multiple spaces in a string?

I have tried the following method and it even works with the extreme case like:

str1='          I   live    on    earth           '

' '.join(str1.split())

But if you prefer a regular expression it can be done as:

re.sub('\s+', ' ', str1)

Although some preprocessing has to be done in order to remove the trailing and ending space.

Renaming columns in Pandas

Since you only want to remove the $ sign in all column names, you could just do:

df = df.rename(columns=lambda x: x.replace('$', ''))

OR

df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

How do I move files in node.js?

I would separate all involved functions (i.e. rename, copy, unlink) from each other to gain flexibility and promisify everything, of course:

const renameFile = (path, newPath) => 
  new Promise((res, rej) => {
    fs.rename(path, newPath, (err, data) =>
      err
        ? rej(err)
        : res(data));
  });

const copyFile = (path, newPath, flags) =>
  new Promise((res, rej) => {
    const readStream = fs.createReadStream(path),
      writeStream = fs.createWriteStream(newPath, {flags});

    readStream.on("error", rej);
    writeStream.on("error", rej);
    writeStream.on("finish", res);
    readStream.pipe(writeStream);
  });

const unlinkFile = path => 
  new Promise((res, rej) => {
    fs.unlink(path, (err, data) =>
      err
        ? rej(err)
        : res(data));
  });

const moveFile = (path, newPath, flags) =>
  renameFile(path, newPath)
    .catch(e => {
      if (e.code !== "EXDEV")
        throw new e;

      else
        return copyFile(path, newPath, flags)
          .then(() => unlinkFile(path));
    });

moveFile is just a convenience function and we can apply the functions separately, when, for example, we need finer grained exception handling.

C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

What is the easiest way to parse an INI file in Java?

Another option is Apache Commons Config also has a class for loading from INI files. It does have some runtime dependencies, but for INI files it should only require Commons collections, lang, and logging.

I've used Commons Config on projects with their properties and XML configurations. It is very easy to use and supports some pretty powerful features.

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Although this may not solve your problem, it did for me when I wanted to do a similar thing. Instead of setting the header I used the footer of the section above. What saved me was that this section was small and static in nature, so it never scrolled below the bottom of the view.

CASE .. WHEN expression in Oracle SQL

You could use an IN clause

Something like

SELECT
  status,
  CASE
    WHEN STATUS IN('a1','a2','a3')
    THEN 'Active'
    WHEN STATUS = 'i'
    THEN 'Inactive'
    WHEN STATUS = 't'
    THEN 'Terminated'
  END AS STATUSTEXT
FROM
  STATUS

Have a look at this demo

SQL Fiddle DEMO

In jQuery, how do I get the value of a radio button when they all have the same name?

There is another way also. Try below code

$(document).ready(function(){

      $("input[name='gender']").on("click", function() {
            alert($(this).val());
        });
});

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

Android: Scale a Drawable or background image?

To keep the aspect ratio you have to use android:scaleType=fitCenter or fitStart etc. Using fitXY will not keep the original aspect ratio of the image!

Note this works only for images with a src attribute, not for the background image.

How to search a specific value in all tables (PostgreSQL)?

Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.

DO $$
DECLARE
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
BEGIN
  DROP TABLE IF EXISTS _x;
  CREATE TEMPORARY TABLE _x (
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  );
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
        LOOP
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
    BEGIN
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
    EXCEPTION WHEN OTHERS THEN
    END;
  END LOOP;
  END; $$;

SELECT * FROM _x;

Is it possible to focus on a <div> using JavaScript focus() function?

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

How to build x86 and/or x64 on Windows from command line with CMAKE?

This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.

To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.

For CMake 3.13 or newer, run the following commands:

cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release

For earlier versions of CMake, run the following commands:

mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release

CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build followed by the build directory. The --config option specifies the build configuration.

How to Make A Chevron Arrow Using CSS?

Here's a different approach:

1) Use the multiplication character: &times; ×

2) Hide half of it with overflow:hidden

3) Then add a triangle as a pseudo element for the tip.

The advantage here is that no transforms are necessary. (It will work in IE8+)

FIDDLE

_x000D_
_x000D_
.arrow {_x000D_
  position: relative;_x000D_
}_x000D_
.arrow:before {_x000D_
  content: '×';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  font-size: 240px;_x000D_
  font-weight: bold;_x000D_
  font-family: verdana;_x000D_
  width: 103px;_x000D_
  height: 151px;_x000D_
  overflow: hidden;_x000D_
  line-height: 117px;_x000D_
}_x000D_
.arrow:after {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  left: 101px;_x000D_
  top: 51px;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-style: solid;_x000D_
  border-width: 25px 0 25px 24px;_x000D_
  border-color: transparent transparent transparent black;_x000D_
}
_x000D_
<div class="arrow"></div>
_x000D_
_x000D_
_x000D_

How do you specify a different port number in SQL Management Studio?

Using the client manager affects all connections or sets a client machine specific alias.

Use the comma as above: this can be used in an app.config too

It's probably needed if you have firewalls between you and the server too...

How to modify the nodejs request default timeout time?

With the latest NodeJS you can experiment with this monkey patch:

const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
    const that = this;
    socket.setTimeout(this.timeout ? this.timeout : 3000);
    socket.on('timeout', function() {
        that.abort();
    });
    originalOnSocket.call(this, socket);
};

Drawing in Java using Canvas

The following should work:

public static void main(String[] args)
{
    final String title = "Test Window";
    final int width = 1200;
    final int height = width / 16 * 9;

    //Creating the frame.
    JFrame frame = new JFrame(title);

    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    //Creating the canvas.
    Canvas canvas = new Canvas();

    canvas.setSize(width, height);
    canvas.setBackground(Color.BLACK);
    canvas.setVisible(true);
    canvas.setFocusable(false);


    //Putting it all together.
    frame.add(canvas);

    canvas.createBufferStrategy(3);

    boolean running = true;

    BufferStrategy bufferStrategy;
    Graphics graphics;

    while (running) {
        bufferStrategy = canvas.getBufferStrategy();
        graphics = bufferStrategy.getDrawGraphics();
        graphics.clearRect(0, 0, width, height);

        graphics.setColor(Color.GREEN);
        graphics.drawString("This is some text placed in the top left corner.", 5, 15);

        bufferStrategy.show();
        graphics.dispose();
    }
}

What is the best way to repeatedly execute a function every x seconds?

The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.

A SQL Query to select a string between two known strings

You need to adjust for the LENGTH in the SUBSTRING. You were pointing it to the END of the 'ending string'.

Try something like this:

declare @TEXT varchar(200)
declare @ST varchar(200)
declare @EN varchar(200)
set @ST = 'the dog'
set @EN = 'immediately'
set @TEXT = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
SELECT SUBSTRING(@Text, CHARINDEX(@ST, @Text), (CHARINDEX(@EN, @Text)+LEN(@EN))-CHARINDEX(@ST, @Text))

Of course, you may need to adjust it a bit.

Builder Pattern in Effective Java

Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.

public class NutritionFacts {
    public static class Builder {
    }
}

Reference: Nested classes

LIMIT 10..20 in SQL Server

For SQL Server 2012 + you can use.

SELECT  *
FROM     sys.databases
ORDER BY name 
OFFSET  5 ROWS 
FETCH NEXT 5 ROWS ONLY 

Difference between "or" and || in Ruby?

or is NOT the same as ||. Use only || operator instead of the or operator.

Here are some reasons. The:

  • or operator has a lower precedence than ||.
  • or has a lower precedence than the = assignment operator.
  • and and or have the same precedence, while && has a higher precedence than ||.

Execution failed for task :':app:mergeDebugResources'. Android Studio

click here for the image

  1. Click Gradle in the right side tab

  2. Click the toggle offline icon (enable the Gradle online)

  3. Now try building the project

    And that's it!

Can I make a function available in every controller in angular?

I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.

This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

What is difference between monolithic and micro kernel?

Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site. For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here

How do I push to GitHub under a different username?

It's simple while cloning please take the git URL with your username.While committing it will ask your new user password.

Eg:

git clone https://[email protected]/username/reponame.git

git clone https://[email protected]/username/reponame.git

Twitter Bootstrap - how to center elements horizontally or vertically

for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

<div class="d-flex flex-column justify-content-center bg-secondary" style="
    height: 300px;
">
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
  </div> 

[Ljava.lang.Object; cannot be cast to

I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:

You need to frame your query like this

select entity from Entity as entity where ...

Also check such case, it perfectly works for me:

public List<User> findByRole(String role) {

    Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
    query.setString("role_name", role);
    @SuppressWarnings("unchecked")
    List<User> users = (List<User>) query.list();
    return users;
}

So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.

How can I read and parse CSV files in C++?

For what it is worth, here is my implementation. It deals with wstring input, but could be adjusted to string easily. It does not handle newline in fields (as my application does not either, but adding its support isn't too difficult) and it does not comply with "\r\n" end of line as per RFC (assuming you use std::getline), but it does handle whitespace trimming and double-quotes correctly (hopefully).

using namespace std;

// trim whitespaces around field or double-quotes, remove double-quotes and replace escaped double-quotes (double double-quotes)
wstring trimquote(const wstring& str, const wstring& whitespace, const wchar_t quotChar)
{
    wstring ws;
    wstring::size_type strBegin = str.find_first_not_of(whitespace);
    if (strBegin == wstring::npos)
        return L"";

    wstring::size_type strEnd = str.find_last_not_of(whitespace);
    wstring::size_type strRange = strEnd - strBegin + 1;

    if((str[strBegin] == quotChar) && (str[strEnd] == quotChar))
    {
        ws = str.substr(strBegin+1, strRange-2);
        strBegin = 0;
        while((strEnd = ws.find(quotChar, strBegin)) != wstring::npos)
        {
            ws.erase(strEnd, 1);
            strBegin = strEnd+1;
        }

    }
    else
        ws = str.substr(strBegin, strRange);
    return ws;
}

pair<unsigned, unsigned> nextCSVQuotePair(const wstring& line, const wchar_t quotChar, unsigned ofs = 0)
{
    pair<unsigned, unsigned> r;
    r.first = line.find(quotChar, ofs);
    r.second = wstring::npos;
    if(r.first != wstring::npos)
    {
        r.second = r.first;
        while(((r.second = line.find(quotChar, r.second+1)) != wstring::npos)
            && (line[r.second+1] == quotChar)) // WARNING: assumes null-terminated string such that line[r.second+1] always exist
            r.second++;

    }
    return r;
}

unsigned parseLine(vector<wstring>& fields, const wstring& line)
{
    unsigned ofs, ofs0, np;
    const wchar_t delim = L',';
    const wstring whitespace = L" \t\xa0\x3000\x2000\x2001\x2002\x2003\x2004\x2005\x2006\x2007\x2008\x2009\x200a\x202f\x205f";
    const wchar_t quotChar = L'\"';
    pair<unsigned, unsigned> quot;

    fields.clear();

    ofs = ofs0 = 0;
    quot = nextCSVQuotePair(line, quotChar);
    while((np = line.find(delim, ofs)) != wstring::npos)
    {
        if((np > quot.first) && (np < quot.second))
        { // skip delimiter inside quoted field
            ofs = quot.second+1;
            quot = nextCSVQuotePair(line, quotChar, ofs);
            continue;
        }
        fields.push_back( trimquote(line.substr(ofs0, np-ofs0), whitespace, quotChar) );
        ofs = ofs0 = np+1;
    }
    fields.push_back( trimquote(line.substr(ofs0), whitespace, quotChar) );

    return fields.size();
}

"Port 4200 is already in use" when running the ng serve command

I also faced the same error msg, so i tried ng serve --port 12012 and it worked fine.

How can I download a specific Maven artifact in one command line?

To copy artifact in specified location use copy instead of get.

mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
  -DrepoUrl=someRepositoryUrl \
  -Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/

Programmatically set the initial view controller using Storyboards

I created a routing class to handle dynamic navigation and keep clean AppDelegate class, I hope it will help other too.

//
//  Routing.swift
// 
//
//  Created by Varun Naharia on 02/02/17.
//  Copyright © 2017 TechNaharia. All rights reserved.
//

import Foundation
import UIKit
import CoreLocation

class Routing {

    class func decideInitialViewController(window:UIWindow){
        let userDefaults = UserDefaults.standard
        if((Routing.getUserDefault("isFirstRun")) == nil)
        {
            Routing.setAnimatedAsInitialViewContoller(window: window)
        }
        else if((userDefaults.object(forKey: "User")) != nil)
        {
            Routing.setHomeAsInitialViewContoller(window: window)
        }
        else
        {
            Routing.setLoginAsInitialViewContoller(window: window)
        }

    }

    class func setAnimatedAsInitialViewContoller(window:UIWindow) {
        Routing.setUserDefault("Yes", KeyToSave: "isFirstRun")
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let animatedViewController: AnimatedViewController = mainStoryboard.instantiateViewController(withIdentifier: "AnimatedViewController") as! AnimatedViewController

        window.rootViewController = animatedViewController
        window.makeKeyAndVisible()
    }

    class func setHomeAsInitialViewContoller(window:UIWindow) {
        let userDefaults = UserDefaults.standard
        let decoded  = userDefaults.object(forKey: "User") as! Data
        User.currentUser = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! User

        if(User.currentUser.userId != nil && User.currentUser.userId != "")
        {
            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let homeViewController: HomeViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
            let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController
            loginViewController.viewControllers.append(homeViewController)
            window.rootViewController = loginViewController
        }
        window.makeKeyAndVisible()
    }

    class func setLoginAsInitialViewContoller(window:UIWindow) {
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController

        window.rootViewController = loginViewController
        window.makeKeyAndVisible()
    }

  class func setUserDefault(_ ObjectToSave : Any?  , KeyToSave : String)
    {
        let defaults = UserDefaults.standard

        if (ObjectToSave != nil)
        {

            defaults.set(ObjectToSave, forKey: KeyToSave)
        }

        UserDefaults.standard.synchronize()
    }

    class func getUserDefault(_ KeyToReturnValye : String) -> Any?
    {
        let defaults = UserDefaults.standard

        if let name = defaults.value(forKey: KeyToReturnValye)
        {
            return name as Any
        }
        return nil
    }

    class func removetUserDefault(_ KeyToRemove : String)
    {
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: KeyToRemove)
        UserDefaults.standard.synchronize()
    }

}

And in your AppDelegate call this

 self.window = UIWindow(frame: UIScreen.main.bounds)
 Routing.decideInitialViewController(window: self.window!)

Evaluate list.contains string in JSTL

The following is more of a workaround than an answer to your question but it may be what you are looking for. If you can put your values in a map instead of a list, that would solve your problem. Just map your values to a non null value and do this <c:if test="${mymap.myValue ne null}">style='display:none;'</c:if> or you can even map to style='display:none; and simply output ${mymap.myValue}

How to execute a raw update sql with dynamic binding in rails

Sometime would be better use name of parent class instead name of table:

# Refers to the current class
self.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)

For example "Person" base class, subclasses (and database tables) "Client" and "Seller" Instead using:

Client.where(self.class.primary_key => id).update_all(created _at: timestamp)
Seller.where(self.class.primary_key => id).update_all(created _at: timestamp)

You can use object of base class by this way:

person.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)

Multiplying across in a numpy array

Why don't you just do

>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> (m.T * c).T

??

Angularjs dynamic ng-pattern validation

This is an interesting problem, complex Angular validation. The following fiddle implements what you want:

http://jsfiddle.net/2G8gA/1/

Details

I created a new directive, rpattern, that is a mix of Angular's ng-required and the ng-pattern code from input[type=text]. What it does is watch the required attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern.

Notes

  • Most of the code is from Angular, tailored to the needs of this.
  • When the checkbox is checked, the field is required.
  • The field is not hidden when the required checkbox is false.
  • The regular expression is simplified for the demo (valid is 3 digits).

A dirty (but smaller) solution, if you do not want a new directive, would be something like:

$scope.phoneNumberPattern = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            if( $scope.requireTel === false ) {
                return true;
            }
            return regexp.test(value);
        }
    };
})();

And in HTML no changes would be required:

<input type="text" ng-model="..." ng-required="requireTel"
    ng-pattern="phoneNumberPattern" />

This actually tricks angular into calling our test() method, instead of RegExp.test(), that takes the required into account.

Add a summary row with totals

Try to use union all as below

SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before

if you have problem with ordering, as i-one suggested try this:

select [Type], [Total Sales] 
from (SELECT [Type], [Total Sales], 0 [Key] 
      From Before 
      union all 
      SELECT 'Total', Sum([Total Sales]), 1 From Before) sq 
order by [Key], Type

Default values and initialization in Java

In Java, the default initialization is applicable for only instance variable of class member.

It isn't applicable for local variables.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

Validate that text field is numeric usiung jQuery

I know there isn't any need to add a plugin for this.

But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.

The rest of karim79's answer is super cool.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.numeric.js"></script>
    </head>

    <body>
        <form>
            Numbers only:
            <input class="numeric" type="text" />
            Integers only:
            <input class="integer" type="text" />
            No negative values:
            <input class="positive" type="text" />
            No negative values (integer only):
            <input class="positive-integer" type="text" />
            <a href="#" id="remove">Remove numeric</a>
        </form>

        <script type="text/javascript">
            $(".numeric").numeric();

            $(".integer").numeric(false, function() {
                alert("Integers only");
                this.value = "";
                this.focus();
            });

            $(".positive").numeric({ negative: false },
                function() {
                    alert("No negative values");
                    this.value = "";
                    this.focus();
                });

            $(".positive-integer").numeric({ decimal: false, negative: false },
                function() {
                    alert("Positive integers only");
                    this.value = "";
                    this.focus();
                });

            $("#remove").click(
                function(e)
                {
                    e.preventDefault();
                    $(".numeric,.integer,.positive").removeNumeric();
                }
            );
        </script>

    </body>
</html>

Passing parameter via url to sql server reporting service

Try passing multiple values via url:

/ReportServer?%2fService+Specific+Reports%2fFilings%2fDrillDown%2f&StartDate=01/01/2010&EndDate=01/05/2010&statuses=1&statuses=2&rs%3AFormat=PDF

This should work.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I solved it this way:

First, I stopped all running containers:

docker-compose down

Then I executed a lsof command to find the process using the port (for me it was port 9000)

sudo lsof -i -P -n | grep 9000

Finally, I "killed" the process (in my case, it was a VSCode extension):

kill -9 <process id>

What does IFormatProvider do?

The IFormatProvider interface is normally implemented for you by a CultureInfo class, e.g.:

  • CultureInfo.CurrentCulture
  • CultureInfo.CurrentUICulture
  • CultureInfo.InvariantCulture
  • CultureInfo.CreateSpecificCulture("de-CA") //German (Canada)

The interface is a gateway for a function to get a set of culture-specific data from a culture. The two commonly available culture objects that an IFormatProvider can be queried for are:

The way it would normally work is you ask the IFormatProvider to give you a DateTimeFormatInfo object:

DateTimeFormatInfo format;
format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
if (format != null)
   DoStuffWithDatesOrTimes(format);

There's also inside knowledge that any IFormatProvider interface is likely being implemented by a class that descends from CultureInfo, or descends from DateTimeFormatInfo, so you could cast the interface directly:

CultureInfo info = provider as CultureInfo;
if (info != null)
   format = info.DateTimeInfo;
else
{
   DateTimeFormatInfo dtfi = provider as DateTimeFormatInfo;
   if (dtfi != null)
       format = dtfi;
   else
       format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
}

if (format != null)
   DoStuffWithDatesOrTimes(format);

But don't do that

All that hard work has already been written for you:

To get a DateTimeFormatInfo from an IFormatProvider:

DateTimeFormatInfo format = DateTimeFormatInfo.GetInstance(provider);

To get a NumberFormatInfo from an IFormatProvider:

NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);

The value of IFormatProvider is that you create your own culture objects. As long as they implement IFormatProvider, and return objects they're asked for, you can bypass the built-in cultures.

You can also use IFormatProvider for a way of passing arbitrary culture objects - through the IFormatProvider. E.g. the name of god in different cultures

  • god
  • God
  • Jehova
  • Yahwe
  • ????
  • ???? ??? ????

This lets your custom LordsNameFormatInfo class ride along inside an IFormatProvider, and you can preserve the idiom.

In reality you will never need to call GetFormat method of IFormatProvider yourself.

Whenever you need an IFormatProvider you can pass a CultureInfo object:

DateTime.Now.ToString(CultureInfo.CurrentCulture);

endTime.ToString(CultureInfo.InvariantCulture);

transactionID.toString(CultureInfo.CreateSpecificCulture("qps-ploc"));

Note: Any code is released into the public domain. No attribution required.

How can I search (case-insensitive) in a column using LIKE wildcard?

Simply use :

"SELECT * FROM `trees` WHERE LOWER(trees.`title`) LIKE  '%elm%'";

Or Use

"SELECT * FROM `trees` WHERE LCASE(trees.`title`) LIKE  '%elm%'";

Both functions works same

'AND' vs '&&' as operator

which version are you using?

If the coding standards for the particular codebase I am writing code for specifies which operator should be used, I'll definitely use that. If not, and the code dictates which should be used (not often, can be easily worked around) then I'll use that. Otherwise, probably &&.

Is 'and' more readable than '&&'?

Is it more readable to you. The answer is yes and no depending on many factors including the code around the operator and indeed the person reading it!

|| there is ~ difference?

Yes. See logical operators for || and bitwise operators for ~.

Validating URL in Java

Are you sure you're using the correct proxy as system properties?

Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

Checking host availability by using ping in bash scripts

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

How to turn on WCF tracing?

In your web.config (on the server) add

<system.diagnostics>
 <sources>
  <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
   <listeners>
    <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
   </listeners>
  </source>
 </sources>
</system.diagnostics>

How to convert a HTMLElement to a string

Suppose your element is entire [object HTMLDocument]. You can convert it to a String this way:

_x000D_
_x000D_
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]

const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);
_x000D_
_x000D_
_x000D_

MySQL Trigger after update only if row has changed

In here if there any row affect with new insertion Then it will update on different table in the database.

DELIMITER $$

CREATE TRIGGER "give trigger name" AFTER INSERT ON "table name" 
FOR EACH ROW
BEGIN
    INSERT INTO "give table name you want to add the new insertion on previously given table" (id,name,age) VALUES (10,"sumith",24);
END;
$$
DELIMITER ;

Disabling the button after once click

jQuery now has the .one() function that limits any given event (such as "submit") to one occurrence.

Example:

$('#myForm').one('submit', function() {
    $(this).find('input[type="submit"]').attr('disabled','disabled');
});

This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.

Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.

Note 2: Per gorelog, using attr('disabled','disabled') will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;') instead.

How can I shrink the drawable on a button?

Use a ScaleDrawable as Abhinav suggested.

The problem is that the drawable doesn't show then - it's some sort of bug in ScaleDrawables. you'll need to change the "level" programmatically. This should work for every button:

// Fix level of existing drawables
Drawable[] drawables = myButton.getCompoundDrawables();
for (Drawable d : drawables) if (d != null && d instanceof ScaleDrawable) d.setLevel(1);
myButton.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);

What's onCreate(Bundle savedInstanceState)

As Dhruv Gairola answered, you can save the state of the application by using Bundle savedInstanceState. I am trying to give a very simple example that new learners like me can understand easily.

Suppose, you have a simple fragment with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this. If you take a look into the life cyle of the fragment.Fragment Lifecylce you will get that a method "onSaveInstanceState" is called when the fragment is about to destroyed.

So, we can save the state means the changed text value into that bundle like this

 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }

After you make the orientation the "onCreate" method will be called right? so we can just do this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //here zero is the default value
    }
}

Now, you won't lose your value after the orientation. The modified value always will be displayed.

Cannot delete or update a parent row: a foreign key constraint fails

This happened to me as well and due to a dependency and reference from other tables, I could not remove the entry. What I did is added a delete column (of type boolean) to the table. The value in that field showed whether the item is marked for deletion or not. If marked for deletion, don't fetch/use; otherwise, use it.

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

Bootstrap datepicker hide after selection

$('#input').datepicker({autoclose:true});

Find UNC path of a network drive?

The answer is a simple PowerShell one-liner:

Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A

If you only want to pull the UNC for one particular drive, add a where statement:

Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:'  | ft "RemoteName","LocalName" -A

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

Android Call an method from another class

You should use the following code :

Class2 cls2 = new Class2();
cls2.UpdateEmployee();

In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.UpdateEmployee().

How to call a method function from another class?

You need a reference to the class that contains the method you want to call. Let's say we have two classes, A and B. B has a method you want to call from A. Class A would look like this:

public class A
{
    B b; // A reference to B

    b = new B(); // Creating object of class B

    b.doSomething();  // Calling a method contained in class B from class A
}

B, which contains the doSomething() method would look like this:

public class B
{
    public void doSomething()
    {
        System.out.println("Look, I'm doing something in class B!");
    }
}

MySQL - Cannot add or update a child row: a foreign key constraint fails

On an unrelated task, I recently brought up our MySQL database in MySQL Workbench, and when viewing the table relations for the above tables, I noticed 'duplicate' and/or spurious relations that I had somehow missed before (they weren't showing up in PHPMyAdmin FWIW). Removing these extra relations cleared up the issue immediately.

Convert column classes in data.table

Here is the same way as @Nera suggested to check the class first but instead of using .SD is to use the fast loop of data.table with set as @Matt Dowle solution with added class check.

for (j in seq_len(ncol(DT))){
  if(class(DT[[j]]) == 'factor')
    set(DT, j = j, value = as.character(DT[[j]]))
}

Is there any way to kill a Thread?

If you really need the ability to kill a sub-task, use an alternate implementation. multiprocessing and gevent both support indiscriminately killing a "thread".

Python's threading does not support cancellation. Do not even try. Your code is very likely to deadlock, corrupt or leak memory, or have other unintended "interesting" hard-to-debug effects which happen rarely and nondeterministically.

Convert double/float to string

I know maybe it is unnecessary, but I made a function which converts float to string:

CODE:

#include <stdio.h>

/** Number on countu **/

int n_tu(int number, int count)
{
    int result = 1;
    while(count-- > 0)
        result *= number;

    return result;
}

/*** Convert float to string ***/
void float_to_string(float f, char r[])
{
    long long int length, length2, i, number, position, sign;
    float number2;

    sign = -1;   // -1 == positive number
    if (f < 0)
    {
        sign = '-';
        f *= -1;
    }

    number2 = f;
    number = f;
    length = 0;  // Size of decimal part
    length2 = 0; // Size of tenth

    /* Calculate length2 tenth part */
    while( (number2 - (float)number) != 0.0 && !((number2 - (float)number) < 0.0) )
    {
         number2 = f * (n_tu(10.0, length2 + 1));
         number = number2;

         length2++;
    }

    /* Calculate length decimal part */
    for (length = (f > 1) ? 0 : 1; f > 1; length++)
        f /= 10;

    position = length;
    length = length + 1 + length2;
    number = number2;
    if (sign == '-')
    {
        length++;
        position++;
    }

    for (i = length; i >= 0 ; i--)
    {
        if (i == (length))
            r[i] = '\0';
        else if(i == (position))
            r[i] = '.';
        else if(sign == '-' && i == 0)
            r[i] = '-';
        else
        {
            r[i] = (number % 10) + '0';
            number /=10;
        }
    }
}

Angular: How to download a file from HttpClient?

I ended up here when searching for ”rxjs download file using post”.

This was my final product. It uses the file name and type given in the server response.

import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

downloadPost(url: string, data: any) {
    return ajax({
        url: url,
        method: 'POST',
        responseType: 'blob',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/plain, */*',
            'Cache-Control': 'no-cache',
        }
    }).pipe(
        map(handleDownloadSuccess),
    );
}


handleDownloadSuccess(response: AjaxResponse) {
    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(response.response);

    const disposition = response.xhr.getResponseHeader('Content-Disposition');
    if (disposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            const filename = matches[1].replace(/['"]/g, '');
            downloadLink.setAttribute('download', filename);
        }
    }

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

What's the difference between unit, functional, acceptance, and integration tests?

This is very simple.

  1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

  2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

  3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

  4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

How to call a .NET Webservice from Android using KSOAP2?

How does your .NET Webservice look like?

I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)

And everytime I used

    Integer result = (Integer)envelope.getResponse();

to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive exception.

I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.

    [SoapRpcMethod(), WebMethod]
    public Object GetInteger1(int i)
    {
        // android device will throw exception
        return 0;
    }

    [WebMethod]
    public Object GetInteger2(int i)
    {
        // android device will get the value
        return 0;
    }

Then I changed my Android code to:

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString() method, so I use Integer.parseInt(result.toString()) to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.

Here is the full source:

private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";

public int GetInteger2() throws IOException, XmlPullParserException {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo pi = new PropertyInfo();
    pi.setName("i");
    pi.setValue(123);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    androidHttpTransport.call(SOAP_ACTION, envelope);

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    return Integer.parseInt(result.toString());
}

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

How do I compare 2 rows from the same table (SQL Server)?

OK, after 2 years it's finally time to correct the syntax:

SELECT  t1.value, t2.value
FROM    MyTable t1
JOIN    MyTable t2
ON      t1.id = t2.id
WHERE   t1.id = @id
        AND t1.status = @status1
        AND t2.status = @status2

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

Detect Android phone via Javascript / jQuery

Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

PHP:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js

Using module 'subprocess' with timeout

https://pypi.python.org/pypi/python-subprocess2 provides extensions to the subprocess module which allow you to wait up to a certain period of time, otherwise terminate.

So, to wait up to 10 seconds for the process to terminate, otherwise kill:

pipe  = subprocess.Popen('...')

timeout =  10

results = pipe.waitOrTerminate(timeout)

This is compatible with both windows and unix. "results" is a dictionary, it contains "returnCode" which is the return of the app (or None if it had to be killed), as well as "actionTaken". which will be "SUBPROCESS2_PROCESS_COMPLETED" if the process completed normally, or a mask of "SUBPROCESS2_PROCESS_TERMINATED" and SUBPROCESS2_PROCESS_KILLED depending on action taken (see documentation for full details)

How can I print the contents of an array horizontally?

If you need to pretty print an array of arrays, something like this could work: Pretty Print Array of Arrays in .NET C#

public string PrettyPrintArrayOfArrays(int[][] arrayOfArrays)
{
  if (arrayOfArrays == null)
    return "";

  var prettyArrays = new string[arrayOfArrays.Length];

  for (int i = 0; i < arrayOfArrays.Length; i++)
  {
    prettyArrays[i] = "[" + String.Join(",", arrayOfArrays[i]) + "]";
  }

  return "[" + String.Join(",", prettyArrays) + "]";
}

Example Output:

[[2,3]]

[[2,3],[5,4,3]]

[[2,3],[5,4,3],[8,9]]

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

Good font for code presentations?

I use DejaVu Sans Mono at Size 16.

UPDATE : I have switched to Envy Code R for coding and Anonymous Pro for terminal

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

jQuery add class .active on menu

this work for me :D

    function setActive() {
      aObj = document.getElementById('menu').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          var activeurl = window.location;
          $('a[href="'+activeurl+'"]').parent('li').addClass('active');
        }
      }
    }

    window.onload = setActive;

How can I permanently enable line numbers in IntelliJ?

I just hit this with IdeaVim plugin installed, where even if I set Show Line Numbers, it continued to revert to hiding them.

The (forehead-slapping-worthy) solution was:

:set nu

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

Why use multiple columns as primary keys (composite primary key)

You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.

HTML5 Form Input Pattern Currency Format

I'm wrote this price pattern without zero price.

(0\.((0[1-9]{1})|([1-9]{1}([0-9]{1})?)))|(([1-9]+[0-9]*)(\.([0-9]{1,2}))?)

Valid For:

  • 1.00
  • 1
  • 1.5
  • 0.10
  • 0.1
  • 0.01
  • 2500.00

Invalid For:

  • 0
  • 0.00
  • 0.0
  • 2500.
  • 2500.0000

Check my code online: http://regexr.com/3binj

What is the difference between PUT, POST and PATCH?

Main Difference Between PUT and PATCH Requests:

Suppose we have a resource that holds the first name and last name of a person.

If we want to change the first name then we send a put request for Update

{ "first": "Michael", "last": "Angelo" }

Here, although we are only changing the first name, with PUT request we have to send both parameters first and last.
In other words, it is mandatory to send all values again, the full payload.

When we send a PATCH request, however, we only send the data which we want to update. In other words, we only send the first name to update, no need to send the last name.

How many socket connections can a web server handle?

I think that the number of concurrent socket connections one web server can handle largely depends on the amount of resources each connection consumes and the amount of total resource available on the server barring any other web server resource limiting configuration.

To illustrate, if every socket connection consumed 1MB of server resource and the server has 16GB of RAM available (theoretically) this would mean it would only be able to handle (16GB / 1MB) concurrent connections. I think it's as simple as that... REALLY!

So regardless of how the web server handles connections, every connection will ultimately consume some resource.

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

Disable Scrolling on Body

Set height and overflow:

html, body {margin: 0; height: 100%; overflow: hidden}

http://jsfiddle.net/q99hvawt/

Python extending with - using super() Python 3 vs Python 2

  • super() (without arguments) was introduced in Python 3 (along with __class__):

    super() -> same as super(__class__, self)
    

    so that would be the Python 2 equivalent for new-style classes:

    super(CurrentClass, self)
    
  • for old-style classes you can always use:

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    

How do I count unique values inside a list

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

Neatest way to remove linebreaks in Perl

In your example, you can just go:

chomp(@lines);

Or:

$_=join("", @lines);
s/[\r\n]+//g;

Or:

@lines = split /[\r\n]+/, join("", @lines);

Using these directly on a file:

perl -e '$_=join("",<>); s/[\r\n]+//g; print' <a.txt |less

perl -e 'chomp(@a=<>);print @a' <a.txt |less

"NoClassDefFoundError: Could not initialize class" error

NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).

NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).

The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.

I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

iTerm2 keyboard shortcut - split pane navigation

Spanish ISO:

  1. ?+?+[ goes left top
  2. ?+?+] goes bottom right

Converting JSON data to Java object

Give boon a try:

https://github.com/RichardHightower/boon

It is wicked fast:

https://github.com/RichardHightower/json-parsers-benchmark

Don't take my word for it... check out the gatling benchmark.

https://github.com/gatling/json-parsers-benchmark

(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)

It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.

It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).

It also has the fastest JSON to JavaBean mode too.

It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.

Insert ellipsis (...) into HTML tag if content too wide

The following CSS only solution for truncating text on a single line works with all browers listed at http://www.caniuse.com as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}

If you need support for earlier versions of Firefox check out my answer on this other question.

How do I compare two string variables in an 'if' statement in Bash?

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash IMO.

Here are some examples Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

 if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

 if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

 if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

 if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

 if [ "$a" = "$b" ] ;then

ActiveRecord find and only return selected columns

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns

Missing Microsoft RDLC Report Designer in Visual Studio

The setup feature does not work on Visual Studio 2017 and later versions.

The extension needs to be downloaded from VS Marketplace and then installed - Link

The same applies to other extensions such as Installer Projects (used for creating executable files) - Link

What is the difference between aggregation, composition and dependency?

Aggregation and composition are almost completely identical except that composition is used when the life of the child is completely controlled by the parent.

Aggregation

Car -> Tires

The Tires can be taken off of the Car object and installed on a different one. Also, if the car gets totaled, the tires do not necessarily have to be destroyed.

Composition

Body -> Blood Cell

When the Body object is destroyed the BloodCells get destroyed with it.

Dependency

A relationship between two objects where changing one may affect the other.

Reload chart data via JSON with Highcharts

The other answers didn't work for me. I found the answer in their documentation:

http://api.highcharts.com/highcharts#Series

Using this method (see JSFiddle example):

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container'
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]        
    }]
});

// the button action
$('#button').click(function() {
    chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

ZIP Code (US Postal Code) validation

If you're doing for Canada remember that not all letters are valid

These letters are invalid: D, F, I, O, Q, or U And the letters W and Z are not used as the first letter. Also some people use an optional space after the 3rd character.

Here is a regular expression for Canadian postal code:

new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)

The last i makes it case insensitive.

How can I render a list select box (dropdown) with bootstrap?

I'm currently fighting with dropdowns and I'd like to share my experiences:

There are specific situations where <select> can't be used and must be 'emulated' with dropdown.

For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select> is not supported in input groups, it will not be rendered properly.

Or does anybody solved this already? I would be very interested on the solution.

And to make it even more complicated, you can't use so simply $(this).text() to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example: <li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li> Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.

I found two possible solutions:

1) Use $(this).html() to get content of the selected <li> element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a> so you need to play with this to extract what you need.

2) Use $(this).text() and hide the text in element in hidden span: <li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>. For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html() result like in option 1) to get what you need.

I hope it's clear and can help somebody :-)

Why doesn't RecyclerView have onItemClickListener()?

> How RecyclerView is different from Listview?

One difference is that there is LayoutManager class with RecyclerView by which you can manage your RecyclerView like-

Horizontal or Vertical scrolling by LinearLayoutManager

GridLayout by GridLayoutManager

Staggered GridLayout by StaggeredGridLayoutManager

Like for horizontal scrolling for RecyclerView-

LinearLayoutManager llm = new LinearLayoutManager(context);
llm.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(llm);

Service Reference Error: Failed to generate code for the service reference

I have encountered this problem when upgrading a VS2010 WCF+Silverlight solution in VS2015 Professional. Besides automatically upgrading from Silverlight 4 to Silverlight 5, the service reference reuse checkbox value was changed and generation failed.

TypeLoadException says 'no implementation', but it is implemented

As an addendum: this can also occur if you update a nuget package that was used to generate a fakes assembly. Say you install V1.0 of a nuget package and create a fakes assembly "fakeLibrary.1.0.0.0.Fakes". Next, you update to the newest version of the nuget package, say v1.1 which added a new method to an interface. The Fakes library is still looking for v1.0 of the library. Simply remove the fake assembly and regenerate it. If that was the issue, this will probably fix it.

Change image size with JavaScript

you can see the result here In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.

html:

<div>
<img  onmouseover="fifo()" onmouseleave="fifo()" src="your_image"   
       width="10%"  id="f" >
</div>

js file:

var b=0;
function fifo() {
       if(b==0){
            document.getElementById("f").width = "300";
           b=1;
          }
       else
          {
         document.getElementById("f").width = "100";
          b=0;
        }
   }

What port is a given program using?

If your prefer a GUI interface CurrPorts is free and works with all versions of windows. Shows ports and what process has them open.

Java: Simplest way to get last word in a string

Get the last word in Kotlin:

String.substringAfterLast(" ")

How do I configure git to ignore some files locally?

Add the following lines to the [alias] section of your .gitconfig file

ignore = update-index --assume-unchanged
unignore = update-index --no-assume-unchanged
ignored = !git ls-files -v | grep "^[[:lower:]]"

Now you can use git ignore my_file to ignore changes to the local file, and git unignore my_file to stop ignoring the changes. git ignored lists the ignored files.

This answer was gleaned from http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html.

How to embed a PDF viewer in a page?

If I'm not mistaken, the OP was asking (although later accepted a .js solution) whether Google's embedded PDF display server will display a PDF on his own website.

So, one and a half years later: yes, it will.

See http://googlesystem.blogspot.ca/2009/09/embeddable-google-document-viewer.html. Also, see https://docs.google.com/viewer, and plug in the URL of the file you want to display.

Edit: Re-reading, OP was asking for solutions that don't use iFrames. I don't think that's possible with Google's viewer.

Change Active Menu Item on Page Scroll?

Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.

jQuery(document).ready(function(jQuery) {            
            var topMenu = jQuery("#top-menu"),
                offset = 40,
                topMenuHeight = topMenu.outerHeight()+offset,
                // All list items
                menuItems =  topMenu.find('a[href*="#"]'),
                // Anchors corresponding to menu items
                scrollItems = menuItems.map(function(){
                  var href = jQuery(this).attr("href"),
                  id = href.substring(href.indexOf('#')),
                  item = jQuery(id);
                  //console.log(item)
                  if (item.length) { return item; }
                });

            // so we can get a fancy scroll animation
            menuItems.click(function(e){
              var href = jQuery(this).attr("href"),
                id = href.substring(href.indexOf('#'));
                  offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
              jQuery('html, body').stop().animate({ 
                  scrollTop: offsetTop
              }, 300);
              e.preventDefault();
            });

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

               // Get id of current scroll item
               var cur = scrollItems.map(function(){
                 if (jQuery(this).offset().top < fromTop)
                   return this;
               });

               // Get the id of the current element
               cur = cur[cur.length-1];
               var id = cur && cur.length ? cur[0].id : "";               

               menuItems.parent().removeClass("active");
               if(id){
                    menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
               }

            })
        })

Basically i replaced

menuItems = topMenu.find("a"),

by

menuItems =  topMenu.find('a[href*="#"]'),

To match all links with anchor somewhere, and changed all that what was necessary to make it work with this

See it in action on jsfiddle

'too many values to unpack', iterating over a dict. key=>string, value=>list

For Python 3.x iteritems has been removed. Use items instead.

for field, possible_values in fields.items():
    print(field, possible_values)

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

requestFeature() must be called before adding content

I know it's over a year old, but calling requestFeature() never solved my problem. In fact I don't call it at all.

It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.

AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog() to update that view.

Another alternative is to leverage AsyncTask for dialogs.

A final solution that I used is below:

public class CustomDialog extends AlertDialog {

   private View content;

   public CustomDialog(Context context) {
       super(context);

       LayoutInflater li = LayoutInflater.from(context);
       content = li.inflate(R.layout.custom_view, null);

       setUpAdditionalStuff(); // do more view cleanup
       setView(content);           
   }

   private void setUpAdditionalStuff() {
       // ...
   }

   // Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method  
   public void prepare() {
       setTitle(R.string.custom_title);
       setIcon( getIcon() );
       // ...
   }
}

* Some Additional notes:

  1. Don't rely on hiding the title. There is often an empty space despite the title not being set.
  2. Don't try to build your own View with header footer and middle view. The header, as stated above, may not be entirely hidden despite requesting FEATURE_NO_TITLE.
  3. Don't heavily style your content view with color attributes or text size. Let the dialog handle that, other wise you risk putting black text on a dark blue dialog because the vendor inverted the colors.

How to disable/enable select field using jQuery?

You would like to use code like this:

<form>
  <input type="checkbox" id="pizza" name="pizza" value="yes">
  <label for="pizza">I would like to order a</label>
  <select id="pizza_kind" name="pizza_kind">
    <option>(choose one)</option>
    <option value="margaritha">Margaritha</option>
    <option value="hawai">Hawai</option>
  </select>
  pizza.
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
  var update_pizza = function () {
    if ($("#pizza").is(":checked")) {
        $('#pizza_kind').prop('disabled', false);
    }
    else {
        $('#pizza_kind').prop('disabled', 'disabled');
    }
  };
  $(update_pizza);
  $("#pizza").change(update_pizza);
</script>

?Here is working example

Jquery mouseenter() vs mouseover()

You see the behavior when your target element contains child elements:

http://jsfiddle.net/ZCWvJ/7/

Each time your mouse enters or leaves a child element, mouseover is triggered, but not mouseenter.

_x000D_
_x000D_
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
  var el = $("#" + e.type);_x000D_
  var n = +el.text();_x000D_
  el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
  padding: 0 20px 20px 0;_x000D_
  background-color: #eee;_x000D_
  margin-bottom: 10px;_x000D_
  width: 90px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
  float: left;_x000D_
  margin: 20px 0 0 20px;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

Reading a UTF8 CSV file with Python

The .encode method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs module in the standard library and codecs.open in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:

import csv

def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
  print field1, field2, field3 

PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv module level), of the form line.decode('whateverweirdcodec').encode('utf-8') -- but probably you can just use the name of your existing encoding in the yield line in my code above, instead of 'utf-8', as csv is actually going to be just fine with ISO-8859-* encoded bytestrings.

Firebase (FCM) how to get token

You can use the following in Firebase (FCM) to get the token:

FirebaseInstanceId.getInstance().getToken();

What's the use of session.flush() in Hibernate

Calling EntityManager#flush does have side-effects. It is conveniently used for entity types with generated ID values (sequence values): such an ID is available only upon synchronization with underlying persistence layer. If this ID is required before the current transaction ends (for logging purposes for instance), flushing the session is required.

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

The request failed or the service did not respond in a timely fashion?

For me a simple windows update fixed it, I wish I tried it before.

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Above answers are excellent. You can look at the following full code example so that you could exactly know how to use

_x000D_
_x000D_
   var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
   app.controller('usersCtrl', function($scope, $http) {_x000D_
     $http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
        console.log(response.data)_x000D_
_x000D_
         $scope.users = response.data;_x000D_
          $scope.setKey = function (userId){_x000D_
              alert(userId)_x000D_
              if(localStorage){_x000D_
                localStorage.setItem("userId", userId)_x000D_
              } else {_x000D_
                alert("No support of localStorage")_x000D_
                return_x000D_
              }_x000D_
          }//function closed  _x000D_
     });_x000D_
   });
_x000D_
      #header{_x000D_
       color: green;_x000D_
       font-weight: bold;_x000D_
      }
_x000D_
  <!DOCTYPE html>_x000D_
  <html>_x000D_
  <head>_x000D_
    <title>HyperCrud</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <!-- NAVBAR STARTS -->_x000D_
      <nav class="navbar navbar-default navbar-fixed-top">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">HyperCrud</a>_x000D_
          </div>_x000D_
          <div id="navbar" class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="/">Home</a></li>_x000D_
              <li><a href="/about/">About</a></li>_x000D_
              <li><a href="/contact/">Contact</a></li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="/qAlarm/details/">qAlarm &raquo;</a></li>_x000D_
                  <li><a href="/YtEdit/details/">YtEdit &raquo;</a></li>_x000D_
                  <li><a href="/GWeather/details/">GWeather &raquo;</a></li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li><a href="/WadStore/details/">WadStore &raquo;</a></li>_x000D_
                  <li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="/login/">Login</a></li>_x000D_
              <li><a href="/register/">Register</a></li>_x000D_
              <li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
      <!--NAVBAR ENDS-->_x000D_
  <br>_x000D_
  <br>_x000D_
_x000D_
  <div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
    <div class="row">_x000D_
     <div class="col-sm-12 col-md-12">_x000D_
      <center>_x000D_
        <h1 id="header"> Users </h1>_x000D_
      </center>_x000D_
     </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row" >_x000D_
        <!--ITERATING USERS LIST-->_x000D_
      <div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
        <div class="thumbnail">_x000D_
          <center>_x000D_
           <img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
           <hr>_x000D_
          </center>_x000D_
          <div class="caption">_x000D_
           <center>_x000D_
             <h3>{{user.name}}</h3>_x000D_
             <p>{{user.email}}</p>_x000D_
             <p>+91 {{user.phone}}</p>_x000D_
             <p>{{user.address.city}}</p>_x000D_
            </center>_x000D_
          </div>_x000D_
            <div class="caption">_x000D_
                <a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
                <a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
            </div>_x000D_
        </div>_x000D_
      </div>_x000D_
_x000D_
        <div class="col-sm-6 col-md-4">_x000D_
          <div class="thumbnail">_x000D_
            <a href="/regiser/">_x000D_
             <img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
    </div>_x000D_
      <!--ROW ENDS-->_x000D_
  </div>_x000D_
_x000D_
_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

openCV video saving in python

Please make sure to set correct width and height. You can set it like bellow

cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

Authentication failed to bitbucket

After fighting with this for a long time, it looks like I found something that seems to work. I was optimizing the urls to not include the username (keep it as generic as possible), but the authentication dialog kept popping up:

enter image description here

I tried everything that came into mind, such as:

  1. Enable and disable MFA (Multi Factor Authentication)
  2. Create app passwords (again, with and without MFA enabled)

No matter what tools I used (including SourceTree), nothing worked. The server kept returning: "Create an app password"

Basically you must

  1. Use the url including the username (e.g. https://[email protected]/...)
  2. Use an app password created in bitbucket

Would be so nice if the server would have returned this in the response instead of suggesting to use an app password...

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

Not receiving Google OAuth refresh token

For me I was trying out CalendarSampleServlet provided by Google. After 1 hour the access_key times out and there is a redirect to a 401 page. I tried all the above options but they didn't work. Finally upon checking the source code for 'AbstractAuthorizationCodeServlet', I could see that redirection would be disabled if credentials are present, but ideally it should have checked for refresh token!=null. I added below code to CalendarSampleServlet and it worked after that. Great relief after so many hours of frustration . Thank God.

if (credential.getRefreshToken() == null) {
    AuthorizationCodeRequestUrl authorizationUrl = authFlow.newAuthorizationUrl();
    authorizationUrl.setRedirectUri(getRedirectUri(req));
    onAuthorization(req, resp, authorizationUrl);
    credential = null;
}

How do I change JPanel inside a JFrame on the fly?

I was having exactly the same problem!! Increadible!! The solution I found was:

  1. Adding all the components (JPanels) to the container;
  2. Using the setVisible(false) method to all of them;
  3. On user action, setting setVisible(true) to the panel I wanted to show.
// Hiding all components (JPanels) added to a container (ex: another JPanel)
for (Component component : this.container.getComponents()) {
      component.setVisible(false);
}
// Showing only the selected JPanel, the one user wants to see
panel.setVisible(true);

No revalidate(), no validate(), no CardLayout needed.

How do you clear Apache Maven's cache?

Delete the artifacts (or the full local repo) from c:\Users\<username>\.m2\repository by hand.

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

The PowerShell -and conditional operator

The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

css absolute position won't work with margin-left:auto margin-right: auto

I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

Check if all elements in a list are identical

This is another option, faster than len(set(x))==1 for long lists (uses short circuit)

def constantList(x):
    return x and [x[0]]*len(x) == x

Checking if a number is a prime number in Python

def is_prime(x):
    n = 2
    if x < n:
        return False
    else:    
        while n < x:
           print n
            if x % n == 0:
                return False
                break
            n = n + 1
        else:
            return True

Reset select value to default

One nice clean way is to add a data-default attribute to the select

<select id="my_select" data-default="b">
...
</select>

An then the code is really simple:

$("#reset").on("click", function () {
    var $select = $('#my_select');
    $select.val($select.data('default'));
});

Live example: http://jsfiddle.net/T8sCf/7/

What is %0|%0 and how does it work?

What it is:

%0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).

How this works:

%0 refers to the command used to run the current program. For example, script.bat

A pipe | symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.

Expanding the example, %0|%0 could mean script.bat|script.bat. This runs itself again, but also creating another process to run the same program again (with no input).

How do I create a folder in VB if it doesn't exist?

(imports System.IO)

if Not Directory.Exists(Path) then
  Directory.CreateDirectory(Path)
end if

Adding attribute in jQuery

use this code <script> $('#someid').attr('disabled,'true'); </script>

Is CSS Turing complete?

You can encode Rule 110 in CSS3, so it's Turing-complete so long as you consider an appropriate accompanying HTML file and user interactions to be part of the “execution” of CSS. A pretty good implementation is available, and another implementation is included here:

_x000D_
_x000D_
body {_x000D_
    -webkit-animation: bugfix infinite 1s;_x000D_
    margin: 0.5em 1em;_x000D_
}_x000D_
@-webkit-keyframes bugfix { from { padding: 0; } to { padding: 0; } }_x000D_
_x000D_
/*_x000D_
 * 111 110 101 100 011 010 001 000_x000D_
 *  0   1   1   0   1   1   1   0_x000D_
 */_x000D_
_x000D_
body > input {_x000D_
    -webkit-appearance: none;_x000D_
    display: block;_x000D_
    float: left;_x000D_
    border-right: 1px solid #ddd;_x000D_
    border-bottom: 1px solid #ddd;_x000D_
    padding: 0px 3px;_x000D_
    margin: 0;_x000D_
    font-family: Consolas, "Courier New", monospace;_x000D_
    font-size: 7pt;_x000D_
}_x000D_
body > input::before {_x000D_
    content: "0";_x000D_
}_x000D_
_x000D_
p {_x000D_
    font-family: Verdana, sans-serif;_x000D_
    font-size: 9pt;_x000D_
    margin-bottom: 0.5em;_x000D_
}_x000D_
_x000D_
body > input:nth-of-type(-n+30) { border-top: 1px solid #ddd; }_x000D_
body > input:nth-of-type(30n+1) { border-left: 1px solid #ddd; clear: left; }_x000D_
_x000D_
body > input::before { content: "0"; }_x000D_
_x000D_
body > input:checked::before { content: "1"; }_x000D_
body > input:checked { background: #afa !important; }_x000D_
_x000D_
_x000D_
input:not(:checked) +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input::before {_x000D_
    content: "1";_x000D_
}_x000D_
input:not(:checked) +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input {_x000D_
    background: #fa0;_x000D_
}_x000D_
_x000D_
_x000D_
input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input::before {_x000D_
    content: "1";_x000D_
}_x000D_
input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input {_x000D_
    background: #fa0;_x000D_
}_x000D_
_x000D_
_x000D_
input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input::before {_x000D_
    content: "1";_x000D_
}_x000D_
input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input {_x000D_
    background: #fa0;_x000D_
}_x000D_
_x000D_
input:checked + input:checked + input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input::before {_x000D_
    content: "0";_x000D_
}_x000D_
input:checked + input:checked + input:checked +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input {_x000D_
    background: #fff;_x000D_
}_x000D_
_x000D_
input:not(:checked) + input:not(:checked) + input:not(:checked) +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input::before {_x000D_
    content: "0";_x000D_
}_x000D_
input:not(:checked) + input:not(:checked) + input:not(:checked) +_x000D_
        *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
        input {_x000D_
    background: #fff;_x000D_
}_x000D_
_x000D_
body > input:nth-child(30n) { display: none !important; }_x000D_
body > input:nth-child(30n) + label { display: none !important; }
_x000D_
<p><a href="http://en.wikipedia.org/wiki/Rule_110">Rule 110</a> in (webkit) CSS, proving Turing-completeness.</p>_x000D_
_x000D_
<!-- A total of 900 checkboxes required -->_x000D_
<input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/>
_x000D_
_x000D_
_x000D_

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

How to set image to UIImage

Just Follow This

UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Create Windows service from executable

these extras prove useful.. need to be executed as an administrator

sc create  <service_name> binpath=<binary_path>
sc stop    <service_name>
sc queryex <service_name>
sc delete  <service_name>

If your service name has any spaces, enclose in "quotes".

Does Python have a ternary conditional operator?

From the documentation:

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

New since version 2.5.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:

split -l 100000 database.sql database-

It will give files like:

database-aaa
database-aab
database-aac
...

Gradle task - pass arguments to Java application

Sorry for answering so late.

I figured an answer alike to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorythm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

And invoke like:

gradle run -Pmyargs=-d,s

Is there a way to collapse all code blocks in Eclipse?

Right click on the circles +/- sign and under Foldings select Collapse All

Android EditText for password with android:hint

If you set

android:inputType="textPassword"

this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use

android:password="true"

property which allows you to enter any type of password without any restriction.

If you want to provide hint use

android:hint="hint text goes here"

example:

android:hint="password"

Request Permission for Camera and Library in iOS 10 - Info.plist

I wrote an extension that takes into account all possible cases:

  • If access is allowed, then the code onAccessHasBeenGranted will be run.
  • If access is not determined, then requestAuthorization(_:) will be called.
  • If the user has denied your app photo library access, then the user will be shown a window offering to go to settings and allow access. In this window, the "Cancel" and "Settings" buttons will be available to him. When he presses the "settings" button, your application settings will open.

Usage example:

PHPhotoLibrary.execute(controller: self, onAccessHasBeenGranted: {
    // access granted... 
})

Extension code:

import Photos
import UIKit

public extension PHPhotoLibrary {

   static func execute(controller: UIViewController,
                       onAccessHasBeenGranted: @escaping () -> Void,
                       onAccessHasBeenDenied: (() -> Void)? = nil) {

      let onDeniedOrRestricted = onAccessHasBeenDenied ?? {
         let alert = UIAlertController(
            title: "We were unable to load your album groups. Sorry!",
            message: "You can enable access in Privacy Settings",
            preferredStyle: .alert)
         alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
         alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
               UIApplication.shared.open(settingsURL)
            }
         }))
         controller.present(alert, animated: true)
      }

      let status = PHPhotoLibrary.authorizationStatus()
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAccessHasBeenGranted)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAccessHasBeenGranted()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   }

}

private func onNotDetermined(_ onDeniedOrRestricted: @escaping (()->Void), _ onAuthorized: @escaping (()->Void)) {
   PHPhotoLibrary.requestAuthorization({ status in
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAuthorized)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAuthorized()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   })
}

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

MySQL Cannot Add Foreign Key Constraint

I had set one field as "Unsigned" and other one not. Once I set both columns to Unsigned it worked.

Is it possible to return empty in react render function?

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this:

return (null);

Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false, you can return any of these values false, null, undefined, true. As per DOC:

booleans (true/false), null, and undefined are valid children, they will be Ignored means they simply don’t render.

All these JSX expressions will render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Example:

Only odd values will get rendered, because for even values we are returning null.

_x000D_
_x000D_
const App = ({ number }) => {_x000D_
  if(number%2) {_x000D_
    return (_x000D_
      <div>_x000D_
        Number: {number}_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
  _x000D_
  return (null);           //===> notice here, returning null for even values_x000D_
}_x000D_
_x000D_
const data = [1,2,3,4,5,6];_x000D_
_x000D_
ReactDOM.render(_x000D_
  <div>_x000D_
    {data.map(el => <App key={el} number={el} />)}_x000D_
  </div>,_x000D_
  document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='app' />
_x000D_
_x000D_
_x000D_

How to call a SOAP web service on Android

It's true that due to it's overhead SOAP is not the best choice for data exchange with mobile devices. However, you might find yourself in situation in which you do not control the format of server output.

So, if you have to stick with SOAP, there is a kSOAP2 library patched for Android here:
http://code.google.com/p/ksoap2-android/

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

How to pass a parameter to routerLink that is somewhere inside the URL?

In your particular example you'd do the following routerLink:

[routerLink]="['user', user.id, 'details']"

To do so in a controller, you can inject Router and use:

router.navigate(['user', user.id, 'details']);

More info in the Angular docs Link Parameters Array section of Routing & Navigation

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

move div with CSS transition

transition-property:width;

This should work. you have to have browser dependent code

Get month and year from a datetime in SQL Server 2005

select 
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)

Disable html5 video autoplay

I'd remove the autoplay attribute, since if the browser encounters it, it autoplays!

autoplay is a HTML boolean attribute, but be aware that the values true and false are not allowed. To represent a false value, you must omit the attribute.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Also, the type goes inside the source, like this:

<video width="640" height="480" controls preload="none">
   <source src="http://example.com/mytestfile.mp4" type="video/mp4">
   Your browser does not support the video tag.
</video>

References:

Java converting int to hex and back again

It's worth mentioning that Java 8 has the methods Integer.parseUnsignedInt and Long.parseUnsignedLong that does what you wanted, specifically:

Integer.parseUnsignedInt("ffff8000",16) == -32768

The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

Since printArea is a jQuery plugin it is not included in jquery.d.ts.

You need to create a jquery.printArea.ts definition file.

If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

SQL Server - find nth occurrence in a string

DECLARE @str AS VARCHAR(100)
SET @str='1,2  , 3,   4,   5,6'
SELECT COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[1]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[2]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[3]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[4]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[5]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[6]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[7]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[8]', 'varchar(128)')), ''),
       COALESCE(LTRIM(CAST(('<X>'+REPLACE(@str,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[9]', 'varchar(128)')), '')

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

ImportError: No module named 'selenium'

Your IDE might be pointing to a different installation of Python than where Selenium is installed.

I'm using Eclipse and when I ran 'quick auto-configure' under:

Preferences > PyDev > Interpreters > Python Interpreter

it pointed to a different version of Python than where pip or easy_install actually installed it.

Selenium worked from the Terminal so I determined which version of python my Terminal was using by running this:

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

then had Eclipse point to that same location, which for me on my 10.11 Mac was here:

/Library/Frameworks/Python.framework/Versions/Current/bin/python2.7/

You can run "Advanced Auto-Config" as well to see all of the installed versions of python and select the one you want to use. When I selected that same location using "Advanced Auto-Config" it finally showed me the Selenium folder as it went through the configuration steps.

Is there a standardized method to swap two variables in Python?

That is the standard way to swap two variables, yes.

How to replace master branch in Git, entirely, from another branch?

You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks'.

In that case you can:
git remote --show may not work. (Make a git remote show to check how your remote is declared within your local repo. I will assume 'origin')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin' button on GitHub and set the 'Default Branch' to something other than 'master', then put it back afterwards")

git branch -m master master-old  # rename master on local
git push origin :master          # delete master on remote
git push origin master-old       # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master           # create master on remote

But again:

  • if other users try to pull while master is deleted on remote, their pulls will fail ("no such ref on remote")
  • when master is recreated on remote, a pull will attempt to merge that new master on their local (now old) master: lots of conflicts. They actually need to reset --hard their local master to the remote/master branch they will fetch, and forget about their current master.

How to change Navigation Bar color in iOS 7?

This question and these answers are helpful. With them I was able to set my desired dark blue navigationBar color with white title and button text.

But I also needed to change the clock, carrier, signal strength, etc. to white. Black just didn't contrast enough with the dark blue.

I may have overlooked that solution in one of the previous answers, but I was able to make that change by adding this line to my top level viewController's viewDidLoad:

[self.navigationController.navigationBar setBarStyle:UIStatusBarStyleLightContent];

awk without printing newline

I guess many people are entering in this question looking for a way to avoid the new line in awk. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!

In awk, print automatically inserts a ORS after printing. ORS stands for "output record separator" and defaults to the new line. So whenever you say print "hi" awk prints "hi" + new line.

This can be changed in two different ways: using an empty ORS or using printf.

Using an empty ORS

awk -v ORS= '1' <<< "hello
man"

This returns "helloman", all together.

The problem here is that not all awks accept setting an empty ORS, so you probably have to set another record separator.

awk -v ORS="-" '{print ...}' file

For example:

awk -v ORS="-" '1' <<< "hello
man"

Returns "hello-man-".

Using printf (preferable)

While print attaches ORS after the record, printf does not. Thus, printf "hello" just prints "hello", nothing else.

$ awk 'BEGIN{print "hello"; print "bye"}'
hello
bye
$ awk 'BEGIN{printf "hello"; printf "bye"}'
hellobye

Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use END {print ""} so a new line will be printed after all the processing.

$ seq 5 | awk '{printf "%s", $0}'
12345$
#    ^ prompt here

$ seq 5 | awk '{printf "%s", $0} END {print ""}'
12345

Why do I always get the same sequence of random numbers with rand()?

If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:

"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".

Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.

Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.

Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.

Execute raw SQL using Doctrine 2

You can't, Doctrine 2 doesn't allow for raw queries. It may seem like you can but if you try something like this:

$sql = "SELECT DATE_FORMAT(whatever.createdAt, '%Y-%m-%d') FORM whatever...";
$em = $this->getDoctrine()->getManager();
$em->getConnection()->exec($sql);

Doctrine will spit an error saying that DATE_FORMAT is an unknown function.

But my database (mysql) does know that function, so basically what is hapening is Doctrine is parsing that query behind the scenes (and behind your back) and finding an expression that it doesn't understand, considering the query to be invalid.

So if like me you want to be able to simply send a string to the database and let it deal with it (and let the developer take full responsibility for security), forget it.

Of course you could code an extension to allow that in some way or another, but you just as well off using mysqli to do it and leave Doctrine to it's ORM buisness.