Programs & Examples On #Highlighting

Attract attention to or emphasize something important eg. by making chosen words or phrases more visually prominent.

How to highlight text using javascript

Here's my regexp pure JavaScript solution:

function highlight(text) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp(text + '(?!([^<]+)?<)', 'gi'),
        '<b style="background-color:#ff0;font-size:100%">$&</b>'
    );
}

Android: disabling highlight on listView click

As an alternative:

listView.setSelector(android.R.color.transparent);

or

listView.setSelector(new StateListDrawable());

Textarea that can do syntax highlighting on the fly?

I would recommend EditArea for live editing of a syntax hightlighted textarea.

How to make HTML Text unselectable

The full modern solution to your problem is purely CSS-based, but note that older browsers won't support it, in which cases you'd need to fallback to solutions such as the others have provided.

So in pure CSS:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

However the mouse cursor will still change to a caret when over the element's text, so you add to that:

cursor: default;

Modern CSS is pretty elegant.

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.

If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.

Dynamic button click event handler

@Debasish Sahu, your answer is an answer to another question, namely: how to know which button (or any other control) was clicked when there is a common handler for a couple of controls? So I'm giving an answer to this question how I usually do it, almost the same as yours, but note that also works without type conversion when it handles the same type of Controls:

Private Sub btn_done_clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim selectedBtn As Button = sender
    MsgBox("you have clicked button " & selectedBtn.Name)
End Sub

Print Pdf in C#

I advice you to try 2Printer command line tool from: http://www.doc2prn.com/

Command line example to print all PDF files from folder "C:\Input" is below. You can simple call it from your C# code.

2Printer.exe -s "C:\Input*.PDF" -prn "Canon MP610 series Printer"

How do you run a single test/spec file in RSpec?

This question is an old one, but it shows up at the top of Google when searching for how to run a single test. I don't know if it's a recent addition, but to run a single test out of a spec you can do the following:

rspec path/to/spec:<line number>

where -line number- is a line number that contains part of your test. For example, if you had a spec like:

1: 
2: it "should be awesome" do
3:   foo = 3
4:   foo.should eq(3)
5: end
6:

Let's say it's saved in spec/models/foo_spec.rb. Then you would run:

rspec spec/models/foo_spec.rb:2

and it would just run that one spec. In fact, that number could be anything from 2 to 5.

Hope this helps!

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Let's revisit key phases of Mapreduce program.

The map phase is done by mappers. Mappers run on unsorted input key/values pairs. Each mapper emits zero, one, or multiple output key/value pairs for each input key/value pairs.

The combine phase is done by combiners. The combiner should combine key/value pairs with the same key. Each combiner may run zero, once, or multiple times.

The shuffle and sort phase is done by the framework. Data from all mappers are grouped by the key, split among reducers and sorted by the key. Each reducer obtains all values associated with the same key. The programmer may supply custom compare functions for sorting and a partitioner for data split.

The partitioner decides which reducer will get a particular key value pair.

The reducer obtains sorted key/[values list] pairs, sorted by the key. The value list contains all values with the same key produced by mappers. Each reducer emits zero, one or multiple output key/value pairs for each input key/value pair.

Have a look at this javacodegeeks article by Maria Jurcovicova and mssqltips article by Datta for a better understanding

Below is the image from safaribooksonline article

enter image description here

Is it valid to replace http:// with // in a <script src="http://...">?

A relative URL without a scheme (http: or https:) is valid, per RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2. If a client chokes on it, then it's the client's fault because they're not complying with the URI syntax specified in the RFC.

Your example is valid and should work. I've used that relative URL method myself on heavily trafficked sites and have had zero complaints. Also, we test our sites in Firefox, Safari, IE6, IE7 and Opera. These browsers all understand that URL format.

What is the use of style="clear:both"?

When you use float without width, there remains some space in that row. To block this space you can use clear:both; in next element.

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

A rather nice way to handle this for missing COM classes:

Dim o:Set o = Nothing
On Error Resume Next
Set o = CreateObject("foo.bar")
On Error Goto 0
If o Is Nothing Then
  Response.Write "Oups, foo.bar isn't installed on this server!"
Else
  Response.Write "Foo bar found, yay."
End If

Swap DIV position with CSS only

This question already has a great answer but in the spirit of exploring all possibilities here is another technique to reorder dom elements whilst still allowing them to take up their space, unlike the absolute positioning method.

This method works in all modern browsers and IE9+ (basically any browser that supports display:table) it has a drawback that it can only be used on a max of 3 siblings though.

//the html    
<div class='container'>
    <div class='div1'>1</div>
    <div class='div2'>2</div>
    <div class='div3'>3</div>
</div>

//the css
.container {
   display:table;    
}
.div1 {
    display:table-footer-group;
}
.div2 {
    display:table-header-group;
}
.div3 {
    display:table-row-group;
}

This will reorder the elements from 1,2,3 to 2,3,1. Basically anything with the display set to table-header-group will be positioned at the top and table-footer-group at the bottom. Naturally table-row-group puts an element in the middle.

This method is quick with good support and requires much less css than the flexbox approach so if you are only looking to swap a few items around for a mobile layout for example then dont rule out this technique.

You can check out a live demo on codepen: http://codepen.io/thepixelninja/pen/eZVgLx

Storing an object in state of a React component?

Even though it can be done via immutability-helper or similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign. Code:

this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})

Can be used on HTML Event Attributes as well, example:

onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

PHP mySQL - Insert new record into table with auto-increment on primary key

$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";

Just leaving the value of the AI primary key NULL will assign an auto incremented value.

How do I load external fonts into an HTML document?

CSS3 offers a way to do it with the @font-face rule.

http://www.w3.org/TR/css3-webfonts/#the-font-face-rule

http://www.css3.info/preview/web-fonts-with-font-face/

Here is a number of different ways which will work in browsers that don't support the @font-face rule.

Check if a String contains numbers Java

.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.

Error when deploying an artifact in Nexus

If any of the above answers worked out, You can create new artifact directly from the admin side of (NEXUS Screen shot attached below).

  1. Login to nexus UI http://YOUR_URL:8081/nexus( username: admin default password: admin123 )
  2. Click repositories on the left side then click the repo, For eg: click release.
  3. Choose artifact Upload (last tab).
  4. Choose GAV definition as GAV Param- Then enter your groupid , artifact id and version .
  5. Choose Jar file.
  6. Click upload artifact. Thats it !

Now you will be able to add the corrsponding in your project.(screenshot below)

enter image description here

HTML Input="file" Accept Attribute File Type (CSV)

In addition to the top-answer, CSV files, for example, are reported as text/plain under macOS but as application/vnd.ms-excel under Windows. So I use this:

<input type="file" accept="text/plain, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

How to use enums as flags in C++?

I'd like to elaborate on Uliwitness answer, fixing his code for C++98 and using the Safe Bool idiom, for lack of the std::underlying_type<> template and the explicit keyword in C++ versions below C++11.

I also modified it so that the enum values can be sequential without any explicit assignment, so you can have

enum AnimalFlags_
{
    HasClaws,
    CanFly,
    EatsFish,
    Endangered
};
typedef FlagsEnum<AnimalFlags_> AnimalFlags;

seahawk.flags = AnimalFlags() | CanFly | EatsFish | Endangered;

You can then get the raw flags value with

seahawk.flags.value();

Here's the code.

template <typename EnumType, typename Underlying = int>
class FlagsEnum
{
    typedef Underlying FlagsEnum::* RestrictedBool;

public:
    FlagsEnum() : m_flags(Underlying()) {}

    FlagsEnum(EnumType singleFlag):
        m_flags(1 << singleFlag)
    {}

    FlagsEnum(const FlagsEnum& original):
        m_flags(original.m_flags)
    {}

