Programs & Examples On #aar

Create aar file in Android Studio

After following the first and second steps mentioned in the hcpl's answer in the same thread, we added , '*.aar'], dir: 'libs' in the our-android-app-project-based-on-gradle/app/build.gradle file as shown below:

...

dependencies {
       implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

...

Our gradle version is com.android.tools.build:gradle:3.2.1

Adding local .aar files to Gradle build using "flatDirs" is not working

If you already use Kotlin Gradle DSL, the alternative to using it this way:

Here's my project structure

|-root
|----- app
|--------- libs // I choose to store the aar here
|-------------- my-libs-01.aar
|-------------- my-libs-02.jar
|--------- build.gradle.kts // app module gradle
|----- common-libs // another aar folder/directory
|----------------- common-libs-01.aar
|----------------- common-libs-02.jar
|----- build.gradle.kts // root gradle

My app/build.gradle.kts

  1. Using simple approach with fileTree
// android related config above omitted...

dependencies {
    // you can do this to include everything in the both directory
    // Inside ./root/common-libs & ./root/app/libs
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.aar"))))
    implementation(fileTree(mapOf("dir" to "../common-libs", "include" to listOf("*.jar", "*.aar"))))
}
  1. Using same approach like fetching from local / remote maven repository with flatDirs
// android related config above omitted...

repositories {
    flatDir {
        dirs = mutableSetOf(File("libs"), File("../common-libs") 
    }
}

dependencies {
   implementation(group = "", name = "my-libs-01", ext = "aar")
   implementation(group = "", name = "my-libs-02", ext = "jar")

   implementation(group = "", name = "common-libs-01", ext = "aar")
   implementation(group = "", name = "common-libs-02", ext = "jar")
}

The group was needed, due to its mandatory (not optional/has default value) in kotlin implementation, see below:

// Filename: ReleaseImplementationConfigurationAccessors.kt
package org.gradle.kotlin.dsl

fun DependencyHandler.`releaseImplementation`(
    group: String,
    name: String,
    version: String? = null,
    configuration: String? = null,
    classifier: String? = null,
    ext: String? = null,
    dependencyConfiguration: Action<ExternalModuleDependency>? = null
)

Disclaimer: The difference using no.1 & flatDirs no.2 approach, I still don't know much, you might want to edit/comment to this answer.

References:

  1. https://stackoverflow.com/a/56828958/3763032
  2. https://github.com/gradle/gradle/issues/9272

How to convert AAR to JAR

For those, who want to do it automatically, I have wrote a little two-lines bash script which does next two things:

  1. Looks for all *.aar files and extracts classes.jar from them
  2. Renames extracted classes.jar to be like the aar but with a new extension

    find . -name '*.aar' -exec sh -c 'unzip -d `dirname {}` {} classes.jar' \;
    find . -name '*.aar' -exec sh -c 'mv `dirname {}`/classes.jar `echo {} | sed s/aar/jar/g`' \;
    

That's it!

jQuery add required to input fields

Should not enclose true with double quote " " it should be like

$(document).ready(function() {            
   $('input').attr('required', true);   
});

Also you can use prop

jQuery(document).ready(function() {            
   $('input').prop('required', true);   
}); 

Instead of true you can try required. Such as

$('input').prop('required', 'required');

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

invalid byte sequence for encoding "UTF8"

You can replace the backslash character with, for example a pipe character, with sed.

sed -i -- 's/\\/|/g' filename.txt

How do I create a file and write to it?

Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.


First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.

  • Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
  • The rename method didn't work consistently across platforms.
  • There was no real support for symbolic links.
  • More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
  • Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
  • It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.


We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

Here's an example (simplified):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

Another example (append):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

Simplified example (Java 8 or up):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

Another example (append):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.

how to query LIST using linq

var persons = new List<Person>
    {
        new Person {ID = 1, Name = "jhon", Salary = 2500},
        new Person {ID = 2, Name = "Sena", Salary = 1500},
        new Person {ID = 3, Name = "Max", Salary = 5500},
        new Person {ID = 4, Name = "Gen", Salary = 3500}
    };

var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
    acertainperson.Name, acertainperson.Salary);

jhon: 2500 points

var doingprettywell = persons.Where(p => p.Salary > 2000);
            foreach (var person in doingprettywell)
            {
                Console.WriteLine("{0}: {1} points",
                    person.Name, person.Salary);
            }

jhon: 2500 points
Max: 5500 points
Gen: 3500 points

        var astupidcalc = from p in persons
                          where p.ID > 2
                          select new
                                     {
                                         Name = p.Name,
                                         Bobos = p.Salary*p.ID,
                                         Bobotype = "bobos"
                                     };
        foreach (var person in astupidcalc)
        {
            Console.WriteLine("{0}: {1} {2}",
                person.Name, person.Bobos, person.Bobotype);
        }

Max: 16500 bobos
Gen: 14000 bobos

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

In postgresql all foreign keys must reference a unique key in the parent table, so in your bar table you must have a unique (name) index.

See also http://www.postgresql.org/docs/9.1/static/ddl-constraints.html#DDL-CONSTRAINTS-FK and specifically:

Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint.

Emphasis mine.

Remove plot axis values

@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:

x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)

How do I remove the title bar from my app?

The easiest way: Just double click on this button and choose "NoTitleBar" ;)

Click here to see where it is :)

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

What is the difference between "is None" and "== None"

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

What is the worst real-world macros/pre-processor abuse you've ever come across?

#include <iostream>
#define public_static_void_main(x) int main()
#define System_out_println(x) std::cout << x << std::endl

public_static_void_main(String[] args) {
  System_out_println("Hello World!");
}

How to change current Theme at runtime in Android

This is what i have created for Material Design. May it will helpful you.

Have a look for MultipleThemeMaterialDesign

How to know if a Fragment is Visible?

Both isVisible() and isAdded() return true as soon as the Fragment is created, and not even actually visible. The only solution that actually works is:

if (isAdded() && isVisible() && getUserVisibleHint()) {
    // ... do your thing
}

This does the job. Period.

NOTICE: getUserVisibleHint() is now deprecated. be careful.

Update GCC on OSX

If you install macports you can install gcc select, and then choose your gcc version.

/opt/local/bin/port install gcc_select

To see your versions use

port select --list gcc

To select a version use

sudo port select --set gcc gcc40

Java 8 Lambda Stream forEach with multiple statements

You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

entryList.forEach(e->e.setTempId(tempId));

List<Entry> updatedEntries = entryList.stream()
  .map(e->entityManager.update(entry, entry.getId()))
  .collect(toList());

Angular.js How to change an elements css class on click and to remove all others

have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?

    <span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
    <span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Change httpd.conf file as follows:

from

<Directory />
    AllowOverride none
    Require all denied
</Directory>

to

<Directory />
    AllowOverride none
    Require all granted
</Directory>

How to remove numbers from a string?

You can use .match && join() methods. .match() returns an array and .join() makes a string

function digitsBeGone(str){
  return str.match(/\D/g).join('')
}

PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

php return 500 error but no error log

Be sure your file permissions are correct. If apache doesn't have permission to read the file then it can't write to the log.

How to enumerate an enum with String type?

On Swift, enum types can be accessed like EnumType.Case:

let tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)

Most of the time you're only going to use enum types when you have a few options to work with, and know exactly what you're going to do on each one.

It wouldn't make much sense to use the for-in structure when working with enum types.

You can do this, for instance:

func sumNumbers(numbers : Int...) -> Int {
    var sum = 0

    for number in numbers{
        sum += number
    }

    return sum
}

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

Using $_POST to get select option value from HTML

Depends on if the form that the select is contained in has the method set to "get" or "post".

If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].

If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].

To store it into a variable you would:

$option = $_POST['taskOption']

A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.

Why do people write #!/usr/bin/env python on the first line of a Python script?

This is a shell convention that tells the shell which program can execute the script.

#!/usr/bin/env python

resolves to a path to the Python binary.

How do you set a default value for a MySQL Datetime column?

MySQL 5.6 has fixed this problem.

ALTER TABLE mytable CHANGE mydate datetime NOT NULL DEFAULT 'CURRENT_TIMESTAMP'

Best data type to store money values in MySQL

Multiplies 10000 and stores as BIGINT, like "Currency" in Visual Basic and Office. See https://msdn.microsoft.com/en-us/library/office/gg264338.aspx

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

How to write file in UTF-8 format?

This works for me. :)