    FlagsEnum& operator |=(const FlagsEnum& f) {
        m_flags |= f.m_flags;
        return *this;
    }

    FlagsEnum& operator &=(const FlagsEnum& f) {
        m_flags &= f.m_flags;
        return *this;
    }

    friend FlagsEnum operator |(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) |= f2;
    }

    friend FlagsEnum operator &(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) &= f2;
    }

    FlagsEnum operator ~() const {
        FlagsEnum result(*this);
        result.m_flags = ~result.m_flags;
        return result;
    }

    operator RestrictedBool() const {
        return m_flags ? &FlagsEnum::m_flags : 0;
    }

    Underlying value() const {
        return m_flags;
    }

protected:
    Underlying  m_flags;
};

Moment.js with Vuejs

In your package.json in the "dependencies" section add moment:

"dependencies": {
  "moment": "^2.15.2",
  ...
}

In the component where you would like to use moment, import it:

<script>
import moment from 'moment'
...

And in the same component add a computed property:

computed: {
  timestamp: function () {
    return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm')
  }
}

And then in the template of this component:

<p>{{ timestamp }}</p>

Check cell for a specific letter or set of letters

You can use the following formula,

=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")

What is the time complexity of indexing, inserting and removing from common data structures?

Red-Black trees:

  • Insert - O(log n)
  • Retrieve - O(log n)
  • Delete - O(log n)

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Find duplicate records in MySQL

Isn't this easier :

SELECT *
FROM tc_tariff_groups
GROUP BY group_id
HAVING COUNT(group_id) >1

?

Convert Base64 string to an image file?

An easy way I'm using:

file_put_contents($output_file, file_get_contents($base64_string));

This works well because file_get_contents can read data from a URI, including a data:// URI.

Is there a better jQuery solution to this.form.submit();?

this.form.submit();

This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.

Converting Secret Key into a String and Vice Versa

Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:

  1. *.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html

  2. Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

  3. Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html

Code snippets: For encoding:

String temp = new String(Base64.getEncoder().encode(key.getEncoded()));

For decoding:

byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");

Get multiple elements by Id

You can get the multiple element by id by identifying what element it is. For example

<div id='id'></div>
<div id='id'></div>
<div id='id'></div>

I assume if you are using jQuery you can select all them all by

$("div#id")

. This will get you array of elements you loop them based on your logic.

Save string to the NSUserDefaults?

Here's how to do the same with Swift;

var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")

To get it back later;

if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
    // Do something with savedValue
}

In Swift 3.0

var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")

if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {

}

How to list files in an android directory?

In addition to all the answers above:

If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having

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

in your manifest won't be enough. You also have actively request the permission in your activity:

//check for permission
if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
    //ask for permission
    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMISSION_CODE);
}

I recommend reading this: http://developer.android.com/training/permissions/requesting.html#perm-request

Get full path without filename from path that includes filename

Path.GetDirectoryName()... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).

You could validate first by testing File.Exists() and/or Directory.Exists() on your path first to see if you need to call Path.GetDirectoryName

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I was getting an error

"ImportError: Install xlrd >= 1.0.0 for Excel support"

on Pycharm for below code

import pandas as pd
df2 = pd.read_excel("data.xlsx")
print(df2.head(3))
print(df2.tail(3))

Solution : pip install xlrd

It resolved error after using this. Also no need to use "import xlrd"

How to make sure that string is valid JSON using JSON.NET

Use JContainer.Parse(str) method to check if the str is a valid Json. If this throws exception then it is not a valid Json.

JObject.Parse - Can be used to check if the string is a valid Json object
JArray.Parse - Can be used to check if the string is a valid Json Array
JContainer.Parse - Can be used to check for both Json object & Array

How can I add "href" attribute to a link dynamically using JavaScript?

document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

<strong> vs. font-weight:bold & <em> vs. font-style:italic

<strong> and <em> - unlike <b> and <i> - have clear purpose for web browsers for the blind.

A blind person doesn't browse the web visually, but by sound such as text readers. <strong> and <em>, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b> and <i>... they may make them loud or stress them or they may not... you never can be sure unless you use <strong> and <em>.

Calculating Distance between two Latitude and Longitude GeoCoordinates

And here, for those still not satisfied (like me), the original code from .NET-Frameworks GeoCoordinate class, refactored into a standalone method:

public double GetDistance(double longitude, double latitude, double otherLongitude, double otherLatitude)
{
    var d1 = latitude * (Math.PI / 180.0);
    var num1 = longitude * (Math.PI / 180.0);
    var d2 = otherLatitude * (Math.PI / 180.0);
    var num2 = otherLongitude * (Math.PI / 180.0) - num1;
    var d3 = Math.Pow(Math.Sin((d2 - d1) / 2.0), 2.0) + Math.Cos(d1) * Math.Cos(d2) * Math.Pow(Math.Sin(num2 / 2.0), 2.0);
    
    return 6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)));
}

Windows command for file size only

If you are inside a batch script, you can use argument variable tricks to get the filesize:

filesize.bat:

@echo off
echo %~z1

This gives results like the ones you suggest in your question.

Type

help call

at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.

Edit: This only works in Windows 2000 and later

Convert string to hex-string in C#

var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

How to merge two arrays in JavaScript and de-duplicate items

First concatenate the two arrays, next filter out only the unique items:

_x000D_
_x000D_
var a = [1, 2, 3], b = [101, 2, 1, 10]_x000D_
var c = a.concat(b)_x000D_
var d = c.filter((item, pos) => c.indexOf(item) === pos)_x000D_
_x000D_
console.log(d) // d is [1, 2, 3, 101, 10]
_x000D_
_x000D_
_x000D_

Edit

As suggested a more performance wise solution would be to filter out the unique items in b before concatenating with a:

_x000D_
_x000D_
var a = [1, 2, 3], b = [101, 2, 1, 10]_x000D_
var c = a.concat(b.filter((item) => a.indexOf(item) < 0))_x000D_
_x000D_
console.log(c) // c is [1, 2, 3, 101, 10]
_x000D_
_x000D_
_x000D_

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

How to add external fonts to android application

Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);

popup form using html/javascript/css

But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.

Umm. Just change the string passed to the prompt() function.

While searching, I found that there we CANNOT change the content of popup Prompt Box

You can't change the title. You can change the content, it is the first argument passed to the prompt() function.

Windows 7, 64 bit, DLL problems

I had the same problem. After spending hours searching on the web, I found a solution for me.

I copied the file combase.dll file (C:\Windows\System32) to the release folder, and it resolved the problem.

How do I get a computer's name and IP address using VB.NET?

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name : " & hostName & vbNewLine)
        For Each address In Dns.GetHostEntry(hostName).AddressList()
            Select Case Convert.ToInt32(address.AddressFamily)
                Case 2
                    Console.WriteLine("IP Version 4 Address: " & address.ToString)
                Case 23
                    Console.WriteLine("IP Version 6 Address: " & address.ToString)
            End Select
        Next
        Console.ReadKey()
    End Sub
End Module

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Get generic type of class at runtime

One simple solution for this cab be like below

public class GenericDemo<T>{
    private T type;

    GenericDemo(T t)
    {
        this.type = t;
    }

    public String getType()
    {
        return this.type.getClass().getName();
    }

    public static void main(String[] args)
    {
        GenericDemo<Integer> obj = new  GenericDemo<Integer>(5);
        System.out.println("Type: "+ obj.getType());
    }
}

How do you see the entire command history in interactive Python?

This should give you the commands printed out in separate lines:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

Write a file in external storage in Android