$f=fopen($filename,"w"); 
# Now UTF-8 - Add byte order mark 
fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
fwrite($f,$content); 
fclose($f); 

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

AddRange to a Collection

The C5 Generic Collections Library classes all support the AddRange method. C5 has a much more robust interface that actually exposes all of the features of its underlying implementations and is interface-compatible with the System.Collections.Generic ICollection and IList interfaces, meaning that C5's collections can be easily substituted as the underlying implementation.

Filter object properties by key in ES6

The answers here are definitely suitable but they are a bit slow because they require looping through the whitelist for every property in the object. The solution below is much quicker for large datasets because it only loops through the whitelist once:

const data = {
  allowed1: 'blah',
  allowed2: 'blah blah',
  notAllowed: 'woah',
  superSensitiveInfo: 'whooooah',
  allowed3: 'bleh'
};

const whitelist = ['allowed1', 'allowed2', 'allowed3'];

function sanitize(data, whitelist) {
    return whitelist.reduce(
      (result, key) =>
        data[key] !== undefined
          ? Object.assign(result, { [key]: data[key] })
          : result,
      {}
    );
  }

  sanitize(data, whitelist)

Convert decimal to binary in python

You can also use a function from the numpy module

from numpy import binary_repr

which can also handle leading zeros:

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.

How to check the multiple permission at single request in Android M?

As said earlier, currently every permission group has own permission dialog which must be called separately.

You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.

Here is a working example link, may be useful for someone.

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.

What's the algorithm to calculate aspect ratio?

You can always start by making a lookup table based on common aspect ratios. Check https://en.wikipedia.org/wiki/Display_aspect_ratio Then you can simply do the division

For real life problems, you can do something like below

let ERROR_ALLOWED = 0.05
let STANDARD_ASPECT_RATIOS = [
  [1, '1:1'],
  [4/3, '4:3'],
  [5/4, '5:4'],
  [3/2, '3:2'],
  [16/10, '16:10'],
  [16/9, '16:9'],
  [21/9, '21:9'],
  [32/9, '32:9'],
]
let RATIOS = STANDARD_ASPECT_RATIOS.map(function(tpl){return tpl[0]}).sort()
let LOOKUP = Object()
for (let i=0; i < STANDARD_ASPECT_RATIOS.length; i++){
  LOOKUP[STANDARD_ASPECT_RATIOS[i][0]] = STANDARD_ASPECT_RATIOS[i][1]
}

/*
Find the closest value in a sorted array
*/
function findClosest(arrSorted, value){
  closest = arrSorted[0]
  closestDiff = Math.abs(arrSorted[0] - value)
  for (let i=1; i<arrSorted.length; i++){
    let diff = Math.abs(arrSorted[i] - value)
    if (diff < closestDiff){
      closestDiff = diff
      closest = arrSorted[i]
    } else {
      return closest
    }
  }
  return arrSorted[arrSorted.length-1]
}

/*
Estimate the aspect ratio based on width x height (order doesn't matter)
*/
function estimateAspectRatio(dim1, dim2){
  let ratio = Math.max(dim1, dim2) / Math.min(dim1, dim2)
  if (ratio in LOOKUP){
    return LOOKUP[ratio]
  }

  // Look by approximation
  closest = findClosest(RATIOS, ratio)
  if (Math.abs(closest - ratio) <= ERROR_ALLOWED){
    return '~' + LOOKUP[closest]
  }

  return 'non standard ratio: ' + Math.round(ratio * 100) / 100 + ':1'
}

Then you simply give the dimensions in any order

estimateAspectRatio(1920, 1080) // 16:9
estimateAspectRatio(1920, 1085) // ~16:9
estimateAspectRatio(1920, 1150) // non standard ratio: 1.65:1
estimateAspectRatio(1920, 1200) // 16:10
estimateAspectRatio(1920, 1220) // ~16:10

Saving ssh key fails

For windows use enter button 3 times

Enter file in which to save the key (/c/Users/Rupesh/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again:

its work for me...

Python popen command. Wait until the command is finished

wait() works fine for me. The subprocesses p1, p2 and p3 are executed at the same. Therefore, all processes are done after 3 seconds.

import subprocess

processes = []

p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)

processes.append(p1)
processes.append(p2)
processes.append(p3)

for p in processes:
    if p.wait() != 0:
        print("There was an error")

print("all processed finished")

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

how to open a url in python

I think this is the easy way to open a URL using this function

webbrowser.open_new_tab(url)

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

Angular 2 Sibling Component Communication

Behaviour subjects. I wrote a blog about that.

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private noId = new BehaviorSubject<number>(0); 
  defaultId = this.noId.asObservable();

newId(urlId) {
 this.noId.next(urlId); 
 }

In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.

So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.

For example, I get the id from the URL and update the noid from the behavior subject.

public getId () {
  const id = +this.route.snapshot.paramMap.get('id'); 
  return id; 
}

ngOnInit(): void { 
 const id = +this.getId ();
 this.taskService.newId(id) 
}

And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:

delete(task: Task): void { 
  //we save the id , cuz after the delete function, we  gonna lose it 
  const oldId = task.id; 
  this.taskService.deleteTask(task) 
      .subscribe(task => { //we call the defaultId function from task.service.
        this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task 
                 .subscribe(urlId => {
            this.urlId = urlId ;
                  if (oldId == urlId ) { 
                // Location.call('/home'); 
                this.router.navigate(['/home']); 
              } 
          }) 
    }) 
}

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    System.out.println(employees);
    Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    System.out.println(format.format(maxDate));
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);

}

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();
}
}

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    System.out.println(format.format(maxDate));
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

Assign null to a SqlParameter

The accepted answer suggests making use of a cast. However, most of the SQL types have a special Null field which can be used to avoid this cast.

For example, SqlInt32.Null "Represents a DBNull that can be assigned to this instance of the SqlInt32 class."

int? example = null;
object exampleCast = (object) example ?? DBNull.Value;
object exampleNoCast = example ?? SqlInt32.Null;

POST request with a simple string in body with Alamofire

func paramsFromJSON(json: String) -> [String : AnyObject]?
{
    let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
    var jsonDict: [ String : AnyObject]!
    do {
        jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
        return jsonDict
    } catch {
        print("JSON serialization failed:  \(error)")
        return nil
    }
}

let json = Mapper().toJSONString(loginJSON, prettyPrint: false)

Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)

How do I check if a list is empty?

From python3 onwards you can use

a == []

to check if the list is empty

EDIT : This works with python2.7 too..

I am not sure why there are so many complicated answers. It's pretty clear and straightforward

Didn't Java once have a Pair class?

This should help.

To sum it up: a generic Pair class doesn't have any special semantics and you could as well need a Tripplet class etc. The developers of Java thus didn't include a generic Pair but suggest to write special classes (which isn't that hard) like Point(x,y), Range(start, end) or Map.Entry(key, value).

Setting environment variables on OS X

Set up your PATH environment variable on Mac OS

Open the Terminal program (this is in your Applications/Utilities folder by default). Run the following command

touch ~/.bash_profile; open ~/.bash_profile

This will open the file in the your default text editor.

For Android SDK as example:

You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use "/Development/android-sdk-macosx" as the directory the SDK is installed in. Add the following line:

export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools

Save the file and quit the text editor. Execute your .bash_profile to update your PATH:

source ~/.bash_profile

Now every time you open the Terminal program your PATH will include the Android SDK.

PHP/regex: How to get the string value of HTML tag?

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

That should do the trick

Found shared references to a collection org.hibernate.HibernateException

My problem was that I had setup an @ManyToOne relationship. Maybe if the answers above don't fix your problem you might want to check the relationship that was mentioned in the error message.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Multi-key dictionary in c#?

I use a Tuple as the keys in a Dictionary.

public class Tuple<T1, T2> {
    public T1 Item1 { get; private set; }
    public T2 Item2 { get; private set; }

    // implementation details
}

Be sure to override Equals and GetHashCode and define operator!= and operator== as appropriate. You can expand the Tuple to hold more items as needed. .NET 4.0 will include a built-in Tuple.

Is there a way to crack the password on an Excel VBA Project?

VBA Project Passwords on Access, Excel, Powerpoint, or Word documents (2007, 2010, 2013 or 2016 versions with extensions .ACCDB .XLSM .XLTM .DOCM .DOTM .POTM .PPSM) can be easily removed.

It's simply a matter of changing the filename extension to .ZIP, unzipping the file, and using any basic Hex Editor (like XVI32) to "break" the existing password, which "confuses" Office so it prompts for a new password next time the file is opened.

A summary of the steps:

  • rename the file so it has a .ZIP extension.
  • open the ZIP and go to the XL folder.
  • extract vbaProject.bin and open it with a Hex Editor
  • "Search & Replace" to "replace all" changing DPB to DPX.
  • Save changes, place the .bin file back into the zip, return it to it's normal extension and open the file like normal.
  • ALT+F11 to enter the VB Editor and right-click in the Project Explorer to choose VBA Project Properties.
  • On the Protection tab, Set a new password.
  • Click OK, Close the file, Re-open it, hit ALT+F11.
  • Enter the new password that you set.

At this point you can remove the password completely if you choose to.

Complete instructions with a step-by-step video I made "way back when" are on YouTube here.

It's kind of shocking that this workaround has been out there for years, and Microsoft hasn't fixed the issue.


The moral of the story?

Microsoft Office VBA Project passwords are not to be relied upon for security of any sensitive information. If security is important, use third-party encryption software.

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

Not that I've done this, but you could get around the double indexer call and still keep your code clean by using a static / extension method.

Ie.

public static IsDBNull<T>(this object value, T default)
{
    return (value == DBNull.Value)
        ? default
        : (T)value;
}

public static IsDBNull<T>(this object value)
{
    return value.IsDBNull(default(T));
}

Then:

IDataRecord record; // Comes from somewhere

entity.StringProperty = record["StringProperty"].IsDBNull<string>(null);
entity.Int32Property = record["Int32Property"].IsDBNull<int>(50);

entity.NoDefaultString = record["NoDefaultString"].IsDBNull<string>();
entity.NoDefaultInt = record["NoDefaultInt"].IsDBNull<int>();

Also has the benefit of keeping the null checking logic in one place. Downside is, of course, that it's an extra method call.

Just a thought.

How can I search an array in VB.NET?

If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.

Where are the Properties.Settings.Default stored?

They are saved in YOUR_APP.exe.config, the file is saved in the same folder with YOUR_APP.exe file, <userSettings> section:

   <userSettings>
      <ShowGitlabIssues.Properties.Settings>
         <setting name="SavedUserName" serializeAs="String">
            <value />
         </setting>
         <setting name="SavedPassword" serializeAs="String">
            <value />
         </setting>
         <setting name="CheckSave" serializeAs="String">
            <value>False</value>
         </setting>
      </ShowGitlabIssues.Properties.Settings>
   </userSettings>

here is cs code:

public void LoadInfoLogin()
{
    if (Properties.Settings.Default.CheckSave)// chkRemember.Checked)
    {
        txtUsername.Text = Properties.Settings.Default.SaveUserName;
        txtPassword.Text = Properties.Settings.Default.SavePassword;
        chkRemember.Checked = true;
    }
...

What to do with commit made in a detached head

checkout actual-branch

git merge {{commit-hash}}

Class name does not name a type in C++

when you define the class A, in A.h, you explicitely say that the class has a member B.

You MUST include "B.h" in "A.h"

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Unfortunately Launcher3 has stopped working error in android studio?

  1. Press the Apps menu button on your Android mobile phone device. It will display icons of all the apps installed on your mobile phone device. Press Settings.

  2. Press Apps. (Pressing on Apps button will list down all the apps installed on your mobile phone.

  3. Browse the Apps list and press on the app called "Launcher 3". (Launcher 3 is an app and it will be listed in the App list whenever you access Settings > Apps in your android phone).

  4. Pressing on the "Launcher 3" app will open the "App info screen" which will show some details pertaining to that app. On this App info screen, you will find buttons like "Force Stop", "Uninstall", "Clear Data" and "Clear Cache" etc.

  5. In Android Marshmallow (i.e. Android 6.0) choose Settings > Apps > Launcher3 > STORAGE. Press "Clear Cache". If this fails, press "Clear data". This will eventually restore functionality, but all custom shortcuts will be lost.

Restart the phone and its done. All the home screens along with app shortcuts will appear again and your mobile phone is at your service again.

I hope it explains well on how to solve the launcher problem in Android. Worked for me.

Find closing HTML tag in Sublime Text

I think, you may want to try another approach with folding enabled.

In both ST2 and ST3, if you enable folding in User settings:

{
    ...(previous item)
    "fold_buttons": true,
    ...(next item, thus the comma)
}

You can see the triangle folding button at the left side of the line where the start tag is. Click it to expand/fold. If you want to copy, fold and copy, you get all block.

enter image description here

"NOT IN" clause in LINQ to Entities

Try:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;

What's the SQL query you want to translate into a Linq query?

Using WGET to run a cronjob PHP

I tried following format, working fine

*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php

How to get all elements which name starts with some string?

A quick and easy way is to use jQuery and do this:

var $eles = $(":input[name^='q1_']").css("color","yellow");

That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:

var DOMeles = $eles.get();

see http://api.jquery.com/attribute-starts-with-selector/

In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:

var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('q1_') == 0) {
        eles.push(inputs[i]);
    }
}

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

So I take it you want 2 options default selected, and then get the value of it? If so:

http://jsfiddle.net/NdQbw/1/

<div class="divright">
    <select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
        <option value=" ">No illustrations</option>
        <option value="a" selected>Illustrations</option>
        <option value="b">Maps</option>
        <option value="c" selected>selectedPortraits</option>
    </select>
</div>

And to get value:

alert($(".leaderMultiSelctdropdown").val());

To set the value:

 $(".leaderMultiSelctdropdown").val(["a", "c"]);

You can also use an array to set the values:

var selectedValues = new Array();
selectedValues[0] = "a";
selectedValues[1] = "c";

$(".Books_Illustrations").val(selectedValues);

http://jsfiddle.net/NdQbw/4/

Add Keypair to existing EC2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance

How to redirect from one URL to another URL?

You can redirect anything or more URL via javascript, Just simple window.location.href with if else

Use this code,

<script>
if(window.location.href == 'old_url')
{
    window.location.href="new_url";
}


//Another url redirect
if(window.location.href == 'old_url2')
{
    window.location.href="new_url2";
}
</script>

You can redirect many URL's by this procedure. Thanks.

Error in Eclipse: "The project cannot be built until build path errors are resolved"

If not working in any case...then delete your project from the Eclipse workspace and again import as a Maven project if that is a Maven project. Else import as an existing project.

I tried all the previous given solutions, but they didn't work, but it works for me.

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

How can I copy a Python string?

I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

print map( id, [ a,b,c,d,e ] )

print a, b, c, d, e

e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e

The printed output is:

[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]

hello hello hello hello hello

[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]

goodbye hello hello hello hello something

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How to Set Active Tab in jQuery Ui

just trigger a click, it's work for me:

$("#tabX").trigger("click");

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Angular2 Material Dialog css, dialog size

Content in md-dialog-content is automatically scrollable.

You can manually set the size in the call to MdDialog.open

let dialogRef = dialog.open(MyComponent, {
  height: '400px',
  width: '600px',
});

Further documentation / examples for scrolling and sizing: https://material.angular.io/components/dialog/overview

Some colors should be determined by your theme. See here for theming docs: https://material.angular.io/guide/theming

If you want to override colors and such, use Elmer's technique of just adding the appropriate css.

Note that you must have the HTML 5 <!DOCTYPE html> on your page for the size of your dialog to fit the contents correctly ( https://github.com/angular/material2/issues/2351 )

int array to string

I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.

I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?

Taking one of the provided answers as an example:

        result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I need to worry about the array being null, now it becomes this:

        result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I want a comma-delimited string, now it becomes this:

        result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());

This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.

Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:

    public static string ToStringLinqy<T>(this T[] array, string delimiter)
    {
        // edit: let's replace this with a "better" version using a StringBuilder
        //return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
        return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
    }

But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:

    public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // edit: replaced my previous implementation to use StringBuilder
            if (array.Length > 0)
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    builder.Append(delimiter);
                    builder.Append(array[i]);
                }

                return builder.ToString()
            }
            else
            {
                return string.Empty;
            }
        }
        else
        {
            return null;
        }
    }