You can find these method usefull in reading and writing data in android.

 public void saveData(View view) {
    String text = "This is the text in the file, this is the part of the issue of the name and also called the name od the college ";
    FileOutputStream fos = null;
    try {
        fos = openFileOutput("FILE_NAME", MODE_PRIVATE);
        fos.write(text.getBytes());
        Toast.makeText(this, "Data is saved "+ getFilesDir(), Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fos!= null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

public void logData(View view) {
    FileInputStream fis = null;

    try {
        fis = openFileInput("FILE_NAME");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb=  new StringBuilder();
        String text;
        while((text = br.readLine()) != null){
            sb.append(text).append("\n");
            Log.e("TAG", text
            );
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

jQuery: enabling/disabling datepicker

$('#ElementID').unbind('focus');

did the trick for me !!

Wireshark vs Firebug vs Fiddler - pros and cons?

None of the above, if you are on a Mac. Use Charles Proxy. It's the best network/request information collecter that I have ever come across. You can view and edit all outgoing requests, and see the responses from those requests in several forms, depending on the type of the response. It costs 50 dollars for a license, but you can download the trial version and see what you think.

If your on Windows, then I would just stay with Fiddler.

A more useful statusline in vim?

set statusline=%<%f%m\ \[%{&ff}:%{&fenc}:%Y]\ %{getcwd()}\ \ \[%{strftime('%Y/%b/%d\ %a\ %I:%M\ %p')}\]\ %=\ Line:%l\/%L\ Column:%c%V\ %P

This is mine, give as a suggestion

Determine if a String is an Integer in Java

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}

go get results in 'terminal prompts disabled' error for github private repo

If you just want go get to work real fast, and move along with your work...

Just export GIT_TERMINAL_PROMPT=1

$ export GIT_TERMINAL_PROMPT=1
$ go get [whatever]

It will now prompt you for a user/pass for the rest of your shell session. Put this in your .profile or setup git as above for a more permanent solution.

highlight the navigation menu for the current page

Please Look at the following:

Here is what's working:

1.) top menu buttons are visible and highlight correctly

2.) sub menu buttons are not visible until top menu is clicked

Here is what needs work:

1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)

Please see code here: http://jsbin.com/ePawaju/1/edit

or here: http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

Do I need to put this script in the head section? Where is the best place?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery is new to me, any help would greatly be appreciated :) var submenu;

$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

Why you can't just use mysqlsh?

PS C:\Users\artur\Desktop> mysqlsh --user root
MySQL Shell 8.0.17

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
Creating a session to 'root@localhost'
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.17 MySQL Community Server - GPL
No default schema selected; type \use <schema> to set one.
 MySQL  localhost:33060+ ssl  JS >

mysqlsh on windows terminal (pic)

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

is there a 'block until condition becomes true' function in java?

As nobody published a solution with CountDownLatch. What about:

public class Lockeable {
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public void doAfterEvent(){
        countDownLatch.await();
        doSomething();
    }

    public void reportDetonatingEvent(){
        countDownLatch.countDown();
    }
}

Why shouldn't I use mysql_* functions in PHP?

Ease of use

The analytic and synthetic reasons were already mentioned. For newcomers there's a more significant incentive to stop using the dated mysql_ functions.

Contemporary database APIs are just easier to use.

It's mostly the bound parameters which can simplify code. And with excellent tutorials (as seen above) the transition to PDO isn't overly arduous.

Rewriting a larger code base at once however takes time. Raison d'être for this intermediate alternative:

Equivalent pdo_* functions in place of mysql_*

Using <pdo_mysql.php> you can switch from the old mysql_ functions with minimal effort. It adds pdo_ function wrappers which replace their mysql_ counterparts.

  1. Simply include_once("pdo_mysql.php"); in each invocation script that has to interact with the database.

  2. Remove the mysql_ function prefix everywhere and replace it with pdo_.

    • mysql_connect() becomes pdo_connect()
    • mysql_query() becomes pdo_query()
    • mysql_num_rows() becomes pdo_num_rows()
    • mysql_insert_id() becomes pdo_insert_id()
    • mysql_fetch_array() becomes pdo_fetch_array()
    • mysql_fetch_assoc() becomes pdo_fetch_assoc()
    • mysql_real_escape_string() becomes pdo_real_escape_string()
    • and so on...

  3. Your code will work alike and still mostly look the same:

    include_once("pdo_mysql.php"); 
    
    pdo_connect("localhost", "usrABC", "pw1234567");
    pdo_select_db("test");
    
    $result = pdo_query("SELECT title, html FROM pages");  
    
    while ($row = pdo_fetch_assoc($result)) {
        print "$row[title] - $row[html]";
    }
    

Et voilà.
Your code is using PDO.
Now it's time to actually utilize it.

Bound parameters can be easy to use

You just need a less unwieldy API.

pdo_query() adds very facile support for bound parameters. Converting old code is straightforward:

Move your variables out of the SQL string.

  • Add them as comma delimited function parameters to pdo_query().
  • Place question marks ? as placeholders where the variables were before.
  • Get rid of ' single quotes that previously enclosed string values/variables.

The advantage becomes more obvious for lengthier code.

Often string variables aren't just interpolated into SQL, but concatenated with escaping calls in between.

pdo_query("SELECT id, links, html, title, user, date FROM articles
   WHERE title='" . pdo_real_escape_string($title) . "' OR id='".
   pdo_real_escape_string($title) . "' AND user <> '" .
   pdo_real_escape_string($root) . "' ORDER BY date")

With ? placeholders applied you don't have to bother with that:

pdo_query("SELECT id, links, html, title, user, date FROM articles
   WHERE title=? OR id=? AND user<>? ORDER BY date", $title, $id, $root)

Remember that pdo_* still allows either or.
Just don't escape a variable and bind it in the same query.

  • The placeholder feature is provided by the real PDO behind it.
  • Thus also allowed :named placeholder lists later.

More importantly you can pass $_REQUEST[] variables safely behind any query. When submitted <form> fields match the database structure exactly it's even shorter:

pdo_query("INSERT INTO pages VALUES (?,?,?,?,?)", $_POST);

So much simplicity. But let's get back to some more rewriting advises and technical reasons on why you may want to get rid of mysql_ and escaping.

Fix or remove any oldschool sanitize() function

Once you have converted all mysql_ calls to pdo_query with bound params, remove all redundant pdo_real_escape_string calls.

In particular you should fix any sanitize or clean or filterThis or clean_data functions as advertised by dated tutorials in one form or the other:

function sanitize($str) {
   return trim(strip_tags(htmlentities(pdo_real_escape_string($str))));
}

Most glaring bug here is the lack of documentation. More significantly the order of filtering was in exactly the wrong order.

  • Correct order would have been: deprecatedly stripslashes as the innermost call, then trim, afterwards strip_tags, htmlentities for output context, and only lastly the _escape_string as its application should directly preceed the SQL intersparsing.

  • But as first step just get rid of the _real_escape_string call.

  • You may have to keep the rest of your sanitize() function for now if your database and application flow expect HTML-context-safe strings. Add a comment that it applies only HTML escaping henceforth.

  • String/value handling is delegated to PDO and its parameterized statements.

  • If there was any mention of stripslashes() in your sanitize function, it may indicate a higher level oversight.

    • That was commonly there to undo damage (double escaping) from the deprecated magic_quotes. Which however is best fixed centrally, not string by string.

    • Use one of the userland reversal approaches. Then remove the stripslashes() in the sanitize function.

    Historic note on magic_quotes. That feature is rightly deprecated. It's often incorrectly portrayed as failed security feature however. But magic_quotes are as much a failed security feature as tennis balls have failed as nutrition source. That simply wasn't their purpose.

    The original implementation in PHP2/FI introduced it explicitly with just "quotes will be automatically escaped making it easier to pass form data directly to msql queries". Notably it was accidentially safe to use with mSQL, as that supported ASCII only.
    Then PHP3/Zend reintroduced magic_quotes for MySQL and misdocumented it. But originally it was just a convenience feature, not intend for security.

How prepared statements differ

When you scramble string variables into the SQL queries, it doesn't just get more intricate for you to follow. It's also extraneous effort for MySQL to segregate code and data again.

SQL injections simply are when data bleeds into code context. A database server can't later spot where PHP originally glued variables inbetween query clauses.

With bound parameters you separate SQL code and SQL-context values in your PHP code. But it doesn't get shuffled up again behind the scenes (except with PDO::EMULATE_PREPARES). Your database receives the unvaried SQL commands and 1:1 variable values.

While this answer stresses that you should care about the readability advantages of dropping mysql_. There's occasionally also a performance advantage (repeated INSERTs with just differing values) due to this visible and technical data/code separation.

Beware that parameter binding still isn't a magic one-stop solution against all SQL injections. It handles the most common use for data/values. But can't whitelist column name / table identifiers, help with dynamic clause construction, or just plain array value lists.

Hybrid PDO use

These pdo_* wrapper functions make a coding-friendly stop-gap API. (It's pretty much what MYSQLI could have been if it wasn't for the idiosyncratic function signature shift). They also expose the real PDO at most times.
Rewriting doesn't have to stop at using the new pdo_ function names. You could one by one transition each pdo_query() into a plain $pdo->prepare()->execute() call.

It's best to start at simplifying again however. For example the common result fetching:

$result = pdo_query("SELECT * FROM tbl");
while ($row = pdo_fetch_assoc($result)) {

Can be replaced with just an foreach iteration:

foreach ($result as $row) {

Or better yet a direct and complete array retrieval:

$result->fetchAll();

You'll get more helpful warnings in most cases than PDO or mysql_ usually provide after failed queries.

Other options

So this hopefully visualized some practical reasons and a worthwile pathway to drop mysql_.

Just switching to doesn't quite cut it. pdo_query() is also just a frontend onto it.

Unless you also introduce parameter binding or can utilize something else from the nicer API, it's a pointless switch. I hope it's portrayed simple enough to not further the discouragement to newcomers. (Education usually works better than prohibition.)

While it qualifies for the simplest-thing-that-could-possibly-work category, it's also still very experimental code. I just wrote it over the weekend. There's a plethora of alternatives however. Just google for PHP database abstraction and browse a little. There always have been and will be lots of excellent libraries for such tasks.

If you want to simplify your database interaction further, mappers like Paris/Idiorm are worth a try. Just like nobody uses the bland DOM in JavaScript anymore, you don't have to babysit a raw database interface nowadays.

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

How to hide soft keyboard on android after clicking outside EditText?

Instead of iterating through all the views or overriding dispatchTouchEvent.

Why Not just override the onUserInteraction() of the Activity this will make sure keyboard dismisses whenever the user taps outside of EditText.

Will work even when EditText is inside the scrollView.

@Override
public void onUserInteraction() {
    if (getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

The problem in my case was in the discrepancy between the Gradle version installed globally and the one required by React Native. To fix it, I had to update the folder android/gradle/wrapper from the current 6.5 RN version from GH.

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

How to verify that a specific method was not called using Mockito?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

There are actually many ways to achieve this, however it's (arguably) cleaner to use the

verify(yourMock, times(0)).someMethod();

method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:

verify(yourMock, times(5)).someMethod();

Alternatives are:

verify(yourMock, never()).someMethod();

Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:

verifyZeroInteractions(yourMock)

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

Python virtualenv questions

Normally virtualenv creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32 for some reason, I would use a different directory for environments.

You shouldn't need to mess with paths: use the activate script (in <env>\Scripts) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate to set everything back to how it was before activation.

Example:

c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>

Notice how I didn't need to specify a path for deactivate - activate does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix and it should print the root of your environment.)

You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.

If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper (the link points to a port of this to Powershell) makes life with virtualenv even easier.

Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.

Further update: You should be able to use pip, distribute instead of setuptools, and just plain python setup.py install with virtualenv. Just ensure you've activated an environment before installing something into it.

How to install a specific version of package using Composer?

Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:

composer require "laravelcollective/html":"^5.8.0"

A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html

How to use null in switch

Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

Here is an example from their documentation:

String s = Match(i).of(
    Case($(1), "one"),
    Case($(2), "two"),
    Case($(), "?")
);

You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...

JPA entity without id

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

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

Twitter Bootstrap vs jQuery UI?

I have on several projects.

The biggest difference in my opinion

  • jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old

  • Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding

  • jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)

So what to choose?

That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?

I always end up using both, so I can use the best of both worlds.

Here are the links to both frameworks, if you decide to use them.

  1. jQuery UI
  2. Bootstrap

Select multiple rows with the same value(s)

This may work for you:

select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
    from table2
    group by t2.Chromosome, t2.Locus
    having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus

How do I change data-type of pandas data frame to string with a defined format?

I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])

Android difference between Two Dates

It will give you difference in months

long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;

System.out.println(String.format("%d months", elapsedDays/30));

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

Abstract Class:-Real Time Example

A good example of real time found from here:-

A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

A business example:

I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.

How to reset settings in Visual Studio Code?

Steps to reset on Windows:

  • Press 'Windows-Key"+R , and enter %APPDATA%\Code\User

    enter image description here

    And delete 'setting.json' at this location.

  • Press 'Windows-Key"+R , and enter %USERPROFILE%.vscode\extensions

    enter image description here

    And delete all the extensions there.

EDIT

After two vote downs added images to make it more clear :)

Is it possible to specify the schema when connecting to postgres with JDBC?

In Go with "sql.DB" (note the search_path with underscore):

postgres://user:password@host/dbname?sslmode=disable&search_path=schema

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How can I read a whole file into a string variable

If you just want the content as string, then the simple solution is to use the ReadFile function from the io/ioutil package. This function returns a slice of bytes which you can easily convert to a string.

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("file.txt") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // print the content as 'bytes'

    str := string(b) // convert content to a 'string'

    fmt.Println(str) // print the content as a 'string'
}

How can I make a link from a <td> table cell

You can creat the table you want, save it as an image and then use an image map to creat the link (this way you can put the coords of the hole td to make it in to a link).

Writing a string to a cell in excel

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it "MyFullyQualified.xlsm"
  • Add a sheet with no protection and call it "mySheet"
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

How to type a new line character in SQL Server Management Studio

In SSMS, you can't print new line with select, just using PRINT instead

DECLARE @text NVARCHAR(100)
SET @text = concat(N'This is line 1.', CHAR(10), N'This is line 2.')
PRINT @text

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

add to array if it isn't there already

Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k keys to them to be able to get the original values:

$keys = array();
foreach ($array as $k => $v){
    if (isset($v['key'])) {
        $keys[$value] = $k;
    }
}

Then you just need to iterate it to get the original values:

$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key]['key'];
}

This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).

Using in_array instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique on it would be better than in_array (array_unique sorts the values in O(n·log n) and then removes successive duplicates).

Free c# QR-Code generator

Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);

How to reverse apply a stash?

The V1 git man page had a reference about un-applying a stash. The excerpt is below.

The newer V2 git man page doesn't include any reference to un-applying a stash but the below still works well

Un-applying a Stash In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash. Git does not provide such a stash un-apply command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse:

$ git stash show -p stash@{0} | git apply -R

Again, if you don’t specify a stash, Git assumes the most recent stash:

$ git stash show -p | git apply -R

You may want to create an alias and effectively add a stash-unapply command to your Git. For example:

$ git config --global alias.stash-unapply '!git stash show -p | git apply -R'
$ git stash apply
$ #... work work work
$ git stash-unapply

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR

Don't rescue Exception => e (and not re-raise the exception) - or you might drive off a bridge.


Let's say you are in a car (running Ruby). You recently installed a new steering wheel with the over-the-air upgrade system (which uses eval), but you didn't know one of the programmers messed up on syntax.

You are on a bridge, and realize you are going a bit towards the railing, so you turn left.

def turn_left
  self.turn left:
end

oops! That's probably Not Good™, luckily, Ruby raises a SyntaxError.

The car should stop immediately - right?