And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):

    public static string ToString<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // determine if the length of the array is greater than the performance threshold for using a stringbuilder
            // 10 is just an arbitrary threshold value I've chosen
            if (array.Length < 10)
            {
                // assumption is that for arrays of less than 10 elements
                // this code would be more efficient than a StringBuilder.
                // Note: this is a crazy/pointless micro-optimization.  Don't do this.
                string[] values = new string[array.Length];

                for (int i = 0; i < values.Length; i++)
                    values[i] = array[i].ToString();

                return string.Join(delimiter, values);
            }
            else
            {
                // for arrays of length 10 or longer, use a StringBuilder
                StringBuilder sb = new StringBuilder();

                sb.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    sb.Append(delimiter);
                    sb.Append(array[i]);
                }

                return sb.ToString();
            }
        }
        else
        {
            return null;
        }
    }

For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.

That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:

    // convert an enumeration of one type into an enumeration of another type
    public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
    {
        foreach (TIn value in input)
        {
            yield return conversion(value);
        }
    }

    // concatenate the strings in an enumeration separated by the specified delimiter
    public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
    {
        IEnumerator<T> enumerator = input.GetEnumerator();

        if (enumerator.MoveNext())
        {
            StringBuilder builder = new StringBuilder();

            // start off with the first element
            builder.Append(enumerator.Current);

            // append the remaining elements separated by the delimiter
            while (enumerator.MoveNext())
            {
                builder.Append(delimiter);
                builder.Append(enumerator.Current);
            }

            return builder.ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    // concatenate all elements
    public static string ToString<T>(this IEnumerable<T> input)
    {
        return ToString(input, string.Empty);
    }

    // concatenate all elements separated by a delimiter
    public static string ToString<T>(this IEnumerable<T> input, string delimiter)
    {
        return input.Delimit(delimiter);
    }

    // concatenate all elements, each one left-padded to a minimum length
    public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
    {
        return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
    }

Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.

Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.

For this problem, I'd rather just write something like this in my application code:

        int[] arr = { 0, 1, 2, 3, 0, 1 };

        // 012301
        result = arr.ToString<int>();

        // comma-separated values
        // 0,1,2,3,0,1
        result = arr.ToString(",");

        // left-padded to 2 digits
        // 000102030001
        result = arr.ToString(2, '0');

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).

you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below

javac -target 1.7 *.java

if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)

Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90 . These seem conflictive settings. Try increasing MaxConnections=120.

But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

just try this:

_x000D_
_x000D_
//don't call getActivity()
getActivity().startActivityForResult(intent, REQ_CODE);

//just call 
startActivityForResult(intent, REQ_CODE);
//directly from fragment
_x000D_
_x000D_
_x000D_

Convert datatable to JSON in C#

I have simple function to convert datatable to json string.

I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.

Maybe this can be useful.

 private string DataTableToJson(DataTable dt) {
  if (dt == null) {
   return "[]";
  };
  if (dt.Rows.Count < 1) {
   return "[]";
  };

  JArray array = new JArray();
  foreach(DataRow dr in dt.Rows) {
   JObject item = new JObject();
   foreach(DataColumn col in dt.Columns) {
    item.Add(col.ColumnName, dr[col.ColumnName]?.ToString());
   }
   array.Add(item);
  }

  return array.ToString(Newtonsoft.Json.Formatting.Indented);
 }

Removing duplicate rows in Notepad++

If the rows are immediately after each other then you can use a regex replace:

Search Pattern: ^(.*\r?\n)(\1)+

Replace with: \1

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

jQuery select change event get selected option

You can use the jQuery find method

 $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
 });

The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)

    $('select').find('option').click(function () {
     var optionSelected = $(this);
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
   });

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

Error while sending QUERY packet

You may also have this error if the variable wait_timeout is too low.

If so, you may set it higher like that:

SET GLOBAL wait_timeout=10;

This was the solution for the same error in my case.

How to create a byte array in C++?

Maybe you can leverage the std::bitset type available in C++11. It can be used to represent a fixed sequence of N bits, which can be manipulated by conventional logic.

#include<iostream>
#include<bitset>

class MissileLauncher {
 public:
  MissileLauncher() {}
  void show_bits() const {
    std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
  }

  bool toggle_a() {
    // toggles (i.e., flips) the value of `a` bit and returns the
    // resulting logical value
    m_abc[0].flip();
    return m_abc[0];
  }

  bool toggle_c() {
    // toggles (i.e., flips) the value of `c` bit and returns the
    // resulting logical value
    m_abc[2].flip();
    return m_abc[2];
  }

  bool matches(const std::bitset<3>& mask) {
    // tests whether all the bits specified in `mask` are turned on in
    // this instance's bitfield
    return ((m_abc & mask) == mask);
  }

 private:
  std::bitset<3> m_abc;
};

typedef std::bitset<3> Mask;
int main() {
  MissileLauncher ml;

  // notice that the bitset can be "built" from a string - this masks
  // can be made available as constants to test whether certain bits
  // or bit combinations are "on" or "off"
  Mask has_a("001");       // the zeroth bit
  Mask has_b("010");       // the first bit
  Mask has_c("100");       // the second bit
  Mask has_a_and_c("101"); // zeroth and second bits
  Mask has_all_on("111");  // all on!
  Mask has_all_off("000"); // all off!

  // I can even create masks using standard logic (in this case I use
  // the or "|" operator)
  Mask has_a_and_b = has_a | has_b;
  std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;

  // print "true" and "false" instead of "1" and "0"
  std::cout<<std::boolalpha;

  std::cout<<"Bits, as created"<<std::endl;
  ml.show_bits();
  std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"I will toggle a"<<std::endl;
  ml.toggle_a();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();  
  std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
  std::cout<<"Toggle c"<<std::endl;
  ml.toggle_c();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();    
  std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;  
  std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
  return 0;
}

Compiling using gcc 4.7.2

g++ example.cpp -std=c++11

I get:

This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false

Merge PDF files with PHP

This worked for me on Windows

  1. download PDFtk free from https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/
  2. drop folder (PDFtk) into the root of c:
  3. add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file

    $file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';  
    $file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';  
    $file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';   
    
    $command =  'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
    $result = exec($command);
    

Handle Guzzle exception and get HTTP body

As of 2019 here is what I elaborated from the answers above and Guzzle docs to handle the exception, get the response body, status code, message and the other sometimes valuable response items.

try {
    /**
     * We use Guzzle to make an HTTP request somewhere in the
     * following theMethodMayThrowException().
     */
    $result = theMethodMayThrowException();
} catch (\GuzzleHttp\Exception\RequestException $e) {
    /**
     * Here we actually catch the instance of GuzzleHttp\Psr7\Response
     * (find it in ./vendor/guzzlehttp/psr7/src/Response.php) with all
     * its own and its 'Message' trait's methods. See more explanations below.
     *
     * So you can have: HTTP status code, message, headers and body.
     * Just check the exception object has the response before.
     */
    if ($e->hasResponse()) {
        $response = $e->getResponse();
        var_dump($response->getStatusCode()); // HTTP status code;
        var_dump($response->getReasonPhrase()); // Response message;
        var_dump((string) $response->getBody()); // Body, normally it is JSON;
        var_dump(json_decode((string) $response->getBody())); // Body as the decoded JSON;
        var_dump($response->getHeaders()); // Headers array;
        var_dump($response->hasHeader('Content-Type')); // Is the header presented?
        var_dump($response->getHeader('Content-Type')[0]); // Concrete header value;
    }
}
// process $result etc. ...

Voila. You get the response's information in conveniently separated items.

Side Notes:

With catch clause we catch the inheritance chain PHP root exception class \Exception as Guzzle custom exceptions extend it.

This approach may be useful for use cases where Guzzle is used under the hood like in Laravel or AWS API PHP SDK so you cannot catch the genuine Guzzle exception.

In this case, the exception class may not be the one mentioned in the Guzzle docs (e.g. GuzzleHttp\Exception\RequestException as the root exception for Guzzle).

So you have to catch \Exception instead but bear in mind it is still the Guzzle exception class instance.

Though use with care. Those wrappers may make Guzzle $e->getResponse() object's genuine methods not available. In this case, you will have to look at the wrapper's actual exception source code and find out how to get status, message, etc. instead of using Guzzle $response's methods.

If you call Guzzle directly yourself you can catch GuzzleHttp\Exception\RequestException or any other one mentioned in their exceptions docs with respect to your use case conditions.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

I created a small hackMD to install cocoapods on MacOS 10.15 (Catalina) and 11 (Big Sur)

https://hackmd.io/@sBJPlhRESGqCKCqV8ZjP1A/S1UY3W7HP