Nope.

begin
  #...
  eval self.steering_wheel
  #...
rescue Exception => e
  self.beep
  self.log "Caught #{e}.", :warn
  self.log "Logged Error - Continuing Process.", :info
end

beep beep

Warning: Caught SyntaxError Exception.

Info: Logged Error - Continuing Process.

You notice something is wrong, and you slam on the emergency breaks (^C: Interrupt)

beep beep

Warning: Caught Interrupt Exception.

Info: Logged Error - Continuing Process.

Yeah - that didn't help much. You're pretty close to the rail, so you put the car in park (killing: SignalException).

beep beep

Warning: Caught SignalException Exception.

Info: Logged Error - Continuing Process.

At the last second, you pull out the keys (kill -9), and the car stops, you slam forward into the steering wheel (the airbag can't inflate because you didn't gracefully stop the program - you terminated it), and the computer in the back of your car slams into the seat in front of it. A half-full can of Coke spills over the papers. The groceries in the back are crushed, and most are covered in egg yolk and milk. The car needs serious repair and cleaning. (Data Loss)

Hopefully you have insurance (Backups). Oh yeah - because the airbag didn't inflate, you're probably hurt (getting fired, etc).


But wait! There's more reasons why you might want to use rescue Exception => e!

Let's say you're that car, and you want to make sure the airbag inflates if the car is exceeding its safe stopping momentum.

 begin 
    # do driving stuff
 rescue Exception => e
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
    raise
 end

Here's the exception to the rule: You can catch Exception only if you re-raise the exception. So, a better rule is to never swallow Exception, and always re-raise the error.

But adding rescue is both easy to forget in a language like Ruby, and putting a rescue statement right before re-raising an issue feels a little non-DRY. And you do not want to forget the raise statement. And if you do, good luck trying to find that error.

Thankfully, Ruby is awesome, you can just use the ensure keyword, which makes sure the code runs. The ensure keyword will run the code no matter what - if an exception is thrown, if one isn't, the only exception being if the world ends (or other unlikely events).

 begin 
    # do driving stuff
 ensure
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
 end

Boom! And that code should run anyways. The only reason you should use rescue Exception => e is if you need access to the exception, or if you only want code to run on an exception. And remember to re-raise the error. Every time.

Note: As @Niall pointed out, ensure always runs. This is good because sometimes your program can lie to you and not throw exceptions, even when issues occur. With critical tasks, like inflating airbags, you need to make sure it happens no matter what. Because of this, checking every time the car stops, whether an exception is thrown or not, is a good idea. Even though inflating airbags is a bit of an uncommon task in most programming contexts, this is actually pretty common with most cleanup tasks.

Regex Last occurrence?

You can try anchoring it to the end of the string, something like \\[^\\]*$. Though I'm not sure if one absolutely has to use regexp for the task.

Where are my postgres *.conf files?

on MacOS Mojave where I used brew install postgresql to install, I found it here

/usr/local/var/postgres/postgresql.conf

I got this using the following sql command cited in this response here:

psql -U postgres -c 'SHOW config_file'

offsetting an html anchor to adjust for fixed header

I had been facing a similar issue, unfortunately after implementing all the solutions above, I came to the following conclusion.

  1. My inner elements had a fragile CSS structure and implementing a position relative / absolute play, was completely breaking the page design.
  2. CSS is not my strong suit.

I wrote this simple scrolling js, that accounts for the offset caused due to the header and relocated the div about 125 pixels below. Please use it as you see fit.

The HTML

<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->

The JavaScript

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
&& location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});

See a live implementation here.

Open text file and program shortcut in a Windows batch file

In some cases, when opening a LNK file it is expecting the end of the application run.

In such cases it is better to use the following syntax (so you do not have to wait the end of the application):

START /B /I "MyTitleApp" "myshortcut.lnk"

To open a TXT file can be in the way already indicated (because notepad.exxe not interrupt the execution of the start command)

START notepad "myfile.txt"

How to check if an element exists in the xml using xpath?

Normally when you try to select a node using xpath your xpath-engine will return null or equivalent if the node doesn't exists.

xpath: "/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml"

If your using xsl check out this question for an answer:

xpath find if node exists

Secure hash and salt for PHP passwords

In the end, double-hashing, mathematically, provides no benefit. In practice, however, it is useful for preventing rainbow table-based attacks. In other words, it is of no more benefit than hashing with a salt, which takes far less processor time in your application or on your server.

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Refresh Fragment at reload

you can refresh your fragment when it is visible to user, just add this code into your Fragment this will refresh your fragment when it is visible.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Refresh your fragment here          
  getFragmentManager().beginTransaction().detach(this).attach(this).commit();
        Log.i("IsRefresh", "Yes");
    }
}

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

Generating Unique Random Numbers in Java

This will work to generate unique random numbers................

import java.util.HashSet;
import java.util.Random;

public class RandomExample {

    public static void main(String[] args) {
        Random rand = new Random();
        int e;
        int i;
        int g = 10;
        HashSet<Integer> randomNumbers = new HashSet<Integer>();

        for (i = 0; i < g; i++) {
            e = rand.nextInt(20);
            randomNumbers.add(e);
            if (randomNumbers.size() <= 10) {
                if (randomNumbers.size() == 10) {
                    g = 10;
                }
                g++;
                randomNumbers.add(e);
            }
        }
        System.out.println("Ten Unique random numbers from 1 to 20 are  : " + randomNumbers);
    }
}

How can I convert an image into a Base64 string?

Instead of using Bitmap, you can also do this through a trivial InputStream. Well, I am not sure, but I think it's a bit efficient.

InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();

try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
}
catch (IOException e) {
    e.printStackTrace();
}

bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

How do I measure request and response times at once using cURL?

This is a modified version of Simons answer which makes the multi-lined output a single line. It also introduces the current timestamp so it's easier to follow each line of output.

Sample format fle
$ cat time-format.txt
time_namelookup:%{time_namelookup} time_connect:%{time_connect} time_appconnect:%{time_appconnect} time_pretransfer:%{time_pretransfer} time_redirect:%{time_redirect} time_starttransfer:%{time_starttransfer} time_total:%{time_total}\n
example cmd
$ while [ 1 ];do echo -n "$(date) - " ; curl -w @time-format.txt -o /dev/null -s https://myapp.mydom.com/v1/endpt-http; sleep 1; done | grep -v time_total:0
results
Mon Dec 16 17:51:47 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:1.666 time_total:1.666
Mon Dec 16 17:51:50 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:3.794 time_total:3.795
Mon Dec 16 17:51:55 UTC 2019 - time_namelookup:0.004 time_connect:0.017 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:1.971 time_total:1.971
Mon Dec 16 17:51:58 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.173 time_pretransfer:0.173 time_redirect:0.000 time_starttransfer:1.161 time_total:1.161
Mon Dec 16 17:52:00 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.166 time_pretransfer:0.167 time_redirect:0.000 time_starttransfer:1.434 time_total:1.434
Mon Dec 16 17:52:02 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.177 time_pretransfer:0.177 time_redirect:0.000 time_starttransfer:5.119 time_total:5.119
Mon Dec 16 17:52:08 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:30.185 time_total:30.185
Mon Dec 16 17:52:39 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.164 time_pretransfer:0.164 time_redirect:0.000 time_starttransfer:30.175 time_total:30.176
Mon Dec 16 17:54:28 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:3.191 time_pretransfer:3.191 time_redirect:0.000 time_starttransfer:3.212 time_total:3.212
Mon Dec 16 17:56:08 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:1.184 time_pretransfer:1.184 time_redirect:0.000 time_starttransfer:1.215 time_total:1.215
Mon Dec 16 18:00:24 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.181 time_pretransfer:0.181 time_redirect:0.000 time_starttransfer:1.267 time_total:1.267