Installing Cocoapods on MacOS Catalina(MacOS 10.15.X) and Big Sur (MacOS 11)

  1. Make sure you have xcode components are installed.

  2. Download 'Command Line Tools' (about 500MB) directly from this link (Requires you to have apple account) https://developer.apple.com/downloads/index.action

  3. Install the downloaded file

  4. Click on Install

  5. Install COCOAPODS files in terminal sudo gem install -n /usr/local/bin cocoapods

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

Round a divided number in Bash

To round up you can use modulus.

The second part of the equation will add to True if there's a remainder. (True = 1; False = 0)

ex: 3/2

answer=$(((3 / 2) + (3 % 2 > 0)))
echo $answer
2

ex: 100 / 2

answer=$(((100 / 2) + (100 % 2 > 0)))
echo $answer
50

ex: 100 / 3

answer=$(((100 / 3) + (100 % 3 > 0)))
echo $answer
34

How can I remove an entry in global configuration with git config?

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

How to get UTC value for SYSDATE on Oracle

I'm using:

SELECT CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE) FROM DUAL;

It's working fine for me.

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

How to add jQuery code into HTML Page

  1. Create a file for the jquery eg uploadfuntion.js.
  2. Save that file in the same folder as website or in subfolder.
  3. In head section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and then the reference to your script eg: <script src="uploadfuntion.js"> </script>

4.Lastly you should ensure there are elements that match the selectors in the code.

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

Refresh or force redraw the fragment

Use the following code for refreshing fragment again:

FragmentTransaction ftr = getFragmentManager().beginTransaction();                          
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Select      Eventname, 
            count(Eventname) as 'Counts'
INTO        #TEMPTABLE                                                                                
FROM        tblevent
where       Eventname like 'A%'
Group by    Eventname
order by    count(Eventname)

Here by using the into clause the table is directly created

Center content vertically on Vuetify

<v-container> has to be right after <template>, if there is a <div> in between, the vertical align will just not work.

<template>
  <v-container fill-height>
      <v-row class="justify-center align-center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
      </v-row>
  </v-container>
</template>

No assembly found containing an OwinStartupAttribute Error

Add class Startup.cs to root of project with next code:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(ProjectName.Startup))]
namespace ProjectName
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Rewrite URL after redirecting 404 error htaccess

Try this in your .htaccess:

.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]

The ErrorDocument redirects all 404s to a specific URL, all 500s to another url (replace with your domain).

The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.

Local Redirect:

Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):

ErrorDocument 404 /pages/errors/404_redirect.php

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>

Redirect based on error number

Looks like you'll need to specify an ErrorDocument line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.

error_redirect.php

<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

How to increase font size in NeatBeans IDE?

At Windows in the file C:\Program Files\NetBeans x.x\etc\netbeans.conf

Add "--fontsize [size]" at the end of line netbeans_default_options:

netbeans_default_options=".... --fontsize 16"

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

Get Current date in epoch from Unix shell script

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

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

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

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

First char to upper case

public static String cap1stChar(String userIdea)
{
    char[] stringArray = userIdea.toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    return userIdea = new String(stringArray);
}

How can I get the class name from a C++ object?

To get class name without mangling stuff you can use func macro in constructor:

class MyClass {
    const char* name;
    MyClass() {
        name = __func__;
    }
}

How to round each item in a list of floats to 2 decimal places?

You might want to look at Python's decimal module, which can make using floating point numbers and doing arithmetic with them a lot more intuitive. Here's a trivial example of one way of using it to "clean up" your list values:

>>> from decimal import *
>>> mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
>>> getcontext().prec = 2
>>> ["%.2f" % e for e in mylist]
['0.30', '0.50', '0.20']
>>> [Decimal("%.2f" % e) for e in mylist]
[Decimal('0.30'), Decimal('0.50'), Decimal('0.20')]
>>> data = [float(Decimal("%.2f" % e)) for e in mylist]
>>> data
[0.3, 0.5, 0.2]

JavaScript calculate the day of the year (1 - 366)

_x000D_
_x000D_
const dayOfYear = date => {_x000D_
    const myDate = new Date(date);_x000D_
    const year = myDate.getFullYear();_x000D_
    const firstJan = new Date(year, 0, 1);_x000D_
    const differenceInMillieSeconds = myDate - firstJan;_x000D_
    return (differenceInMillieSeconds / (1000 * 60 * 60 * 24) + 1);_x000D_
};_x000D_
_x000D_
const result = dayOfYear("2019-2-01");_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

What's the difference between “mod” and “remainder”?

In C and C++ and many languages, % is the remainder NOT the modulus operator.

For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this

_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_

The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.

Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

Material UI and Grid system

Below is made by purely MUI Grid system,

MUI - Grid Layout

With the code below,

// MuiGrid.js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
    backgroundColor: "#b5b5b5",
    margin: "10px"
  }
}));

export default function FullWidthGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container spacing={0}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

↓ CodeSandbox ↓

Edit MUI-Grid system

How to call an element in a numpy array?

If you are using numpy and your array is an np.array of np.array elements like:

A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])

and you want to access the inner elements (like 10,11,12 13,14.......) then use:

A[0][0] instead of A[0,0]

For example:

>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR

(P.S.: Might be useful when using numpy.array_split())

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

localhost refused to connect Error in visual studio

I have had the same problem while on a computer without any admin rights.

Getting rid of the .vs folder (applicationhost.config file) in the project folder was not enough.

What worked for me...I

  • deleted bin folder (as I reused an existing project)
  • deleted Obj folder
  • deleted .vs folder
  • changed the port of the project (I used 3000) as @vinayakhegde mentionned it above and I also created a virtual directory
  • -

Localhost is accessing the solution so far.

Hope it helps

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

Can't be iterating directly in dictionary. So you can through converting into tuple.

first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']

fields = {
    'first_names': first_names,
    'last_name': last_names,
         } 
tup_field=tuple(fields.items())
for names in fields.items():
     field,possible_values = names
     tup_possible_values=tuple(possible_values)
     for pvalue in tup_possible_values:
           print (field + "is" + pvalue)

HTTP Basic: Access denied fatal: Authentication failed

Open CMD (Run as administrator) type command:

git config --system --unset credential.helper

then enter new password for Git remote server.

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

Find indices of elements equal to zero in a NumPy array

numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

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.

Get second child using jQuery

It's surprising to see that nobody mentioned the native JS way to do this..

Without jQuery:

Just access the children property of the parent element. It will return a live HTMLCollection of children elements which can be accessed by an index. If you want to get the second child:

parentElement.children[1];

In your case, something like this could work: (example)

var secondChild = document.querySelector('.parent').children[1];

console.log(secondChild); // <td>element two</td>
<table>
    <tr class="parent">
        <td>element one</td>
        <td>element two</td>
    </tr>
</table>

You can also use a combination of CSS3 selectors / querySelector() and utilize :nth-of-type(). This method may work better in some cases, because you can also specifiy the element type, in this case td:nth-of-type(2) (example)

var secondChild = document.querySelector('.parent > td:nth-of-type(2)');

console.log(secondChild); // <td>element two</td>

Can't accept license agreement Android SDK Platform 24

install Android 7 - Platform 24 Full in android sdk manager

just it

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The source code provides some basic guidance:

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

For more detail, Kurtis' answer is dead on. I would just add: Don't log any personally identifiable or private information at INFO or above (WARN/ERROR). Otherwise, bug reports or anything else that includes logging may be polluted.

Android - Share on Facebook, Twitter, Mail, ecc

sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"your subject" );
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "your text");
startActivity(Intent.createChooser(sharingIntent, ""));

SQL Error: ORA-00942 table or view does not exist

Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.

Simply wrap the table in double quotes:

INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

In my case the web server IP was blocked on the mail server, it needs to be unblocked by your hosting company and make it whitelisted. Also, use port port 587.

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

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

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

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

, which results in this:

Different font sizes for different labels

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

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

CMake does not find Visual C++ compiler

In my case there was an environment variable set which was the reason for this error. The problem was solved after deleting cxx_flags from the environment variables.

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Event handlers for Twitter Bootstrap dropdowns?

I have been looking at this. On populating the drop down anchors, I have given them a class and data attributes, so when needing to do an action you can do:

<li><a class="dropDownListItem" data-name="Fred Smith" href="#">Fred</a></li>

and then in the jQuery doing something like:

$('.dropDownListItem').click(function(e) {
    var name = e.currentTarget;
    console.log(name.getAttribute("data-name"));
});

So if you have dynamically generated list items in your dropdown and need to use the data that isn't just the text value of the item, you can use the data attributes when creating the dropdown listitem and then just give each item with the class the event, rather than referring to the id's of each item and generating a click event.

Is there a way to specify a max height or width for an image?

set a style for the image

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />

How to Sort a List<T> by a property in the object

Please let me complete the answer by @LukeH with some sample code, as I have tested it I believe it may be useful for some:

public class Order
{
    public string OrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public int Quantity { get; set; }
    public int Total { get; set; }

    public Order(string orderId, DateTime orderDate, int quantity, int total)
    {
        OrderId = orderId;
        OrderDate = orderDate;
        Quantity = quantity;
        Total = total;
    }
}

public void SampleDataAndTest()
{
    List<Order> objListOrder = new List<Order>();

    objListOrder.Add(new Order("tu me paulo ", Convert.ToDateTime("01/06/2016"), 1, 44));
    objListOrder.Add(new Order("ante laudabas", Convert.ToDateTime("02/05/2016"), 2, 55));
    objListOrder.Add(new Order("ad ordinem ", Convert.ToDateTime("03/04/2016"), 5, 66));
    objListOrder.Add(new Order("collocationem ", Convert.ToDateTime("04/03/2016"), 9, 77));
    objListOrder.Add(new Order("que rerum ac ", Convert.ToDateTime("05/02/2016"), 10, 65));
    objListOrder.Add(new Order("locorum ; cuius", Convert.ToDateTime("06/01/2016"), 1, 343));


    Console.WriteLine("Sort the list by date ascending:");
    objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));

    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    Console.WriteLine("Sort the list by date descending:");
    objListOrder.Sort((x, y) => y.OrderDate.CompareTo(x.OrderDate));
    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    Console.WriteLine("Sort the list by OrderId ascending:");
    objListOrder.Sort((x, y) => x.OrderId.CompareTo(y.OrderId));
    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    //etc ...
}

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

XML Parsing - Read a Simple XML File and Retrieve Values

Easy way to parse the xml is to use the LINQ to XML

for example you have the following xml file

<library>
    <track id="1" genre="Rap" time="3:24">
        <name>Who We Be RMX (feat. 2Pac)</name>
        <artist>DMX</artist>
        <album>The Dogz Mixtape: Who's Next?!</album>
    </track>
    <track id="2" genre="Rap" time="5:06">
        <name>Angel (ft. Regina Bell)</name>
        <artist>DMX</artist>
        <album>...And Then There Was X</album>
    </track>
    <track id="3" genre="Break Beat" time="6:16">
        <name>Dreaming Your Dreams</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
    <track id="4" genre="Break Beat" time="9:38">
        <name>Finished Symphony</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
<library>

For reading this file, you can use the following code:

public void Read(string  fileName)
{
    XDocument doc = XDocument.Load(fileName);

    foreach (XElement el in doc.Root.Elements())
    {
        Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
        Console.WriteLine("  Attributes:");
        foreach (XAttribute attr in el.Attributes())
            Console.WriteLine("    {0}", attr);
        Console.WriteLine("  Elements:");

        foreach (XElement element in el.Elements())
            Console.WriteLine("    {0}: {1}", element.Name, element.Value);
    }
}

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

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

Angular HttpClient "Http failure during parsing"

You can specify that the data to be returned is not JSON using responseType.

In your example, you can use a responseType string value of text, like this:

return this.http.post(
    'http://10.0.1.19/login',
    {email, password},
    {responseType: 'text'})

The full list of options for responseType is:

  • json (the default)
  • text
  • arraybuffer
  • blob

See the docs for more information.

Difference between Activity Context and Application Context

Use getApplicationContext() if you need something tied to a Context that itself will have global scope.

If you use Activity, then the new Activity instance will have a reference, which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.

Splitting String and put it on int array

Let's consider that you have input as "1,2,3,4".

That means the length of the input is 7. So now you write the size = 7/2 = 3.5. But as size is an int, it will be rounded off to 3. In short, you are losing 1 value.

If you rewrite the code as below it should work:

String input;
int length, count, size;
Scanner keyboard = new Scanner(System.in);
input = keyboard.next();
length = input.length();

String strarray[] = input.split(",");
int intarray[] = new int[strarray.length];

for (count = 0; count < intarray.length ; count++) {
    intarray[count] = Integer.parseInt(strarray[count]);
}

for (int s : intarray) {
    System.out.println(s);
}

Min and max value of input in angular4 application

Simply do this in angular2+ by adding (onkeypress)

<input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (onkeypress)="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
    name="rateInput">

Tested on Angular 7

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

mysql: SOURCE error 2?

Related issue I had getting error 2 running source command: filename must not be in quotes even if it contains spaces in name or path to file.

Sql Server trigger insert values from new row into another table

You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.

Delete triggers have access to a similar logical table called DELETED.

Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.

Finding the direction of scrolling in a UIScrollView?

Determining the direction is fairly straightforward, but keep in mind that the direction can change several times over the course of a gesture. For example, if you have a scroll view with paging turned on and the user swipes to go to the next page, the initial direction could be rightward, but if you have bounce turned on, it will briefly be going in no direction at all and then briefly be going leftward.

To determine the direction, you'll need to use the UIScrollView scrollViewDidScroll delegate. In this sample, I created a variable named lastContentOffset which I use to compare the current content offset with the previous one. If it's greater, then the scrollView is scrolling right. If it's less then the scrollView is scrolling left:

// somewhere in the private class extension
@property (nonatomic, assign) CGFloat lastContentOffset;

// somewhere in the class implementation
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    ScrollDirection scrollDirection;

    if (self.lastContentOffset > scrollView.contentOffset.x) {
        scrollDirection = ScrollDirectionRight;
    } else if (self.lastContentOffset < scrollView.contentOffset.x) {
        scrollDirection = ScrollDirectionLeft;
    }

    self.lastContentOffset = scrollView.contentOffset.x;

    // do whatever you need to with scrollDirection here.    
}

I'm using the following enum to define direction. Setting the first value to ScrollDirectionNone has the added benefit of making that direction the default when initializing variables:

typedef NS_ENUM(NSInteger, ScrollDirection) {
    ScrollDirectionNone,
    ScrollDirectionRight,
    ScrollDirectionLeft,
    ScrollDirectionUp,
    ScrollDirectionDown,
    ScrollDirectionCrazy,
};

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I had a similar problem and although I made sure that referenced entities were saved first it keeps failing with the same exception. After hours of investigation it turns out that the problem was because the "version" column of the referenced entity was NULL. In my particular setup i was inserting it first in an HSQLDB(that was a unit test) a row like that:

INSERT INTO project VALUES (1,1,'2013-08-28 13:05:38','2013-08-28 13:05:38','aProject','aa',NULL,'bb','dd','ee','ff','gg','ii',NULL,'LEGACY','0','CREATED',NULL,NULL,1,'0',NULL,NULL,NULL,NULL,'0','0', NULL);

The problem of the above is the version column used by hibernate was set to null, so even if the object was correctly saved, Hibernate considered it as unsaved. When making sure the version had a NON-NULL(1 in this case) value the exception disappeared and everything worked fine.

I am putting it here in case someone else had the same problem, since this took me a long time to figure this out and the solution is completely different than the above.

What type of hash does WordPress use?

For manually resetting the password in Wordpress DB, a simple MD5 hash is sufficient. (see reason below)

To prevent breaking backwards compatibility, MD5-hashed passwords stored in the database are still valid. When a user logs in with such a password, WordPress detects MD5 was used, rehashes the password using the more secure method, and stores the new hash in the database.

Source: http://eamann.com/tech/wordpress-password-hashing/

Update: this was an answer posted in 2014. I don't know if it still works for the latest version of WP since I don't work with WP anymore.

How to change Hash values?

If you know that the values are strings, you can call the replace method on them while in the cycle: this way you will change the value.

Altohugh this is limited to the case in which the values are strings and hence doesn't answer the question fully, I thought it can be useful to someone.

How do I get an Excel range using row and column numbers in VSTO / C#?

Try this, works!

Excel.Worksheet sheet = xlWorkSheet;
Excel.Series series1 = seriesCollection.NewSeries();
Excel.Range rng = (Excel.Range)xlWorkSheet.Range[xlWorkSheet.Cells[3, 13], xlWorkSheet.Cells[pp, 13]].Cells;
series1.Values = rng;