I used the above to catch slow responses on the above endpoint.

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

How can I perform a short delay in C# without using sleep?

If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.

How it works is that you mark the function in need of asynchronous operations, with the async keyword. This is just a hint to the compiler. Then you use the await keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async keyword as well and is usually named ending with Async, as in ImportFilesAsync.

What you need to do in your example is:

  1. Make sure your program has .Net Framework 4.5 as Target Framework
  2. Mark your function that needs to sleep with the async keyword (see example below)
  3. Add using System.Threading.Tasks; to your code.

Your code is now ready to use the Task.Delay method instead of the System.Threading.Thread.Sleep method (it is possible to use await on Task.Delay because Task.Delay is marked with async in its definition).

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "\r\nThread Sleeps!";
    await Task.Delay(3000);
    textBox1.Text += "\r\nThread awakens!";
}

Here you can read more about Task.Delay and Await.

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Spring Boot access static resources missing scr/main/resources

You can use following code to read file in String from resource folder.

final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
     publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
     e.printStackTrace();
}

EnterKey to press button in VBA Userform

This one worked for me

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
             Button1_Click
        End If
End Sub

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

How to select date from datetime column?

simple and best way to use date function

example

SELECT * FROM 
data 
WHERE date(datetime) = '2009-10-20' 

OR

SELECT * FROM 
data 
WHERE date(datetime ) >=   '2009-10-20'  && date(datetime )  <= '2009-10-20'

How do I Merge two Arrays in VBA?

To join Array1 and Array2, create a new array say JointArray

Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
    If i <= UBound(Array1) Then
    JointArray(i) = Array1(i)
    Else
    JointArray(i) = Array2(i - UBound(Array1) - 1)
    End If
Next

Smart way to truncate long strings

('long text to be truncated').replace(/(.{250})..+/, "$1…");

Somehow above code was not working for some kind of copy pasted or written text in vuejs app. So I used lodash truncate and its now working fine.

_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

Java 'file.delete()' Is not Deleting Specified File

Problem is that check weather you have closed all the streams or not if opened close the streams and delete,rename..etc the file this is worked for me

Storing a file in a database as opposed to the file system?

If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.

Getting Started with FILESTREAM Storage

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

With adb, you can install GApps and ARM Support zips without a drag & drop. emuking from XDA Developers has instructions for it:

I used 4.2.2, which is acceptable for my testing purposes. I then extracted both zip's "/system/..." folders to a folder on my desktop. In cmd prompt I used the following commands (step 1 is optional and for verification that adb is working):

  1. adb devices
  2. adb remount
  3. adb push "C:\Users\John\Desktop\GenyF_cked\system" /system

You'll have to change the folder name in "adb push" line to where you actually extracted both zip files. After doing it, I recommend you to "adb reboot" the device.

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

My docker container has no internet

for me, my problem was because of iptables-services was not installed, this worked for me (CentOS):

sudo yum install iptables-services
sudo service docker restart

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

The multi-part identifier could not be bound

If this error happens in an UPDATE, double-check the JOIN on the table with the column/field that is causing the error.

In my case this was due to the lack of the JOIN itself, which generated the same error due to an unknown field (as Andriy pointed out).

Purpose of __repr__ method?

The __repr__ method simply tells Python how to print objects of a class

How to set the height and the width of a textfield in Java?

You should not play with the height. Let the text field determine the height based on the font used.

If you want to control the width of the text field then you can use

textField.setColumns(...);

to let the text field determine the preferred width.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

See the Swing tutorial on Layout Managers for more information.

Making TextView scrollable on Android

For a vertically or horizontally scrollable TextView some of the other answers help, but I needed to be able to scroll both ways.

What finally worked is a ScrollView with a HorizontalScrollView inside of it, and a TextView inside the HSV. It's very smooth and can easily go side to side or top to bottom in one swipe. It also only allows scrolling in one direction at a time so there's none of the jumping side to side while scrolling up or down.

An EditText with editing and cursor disabled works, but it feels terrible. Each attempt to scroll moves the cursor and it requires many swipes to go top to bottom or side to side in even a ~100-line file.

Using setHorizontallyScrolling(true) can work, but there's no similar method to allow vertical scrolling, and it doesn't work inside of a ScrollView as far as I can tell (just learning though, could be wrong).

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

How do you get the Git repository's name in some Git repository?

Unfortunately, it seems that Git has no such command built in. But you can easily add it yourself with Git aliases and some shell magic.

As pointed out by this answer, you can use git rev-parse --show-toplevel to show the root of your current Git folder.

If you want to use this regularly, it's probably more convenient to define it as an alias. For this, used git config alias.root '!echo "$(git rev-parse --show-toplevel)"'. After this, you can use git root to see the root folder of the repository you're currently in.

If you want to use another subcommand name than root, simply replace the second part of alias.root in the above command with whatever you want.

For details on aliases in Git, see also the git config man page.

Remove 'b' character do in front of a string literal in Python 3

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding

Spring configure @ResponseBody JSON format

Take a look at Rick Hightower's approach. His approach avoids configuring ObjectMapper as a singleton and allows you to filter the JSON response for the same object in different ways per each request method.

http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring

What's the purpose of META-INF?

From the official JAR File Specification (link goes to the Java 7 version, but the text hasn't changed since at least v1.3):

The META-INF directory

The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services:

  • MANIFEST.MF

The manifest file that is used to define extension and package related data.

  • INDEX.LIST

This file is generated by the new "-i" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.

  • x.SF

The signature file for the JAR file. 'x' stands for the base file name.

  • x.DSA

The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.

  • services/

This directory stores all the service provider configuration files.

Apache default VirtualHost

I will say what worked for me, the others answers above didn't help to my case at all. I hope it can help someone.

Actually, I'm using Virtual host configuration (sites-available / sites-enabled) on EC2 Linux AMI with Apache/2.4.39 (Amazon). So, I have 1 ec2 instance to serve many sites (domains).

Considering that you already have Virtual Host installed and working. In my folder /etc/httpd/sites-available, I have some files with domain names (suffix .conf), for example: domain.com.conf. Create a new file like that.

sudo nano /etc/httpd/sites-available/domain.com.conf

<VirtualHost *:80>
    ServerName www.domain.com
    ServerAlias domain.com
    DocumentRoot /var/www/html/domain
</VirtualHost>

For each file.conf in sites-available, I create a symbolic link:

sudo ln -s /etc/httpd/sites-available/domain.com.conf /etc/httpd/sites-enabled/domain.com.conf

This is the default configuration, so, if access directly by IP of Server, you will be redirect to DocumentRoot of the first file (.conf) in sites-available folder, sorted by filename.

To have a default DocumentRoot folder when access by IP, you have to create a file named 0a.conf, then apache will serve this site because this new file will be the first in sites-available folder.

You must create a symbolic link:

sudo ln -s /etc/httpd/sites-available/0a.conf /etc/httpd/sites-enabled/0a.conf

To check serving order, use it:

sudo apachectl -S

Now, restart apache, and check out it.

Be happy =)

Copying files from server to local computer using SSH

that scp command must be issued on the local command-line, for putty the command is pscp.

C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\

Drawing rotated text on a HTML5 canvas

Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:

ctx.rotate(Math.PI*2/(i*6));

The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

Please see the answer below for a more complete solution.

Change arrow colors in Bootstraps carousel

With Font Awesome icons:

<!-- Controls -->
<a class="carousel-control-prev" href="#carousel-example-generic" role="button" data-slide="prev">
  <span class="fa fa-chevron-left fa-lg" style="color:red;"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-generic" role="button" data-slide="next">
  <span class="fa fa-chevron-right fa-lg" style="color:red;"></span>
  <span class="sr-only">Next</span>
</a>

How to use FormData for AJAX file upload?

Actually The documentation shows that you can use XMLHttpRequest().send() to simply send multiform data in case jquery sucks

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).

In MySQL, a user is identified by both a username ("test2") and a host ("localhost").

The error message identifies the user ("test2") and the host ("localhost") values...

  'test2'@'localhost'

We can check to see if the user exists, using this query from a client we can connect from:

 SELECT user, host FROM mysql.user

We're looking for a row that has "test2" for user, and "localhost" for host.

 user     host       
 -------  -----------
 test2     127.0.0.1  cleanup
 test2     ::1        
 test2     localhost  

If that row doesn't exist, then the host may be set to wildcard value of %, to match any other host that isn't a match.

If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root

 SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')

We can also verify that the user has privileges on objects in the database.

 GRANT SELECT ON jobs.* TO 'test2'@'localhost' 

EDIT

If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES statement, executed by a privileged user.

Android Studio - Device is connected but 'offline'

In my case, turned out that you need to be logged as owner of device to properly accept the USB debugging.

Tried the "Disable and re-enable USB debugging on the phone" step but didn't get the RSA prompt on "normal" user, switched to owner and tried again and got it.

How to right-align and justify-align in Markdown?

Aligning text in native markdown is not possible. However, you can align the text using inline HTML tags.

<div style="text-align: right"> your-text-here </div>

To justify, replace right with justify in the above.

Do I use <img>, <object>, or <embed> for SVG files?

I recommend using the combination of

<svg viewBox="" width="" height="">
<path fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
</svg>

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.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

How to capture Enter key press?

<form action="#">
    <input type="text" id="txtBox" name="txt" onkeypress="handle" />
</form>






<script>
    $("#txtBox").keypress(function (e) {
            if (e.keyCode === 13) {
                alert("Enter was pressed was presses");
            }

            return false;
        });

    </script>

How to vertically align text inside a flexbox?

The best move is to just nest a flexbox inside of a flexbox. All you have to do is give the child align-items: center. This will vertically align the text inside of its parent.

// Assuming a horizontally centered row of items for the parent but it doesn't have to be
.parent {
  align-items: center;
  display: flex;
  justify-content: center;
}

.child {
  display: flex;
  align-items: center;
}

add/remove active class for ul list with jquery?

I used this:

$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');

Since the active class is in the <li> element and what is clicked is the <a> element, the first line removes .active from all <li> and the second one (again, $(this) represents <a> which is the clicked element) adds .active to the direct parent, which is <li>.

Disabling browser print options (headers, footers, margins) from page?

Try this code, works 100% for me:
FOR Landscape:

<head>
<style type="text/css">

@page{
  size: auto A4 landscape;
  margin: 3mm;
}

</style>
</head>

FOR Portait:

<head>
<style type="text/css">

@page{
  size: auto;
  margin: 3mm;
}

</style>
</head>

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

In Swift 3.0, register a class for your UITableViewCell like this :

tableView.register(UINib(nibName: "YourCellXibName", bundle: nil), forCellReuseIdentifier: "Cell")

When should a class be Comparable and/or Comparator?

The text below comes from Comparator vs Comparable

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

How do you check current view controller class in Swift?

Try this

if self is MyViewController {        

}

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();

Why is processing a sorted array faster than processing an unsorted array?

Besides the fact that the branch prediction may slow you down, a sorted array has another advantage:

You can have a stop condition instead of just checking the value, this way you only loop over the relevant data, and ignore the rest.
The branch prediction will miss only once.

 // sort backwards (higher values first), may be in some other part of the code
 std::sort(data, data + arraySize, std::greater<int>());

 for (unsigned c = 0; c < arraySize; ++c) {
       if (data[c] < 128) {
              break;
       }
       sum += data[c];               
 }

Android ADT error, dx.jar was not loaded from the SDK folder

I just encountered the same problem yesterday, in Eclipse of Neon Release (4.6.0).

It's a compatible issue related to 26.0.0 of android-sdk "build-tools".

Simple Solution:

  • Delete "26.0.0" in "build-tools" directory
  • Use "25.0.2" instead
  • Restart eclipse

Other Solution:

  • add this in the project.properties of your project:
    sdk.buildtools=25.0.2

Good luck!

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Add an = at the beginning. That makes it a function rather than an entry.

Javascript to display the current date and time

The request was to format a date in this format:

Fri Aug 30 2013 4:36 pm

I strongly suggest that anyone who comes across this question should use JavaScript's Intl API to format your dates instead of trying to come up with your own preferred format.

Here's an example

_x000D_
_x000D_
let d = new Date();
let formatter = Intl.DateTimeFormat(
    "default", // a locale name; "default" chooses automatically
    {
        weekday: "short", 
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "numeric",
        minute: "numeric"
    }
);

console.log(formatter.format(d));
_x000D_
_x000D_
_x000D_

The output for me, in the en-US locale, is:

Wed, Sep 30, 2020, 5:04 PM

The output for someone in Mexico (es-MX), is:

mié., 30 de septiembre de 2020 17:23

Why is Intl better?

  1. It's native code, with no string manipulation, no extra frameworks required, just a browser from any time after 2013 (when this question was first posted)
    • Nothing to download
    • No frameworks to add
    • Native code runs faster
  2. Intl formats dates as appropriate for the user's locale, e.g. a user in a different country who would prefer to read the year before the month would see the appropriately formatted date

How do I `jsonify` a list in Flask?

This is working for me. Which version of Flask are you using?

from flask import jsonify

...

@app.route('/test/json')
def test_json():
    list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
    return jsonify(results = list)

Global npm install location on windows?

According to: https://docs.npmjs.com/files/folders

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

Can you write virtual functions / methods in Java?

From wikipedia

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

jQuery: load txt file and insert into div

Try

$(".text").text(data);

Or to convert the data received to a string.

Windows batch - concatenate multiple text files into one

At its most basic, concatenating files from a batch file is done with 'copy'.

copy file1.txt + file2.txt + file3.txt concattedfile.txt

How to remove all leading zeroes in a string

I don't think preg_replace is the answer.. old thread but just happen to looking for this today. ltrim and (int) casting is the winner.

<?php
 $numString = "0000001123000";
 $actualInt = "1123000";

 $fixed_str1 = preg_replace('/000+/','',$numString);
 $fixed_str2 = ltrim($numString, '0');
 $fixed_str3 = (int)$numString;

 echo $numString . " Original";
 echo "<br>"; 
 echo $fixed_str1 . " Fix1";
 echo "<br>"; 
 echo $fixed_str2 . " Fix2";
 echo "<br>";
 echo $fixed_str3 . " Fix3";
 echo "<br>";
 echo $actualInt . " Actual integer in string";

 //output

 0000001123000 Origina
 1123 Fix1
 1123000 Fix2
 1123000 Fix3
 1123000 Actual integer in tring

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

Python 2

The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u prefix on strings, i.e. u'€' or by decoding a string with mystr.decode('utf-8') using the appropriate encoding.

The best practice is to decode all text data as it's read, rather than decoding mid-program. The io module provides an open() method which decodes text data to Unicode strings as it's read.

ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write() method.

Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write() and adds the relevant header.