SSIS Connection Manager Not Storing SQL Password

I use a variable to store the entire connection string and pass it into the ConnectionString expression. This overwrites all settings for the connection and allows you store the password.

What is a clean, Pythonic way to have multiple constructors in Python?

This is how I solved it for a YearQuarter class I had to create. I created an __init__ which is very tolerant to a wide variety of input.

You use it like this:

>>> from datetime import date
>>> temp1 = YearQuarter(year=2017, month=12)
>>> print temp1
2017-Q4
>>> temp2 = YearQuarter(temp1)
>>> print temp2
2017-Q4
>>> temp3 = YearQuarter((2017, 6))
>>> print temp3
2017-Q2 
>>> temp4 = YearQuarter(date(2017, 1, 18))
>>> print temp4
2017-Q1
>>> temp5 = YearQuarter(year=2017, quarter = 3)
>>> print temp5
2017-Q3

And this is how the __init__ and the rest of the class looks like:

import datetime


class YearQuarter:

    def __init__(self, *args, **kwargs):
        if len(args) == 1:
            [x]     = args

            if isinstance(x, datetime.date):
                self._year      = int(x.year)
                self._quarter   = (int(x.month) + 2) / 3
            elif isinstance(x, tuple):
                year, month     = x

                self._year      = int(year)

                month           = int(month)

                if 1 <= month <= 12:
                    self._quarter   = (month + 2) / 3
                else:
                    raise ValueError

            elif isinstance(x, YearQuarter):
                self._year      = x._year
                self._quarter   = x._quarter

        elif len(args) == 2:
            year, month     = args

            self._year      = int(year)

            month           = int(month)

            if 1 <= month <= 12:
                self._quarter   = (month + 2) / 3
            else:
                raise ValueError

        elif kwargs:

            self._year      = int(kwargs["year"])

            if "quarter" in kwargs:
                quarter     = int(kwargs["quarter"])

                if 1 <= quarter <= 4:
                    self._quarter     = quarter
                else:
                    raise ValueError
            elif "month" in kwargs:
                month   = int(kwargs["month"])

                if 1 <= month <= 12:
                    self._quarter     = (month + 2) / 3
                else:
                    raise ValueError

    def __str__(self):
        return '{0}-Q{1}'.format(self._year, self._quarter)

How do I properly clean up Excel interop objects?

You need to be aware that Excel is very sensitive to the culture you are running under as well.

You may find that you need to set the culture to EN-US before calling Excel functions. This does not apply to all functions - but some of them.

    CultureInfo en_US = new System.Globalization.CultureInfo("en-US"); 
    System.Threading.Thread.CurrentThread.CurrentCulture = en_US;
    string filePathLocal = _applicationObject.ActiveWorkbook.Path;
    System.Threading.Thread.CurrentThread.CurrentCulture = orgCulture;

This applies even if you are using VSTO.

For details: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369

Wrap text in <td> tag

This worked for me with some css frameworks (material design lite [MDL]).

table {
  table-layout: fixed;
  white-space: normal!important;
}

td {
  word-wrap: break-word;
}

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

nvarchar(max) still being truncated

Results to text only allows a maximum of 8192 characters.

Screenshot

I use this approach

DECLARE @Query NVARCHAR(max);

set @Query = REPLICATE('A',4000)
set @Query = @Query + REPLICATE('B',4000)
set @Query = @Query + REPLICATE('C',4000)
set @Query = @Query + REPLICATE('D',4000)

select LEN(@Query)

SELECT @Query /*Won't contain any "D"s*/
SELECT @Query as [processing-instruction(x)] FOR XML PATH /*Not truncated*/

How do I change a tab background color when using TabLayout?

You can change the background color of the tab by this attribute

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
'android:background="@color/primary_color"/>'

Single line sftp from terminal

To UPLOAD a single file, you will need to create a bash script. Something like the following should work on OS X if you have sshpass installed.

Usage:

sftpx <password> <user@hostname> <localfile> <remotefile>

Put this script somewhere in your path and call it sftpx:

#!/bin/bash

export RND=`cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32`
export TMPDIR=/tmp/$RND
export FILENAME=$(basename "$4")
export DSTDIR=$(dirname "$4")

mkdir $TMPDIR
cp "$3" $TMPDIR/$FILENAME

export SSHPASS=$1
sshpass -e sftp -oBatchMode=no -b - $2 << !
   lcd $TMPDIR
   cd $DSTDIR
   put $FILENAME
   bye
!

rm $TMPDIR/$FILENAME
rmdir $TMPDIR

Filter Java Stream to 1 and only 1 element

Have you tried this

long c = users.stream().filter((user) -> user.getId() == 1).count();
if(c > 1){
    throw new IllegalStateException();
}

long count()
Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:

     return mapToLong(e -> 1L).sum();

This is a terminal operation.

Source: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

Convert timestamp to readable date/time PHP

I know that's an old one question, but its high in the search results.

If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:

$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);

Following @sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.

$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored

You may check PHP's manual for DateTime::createFromFormat for more info and options.

Angular2 *ngIf check object array length in template

You can use

<div class="col-sm-12" *ngIf="event.attendees?.length">

Without event.attendees?.length > 0 or even event.attendees?length != 0

Because ?.length already return boolean value.

If in array will be something it will display it else not.

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

For some reason I couldn't get multiple folders to work (well it did for a while but as soon as I needed more dlls and added more folders, none with white spaces in the path). I then copied all needed dlls to one folder and had that as my java.library.path and it worked. I don't have an explanation - if anyone does, it would be great.

com.jcraft.jsch.JSchException: UnknownHostKey

It is a security risk to avoid host key checking.

JSch uses HostKeyRepository interface and its default implementation KnownHosts class to manage this. You can provide an alternate implementation that allows specific keys by implementing HostKeyRepository. Or you could keep the keys that you want to allow in a file in the known_hosts format and call

jsch.setKnownHosts(knownHostsFileName);

Or with a public key String as below.

String knownHostPublicKey = "mysite.com ecdsa-sha2-nistp256 AAAAE............/3vplY";
jsch.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

see Javadoc for more details.

This would be a more secure solution.

Jsch is open source and you can download the source from here. In the examples folder, look for KnownHosts.java to know more details.

document.getElementById().value doesn't set the value

The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

How can I get the current screen orientation?

In your activity class use the method below :

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            setlogo();// Your Method
            Log.d("Daiya", "ORIENTATION_LANDSCAPE");

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

            setlogoForLandScape();// Your Method
            Log.d("Daiya", "ORIENTATION_PORTRAIT");
        }
    }

Then to declare that your activity handles a configuration change, edit the appropriate element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

That's all!!

Can I get all methods of a class?

package tPoint;