Presuming your input file is UTF-8 encoded (0xC2 is common UTF-8 lead byte), putting everything together, and using the with statement, your code should look like:

with io.open('myText.txt', "r", encoding='utf-8') as f:
    data = f.read()

root = ET.Element("add")
doc = ET.SubElement(root, "doc")

field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data

tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)

Output:

<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>

Best practice to call ConfigureAwait for all server-side code

Update: ASP.NET Core does not have a SynchronizationContext. If you are on ASP.NET Core, it does not matter whether you use ConfigureAwait(false) or not.

For ASP.NET "Full" or "Classic" or whatever, the rest of this answer still applies.

Original post (for non-Core ASP.NET):

This video by the ASP.NET team has the best information on using async on ASP.NET.

I had read that it is more performant since it doesn't have to switch thread contexts back to the original thread context.

This is true with UI applications, where there is only one UI thread that you have to "sync" back to.

In ASP.NET, the situation is a bit more complex. When an async method resumes execution, it grabs a thread from the ASP.NET thread pool. If you disable the context capture using ConfigureAwait(false), then the thread just continues executing the method directly. If you do not disable the context capture, then the thread will re-enter the request context and then continue to execute the method.

So ConfigureAwait(false) does not save you a thread jump in ASP.NET; it does save you the re-entering of the request context, but this is normally very fast. ConfigureAwait(false) could be useful if you're trying to do a small amount of parallel processing of a request, but really TPL is a better fit for most of those scenarios.

However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

Actually, just doing an await can do that. Once your async method hits an await, the method is blocked but the thread returns to the thread pool. When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method.

The only difference ConfigureAwait makes in ASP.NET is whether that thread enters the request context when resuming the method.

I have more background information in my MSDN article on SynchronizationContext and my async intro blog post.

How to check if object has any properties in JavaScript?

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

Missing visible-** and hidden-** in Bootstrap v4

i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs                { display:table !important; }
tr.visible-xs                   { display:table-row !important; }
th.visible-xs, td.visible-xs    { display:table-cell !important; }

.visible-xs                 { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}

@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }

.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}

@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }

.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}

@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }

.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}

@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }

.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}

@media (max-width:575px)                        { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px)  { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px)  { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px)                       { .hidden-xl{display:none !important;} }
</pre>

python: how to send mail with TO, CC and BCC?

It did not worked for me until i created:

#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc

and than added cc in recipient [list] like:

s.sendmail(me, [you,cc], msg.as_string())

Generating UML from C++ code?

Here are a few options:

Step-by-Step Guide to Reverse Engineering Code into UML Diagrams with Microsoft Visio 2000 - http://msdn.microsoft.com/en-us/library/aa140255(office.10).aspx

BoUML - http://bouml.fr/features.html

StarUML - http://staruml.sourceforge.net/en/

Reverse engineering of the UML class diagram from C++ code in presence of weakly typed containers (2001) - http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.9064

Umbrello UML Modeller - http://uml.sourceforge.net/

A list of other tools to look at - http://plg.uwaterloo.ca/~migod/uml.html

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How do you set the Content-Type header for an HttpClient request?

For those who didn't see Johns comment to carlos solution ...

req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

How to use the unsigned Integer in Java 8 and Java 9?

If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger.

(Disclaimer: I work for the company behind these libraries)

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

PL/SQL: numeric or value error: character string buffer too small

is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.

for example:

myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26

will fire such an error

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer. However, when a problematic .java file is opened, errors are shown. Try to resolve errors and rebuild the project.

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Simulate low network connectivity for Android

I know it's an old question but...

Some phones nowadays have a setting to utilize 2G only. It's perfect for simulating slow internet on a real device.

enter image description here

Ansible: deploy on multiple hosts in the same time

As of Ansible 2.0 there seems to be an option called strategy on a playbook. When setting the strategy to free, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.

It looks something like this (taken from the above link):

- hosts: all
  strategy: free
  tasks:
  ...

Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.

EDIT:

It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.

This includes specifying async and poll on a task. The following is taken from the 2nd link I mentioned:

- name: simulate long running op, allow to run for 45 sec, fire and forget
  command: /bin/sleep 15
  async: 45
  poll: 0

I guess you can specify longer async times if your task is lengthy. You can probably define your three concurrent task this way.

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

[ :Unexpected operator in shell programming

Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved

What are the proper permissions for an upload folder with PHP/Apache?

I would go with Ryan's answer if you really want to do this.

In general on a *nix environment, you always want to err on giving away as little permissions as possible.

9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.

Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service: move_uploaded_file

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

How to use SQL LIKE condition with multiple values in PostgreSQL?

Perhaps using SIMILAR TO would work ?

SELECT * from table WHERE column SIMILAR TO '(AAA|BBB|CCC)%';

How to move a marker in Google Maps API

moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().

Demo: http://jsfiddle.net/ThinkingStiff/Rsp22/

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}

Script:

function initialize() {

    var myLatLng = new google.maps.LatLng( 50, 50 ),
        myOptions = {
            zoom: 4,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            },
        map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
        marker = new google.maps.Marker( {position: myLatLng, map: map} );

    marker.setMap( map );
    moveBus( map, marker );

}

function moveBus( map, marker ) {

    marker.setPosition( new google.maps.LatLng( 0, 0 ) );
    map.panTo( new google.maps.LatLng( 0, 0 ) );

};

initialize();

How to scan multiple paths using the @ComponentScan annotation?

Provide your package name separately, it requires a String[] for package names.

Instead of this:

@ComponentScan("com.my.package.first,com.my.package.second")

Use this:

@ComponentScan({"com.my.package.first","com.my.package.second"})

m2eclipse error

I am using MacOSX with Eclipse 4.3 (Krepler). What I originally tried was to install Maven via the terminal using Brew. It installed correctly Maven 3.0.4. However when I tried to import any ready maven projects (File > Import > Maven) it would display the following two errors:

No marketplace entries found to handle Execution default-testResources

What I did is go to Help > Eclipse Marketplace and type "Maven" in the search bar and install the first default Maven client for Eclipse. Everything worked for me from this point.

Hope it helps to you too.

What is the difference between exit and return?

In C, there's not much difference when used in the startup function of the program (which can be main(), wmain(), _tmain() or the default name used by your compiler).

If you return in main(), control goes back to the _start() function in the C library which originally started your program, which then calls exit() anyways. So it really doesn't matter which one you use.

What is the difference between URI, URL and URN?

URI (Uniform Resource Identifier) according to Wikipedia:

a string of characters used to identify a resource.

URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.

URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax

IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.

How to pass multiple parameters from ajax to mvc controller?

Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/

Git fails when pushing commit to github

in these cases you can try ssh if https is stuck.

Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

Using sed to split a string with a delimiter

To split a string with a delimiter with GNU sed you say:

sed 's/delimiter/\n/g'     # GNU sed

For example, to split using : as a delimiter:

$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you

Or with a non-GNU sed:

$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you

In this particular case, you missed the g after the substitution. Hence, it is just done once. See:

$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5

g stands for global and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.

All together, in your case you would need to use:

sed 's/:/\\n/g' ~/Desktop/myfile.txt

Note that you can directly use the sed ... file syntax, instead of unnecessary piping: cat file | sed.

What is the iPad user agent?

For iPad Only

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

How to make grep only match if the entire line matches?

Most suggestions will fail if there so much as a single leading or trailing space, which would matter if the file is being edited by hand. This would make it less susceptible in that case:

grep '^[[:blank:]]*ABB\.log[[:blank:]]*$' a.tmp

A simple while-read loop in shell would do this implicitly:

while read file
do 
  case $file in
    (ABB.log) printf "%s\n" "$file"
  esac
done < a.tmp