import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class ReadClasses {

public static void main(String[] args) {

    try {
        Class c = Class.forName("tPoint" + ".Sample");
        Object obj = c.newInstance();
        Document doc = 
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File("src/datasource.xml"));

        Method[] m = c.getDeclaredMethods();

        for (Method e : m) {
            String mName = e.getName();
            if (mName.startsWith("set")) {
                System.out.println(mName);
                e.invoke(obj, new 
          String(doc.getElementsByTagName(mName).item(0).getTextContent()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Multiple Where clauses in Lambda expressions

Can be

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty && l.InternalName != String.Empty)

or

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty)
     .Where(l => l.InternalName != String.Empty)

When you are looking at Where implementation, you can see it accepts a Func(T, bool); that means:

  • T is your IEnumerable type
  • bool means it needs to return a boolean value

So, when you do

.Where(l => l.InternalName != String.Empty)
//     ^                   ^---------- boolean part
//     |------------------------------ "T" part

Android emulator doesn't take keyboard input - SDK tools rev 20

Google wanted to give some more headache to the developers.

So, what you have to do now is edit your AVD and add "Keyboard Support" for it in the Hardware section and change the value to "Yes"

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

Winforms issue - Error creating window handle

The out of memory suggestion doesn't seem like a bad lead.

What is your program doing that it gets this error?

Is it creating a great many windows or controls? Does it create them programatically as opposed to at design time? If so, do you do this in a loop? Is that loop infinite? Are you consuming staggering boatloads of memory in some other way?

What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.

Using bootstrap with bower

assuming you have npm installed and bower installed globally

  1. navigate to your project
  2. bower init (this will generate the bower.json file in your directory)
  3. (then keep clicking yes)...
  4. to set the path where bootstrap will be installed:
    manually create a .bowerrc file next to the bower.json file and add the following to it:

    { "directory" : "public/components" }

  5. bower install bootstrap --save

Note: to install other components:

 bower search {component-name-here}

3 column layout HTML/CSS

CSS:

     .container div{
 width: 33.33%;
 float: left;
 height: 100px ;} 

Clear floats after the columns

 .container:after {
 content: "";
 display: table;
 clear: both;}

What is the difference between `let` and `var` in swift?

Though currently I am still reading the manual, but I think this is very close to C/C++ const pointer. In other words, something like difference between char const* and char*. Compiler also refuses to update content, not only reference reassignment (pointer).

For example, let's say you have this struct. Take care that this is a struct, not a class. AFAIK, classes don't have a concept of immutable state.

import Foundation


struct
AAA
{
    var inner_value1    =   111

    mutating func
    mutatingMethod1()
    {
        inner_value1    =   222
    }
}


let aaa1    =   AAA()
aaa1.mutatingMethod1()      // compile error
aaa1.inner_value1 = 444     // compile error

var aaa2    =   AAA()
aaa2.mutatingMethod1()      // OK
aaa2.inner_value1 = 444     // OK

Because the structs are immutable by default, you need to mark a mutator method with mutating. And because the name aaa1 is constant, you can't call any mutator method on it. This is exactly what we expected on C/C++ pointers.

I believe this is a mechanism to support a kind of const-correctness stuff.

PreparedStatement IN clause alternatives?

Limitations of the in() operator is the root of all evil.

It works for trivial cases, and you can extend it with "automatic generation of the prepared statement" however it is always having its limits.

  • if you're creating a statement with variable number of parameters, that will make an sql parse overhead at each call
  • on many platforms, the number of parameters of in() operator are limited
  • on all platforms, total SQL text size is limited, making impossible for sending down 2000 placeholders for the in params
  • sending down bind variables of 1000-10k is not possible, as the JDBC driver is having its limitations

The in() approach can be good enough for some cases, but not rocket proof :)

The rocket-proof solution is to pass the arbitrary number of parameters in a separate call (by passing a clob of params, for example), and then have a view (or any other way) to represent them in SQL and use in your where criteria.

A brute-force variant is here http://tkyte.blogspot.hu/2006/06/varying-in-lists.html

However if you can use PL/SQL, this mess can become pretty neat.

function getCustomers(in_customerIdList clob) return sys_refcursor is 
begin
    aux_in_list.parse(in_customerIdList);
    open res for
        select * 
        from   customer c,
               in_list v
        where  c.customer_id=v.token;
    return res;
end;

Then you can pass arbitrary number of comma separated customer ids in the parameter, and:

  • will get no parse delay, as the SQL for select is stable
  • no pipelined functions complexity - it is just one query
  • the SQL is using a simple join, instead of an IN operator, which is quite fast
  • after all, it is a good rule of thumb of not hitting the database with any plain select or DML, since it is Oracle, which offers lightyears of more than MySQL or similar simple database engines. PL/SQL allows you to hide the storage model from your application domain model in an effective way.

The trick here is:

  • we need a call which accepts the long string, and store somewhere where the db session can access to it (e.g. simple package variable, or dbms_session.set_context)
  • then we need a view which can parse this to rows
  • and then you have a view which contains the ids you're querying, so all you need is a simple join to the table queried.

The view looks like:

create or replace view in_list
as
select
    trim( substr (txt,
          instr (txt, ',', 1, level  ) + 1,
          instr (txt, ',', 1, level+1)
             - instr (txt, ',', 1, level) -1 ) ) as token
    from (select ','||aux_in_list.getpayload||',' txt from dual)
connect by level <= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1

where aux_in_list.getpayload refers to the original input string.


A possible approach would be to pass pl/sql arrays (supported by Oracle only), however you can't use those in pure SQL, therefore a conversion step is always needed. The conversion can not be done in SQL, so after all, passing a clob with all parameters in string and converting it witin a view is the most efficient solution.

Converting a string to int in Groovy

also you can make static import

import static java.lang.Integer.parseInt as asInteger

and after this use

String s = "99"
asInteger(s)

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.

A CSS rule you might try:

input.ng-dirty.ng-invalid {
  color: red
}

Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)

Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

Cannot checkout, file is unmerged

If you want to discard modifications you made to the file, you can do:

git reset first_Name.txt
git checkout first_Name.txt

python date of the previous month

For someone who got here and looking to get both the first and last day of the previous month:

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)

start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)

# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)

Output:

First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28

Correct way to read a text file into a buffer in C?

Yes - you would probably be arrested for your terriable abuse of strcat !

Take a look at getline() it reads the data a line at a time but importantly it can limit the number of characters you read, so you don't overflow the buffer.

Strcat is relatively slow because it has to search the entire string for the end on every character insertion. You would normally keep a pointer to the current end of the string storage and pass that to getline as the position to read the next line into.

Dynamically load JS inside JS

I need to do this frequently, so I use this:

var loadJS = function(url, implementationCode, location){
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to 
    //insert the <script> element

    var scriptTag = document.createElement('script');
    scriptTag.src = url;

    scriptTag.onload = implementationCode;
    scriptTag.onreadystatechange = implementationCode;

    location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);

For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.

How to set specific Java version to Maven

Maven uses the JAVA_HOME parameter to find which Java version it is supposed to run. I see from your comment that you can't change that in the configuration.

  • You can set the JAVA_HOME parameter just before you start maven (and change it back afterwards if need be).
  • You could also go into your mvn(non-windows)/mvn.bat/mvn.cmd(windows) and set your java version explicitly there.

How to add a custom button to the toolbar that calls a JavaScript function?

I am in the process of developing a number of custom Plugins for CKEditor and here's my survival pack of bookmarks:

For your purpose, I would recommend look at one of the plugins in the _source/plugins directory, for example the "print" button. Adding a simple Javascript function is quite easy to achieve. You should be able to duplicate the print plugin (take the directory from _source into the actual plugins/ directory, worry about minification later), rename it, rename every mention of "print" within it, give the button a proper name you use later in your toolbar setup to include the button, and add your function.

Prevent div from moving while resizing the page

There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.

Relative

An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.

<div style="width:100%"> 
<!-- This div will be the full width of the browser, whatever size it is -->
    <div style="width:300px">
    <!-- this div will be 300px, whatever size the browser is -->
        <p style="width:50%">
            This paragraph's width will be 50% of it's parent (150px).
        </p>
    </div>
</div>

Another relative measurement is ems which are relative to font size.

Fixed

An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.

If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.

<script> tag vs <script type = 'text/javascript'> tag

<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>


<!-- HTML5 -->
<script></script>

type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.

Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script

How to install the current version of Go in Ubuntu Precise

i installed from source. there is a step-by-step tutorial here: http://golang.org/doc/install/source

How to sort pandas data frame using values from several columns?

I have found this to be really useful:

df = pd.DataFrame({'A' : range(0,10) * 2, 'B' : np.random.randint(20,30,20)})

# A ascending, B descending
df.sort(**skw(columns=['A','-B']))

# A descending, B ascending
df.sort(**skw(columns=['-A','+B']))

Note that unlike the standard columns=,ascending= arguments, here column names and their sort order are in the same place. As a result your code gets a lot easier to read and maintain.

Note the actual call to .sort is unchanged, skw (sortkwargs) is just a small helper function that parses the columns and returns the usual columns= and ascending= parameters for you. Pass it any other sort kwargs as you usually would. Copy/paste the following code into e.g. your local utils.py then forget about it and just use it as above.

# utils.py (or anywhere else convenient to import)
def skw(columns=None, **kwargs):
    """ get sort kwargs by parsing sort order given in column name """
    # set default order as ascending (+)
    sort_cols = ['+' + col if col[0] != '-' else col for col in columns]
    # get sort kwargs
    columns, ascending = zip(*[(col.replace('+', '').replace('-', ''), 
                                False if col[0] == '-' else True) 
                               for col in sort_cols])
    kwargs.update(dict(columns=list(columns), ascending=ascending))
    return kwargs

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete the last line in bootstrap.css

folllowing lin /*# sourceMappingURL=bootstrap.css.map */

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In a previous answer, it was suggested to use this line of code for .Net 4.5:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

I would encourage you to OR that value in to whatever the existing values are like this:

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // .NET 4.5

If you look at the list of values, you notice that they are a power of two. This way, in the future when things shift to TLS 2.0 for example, your code will still work.