Programs & Examples On #Generator expression

Reactive forms - disabled attribute

I tried these in angular 7. It worked successfully.

this.form.controls['fromField'].reset();
if(condition){
      this.form.controls['fromField'].enable();
}
else{
      this.form.controls['fromField'].disable();
}

What is your favorite C programming trick?

fill in the blanks to print both 'correct' and 'wrong' below:

if(--------)
printf("correct");
else
printf("wrong");

The answer is !printf("correct")

jQuery .val change doesn't change input value

Use attr instead.
$('#link').attr('value', 'new value');

demo

Source file not compiled Dev C++

I was facing the same issue as described above.

It can be resolved by creating a new project and creating a new file in that project. Save the file and then try to build and run.

Hope that helps. :)

What exactly is \r in C language?

Once upon a time, people had terminals like typewriters (with only upper-case letters, but that's another story). Search for 'Teletype', and how do you think tty got used for 'terminal device'?

Those devices had two separate motions. The carriage return moved the print head back to the start of the line without scrolling the paper; the line feed character moved the paper up a line without moving the print head back to the beginning of the line. So, on those devices, you needed two control characters to get the print head back to the start of the next line: a carriage return and a line feed. Because this was mechanical, it took time, so you had to pause for long enough before sending more characters to the terminal after sending the CR and LF characters. One use for CR without LF was to do 'bold' by overstriking the characters on the line. You'd write the line out once, then use CR to start over and print twice over the characters that needed to be bold. You could also, of course, type X's over stuff that you wanted partially hidden, or create very dense ASCII art pictures with judicious overstriking.

On Unix, all the logic for this stuff was hidden in a terminal driver. You could use the stty command and the underlying functions (in those days, ioctl() calls; they were sanitized into the termios interface by POSIX.1 in 1988) to tweak all sorts of ways that the terminal behaved.

Eventually, you got 'glass terminals' where the speeds were greater and and there were new idiosyncrasies to deal with - Hazeltine glitches and so on and so forth. These got enshrined in the termcap and later terminfo libraries, and then further encapsulated behind the curses library.

However, some other (non-Unix) systems did not hide things as well, and you had to deal with CRLF in your text files - and no, this is not just Windows and DOS that were in the 'CRLF' camp.

Anyway, on some systems, the C library has to deal with text files that contain CRLF line endings and presents those to you as if there were only a newline at the end of the line. However, if you choose to treat the text file as a binary file, you will see the CR characters as well as the LF.

Systems like the old Mac OS (version 9 or earlier) used just CR (aka \r) for the line ending. Systems like DOS and Windows (and, I believe, many of the DEC systems such as VMS and RSTS) used CRLF for the line ending. Many of the Internet standards (such as mail) mandate CRLF line endings. And Unix has always used just LF (aka NL or newline, hence \n) for its line endings. And most people, most of the time, manage to ignore CR.

Your code is rather funky in looking for \r. On a system compliant with the C standard, you won't see the CR unless the file is opened in binary mode; the CRLF or CR will be mapped to NL by the C runtime library.

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

fetch from origin with deleted remote branches?

If git fetch -p origin does not work for some reason (like because the origin repo no longer exists or you are unable to reach it), another solution is to remove the information which is stored locally on that branch by doing from the root of the repo:

rm .git/refs/remotes/origin/DELETED_BRANCH

or if it is stored in the file .git/packed-refs by deleting the corresponding line which is like

7a9930974b02a3b31cb2ebd17df6667514962685 refs/remotes/origin/DELETED_BRANCH

Ruby on Rails: Where to define global constants?

The global variable should be declare in config/initializers directory

COLOURS = %w(white blue black red green)

How to stop an animation (cancel() does not work)

What you can try to do is get the transformation Matrix from the animation before you stop it and inspect the Matrix contents to get the position values you are looking for.

Here are the api's you should look into

public boolean getTransformation (long currentTime, Transformation outTransformation)

public Matrix getMatrix ()

public void getValues (float[] values)

So for example (some pseudo code. I have not tested this):

Transformation outTransformation = new Transformation();
myAnimation.getTransformation(currentTime, outTransformation);
Matrix transformationMatrix = outTransformation.getMatrix();
float[] matrixValues = new float[9];
transformationMatrix.getValues(matrixValues);
float transX = matrixValues[Matrix.MTRANS_X];
float transY = matrixValues[Matrix.MTRANS_Y];

How do you disable viewport zooming on Mobile Safari?

Your code is displaying attribute double quotes as fancy double quotes. If the fancy quotes are present in your actual source code I would guess that is the problem.

This works for me on Mobile Safari in iOS 4.2.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

CSS3 Spin Animation

The only answer which gives the correct 359deg:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}

&.active {
  animation: spin 1s linear infinite;
}

Here's a useful gradient so you can prove it is spinning (if its a circle):

background: linear-gradient(to bottom, #000000 0%,#ffffff 100%);

How to get controls in WPF to fill available space?

Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.

The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.

The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.

How to use a WSDL

If you want to add wsdl reference in .Net Core project, there is no "Add web reference" option.

To add the wsdl reference go to Solution Explorer, right-click on the References project item and then click on the Add Connected Service option.

enter image description here

Then click 'Microsoft WCF Web Service Reference':

enter image description here

Enter the file path into URI text box and import the WSDL:

enter image description here

It will generate a simple, very basic WCF client and you to use it something like this:

YourServiceClient client = new YourServiceClient();
client.DoSomething();

Stashing only staged changes in git - is it possible?

I haven't seen this solution that requires no use of git stash :

You don't even need to use git stash at all. You can work this out using a dedicated branch as covered here (branches are cheap).

Indeed, you can isolate separately un- and staged changes with a few consecutive commands that you could bundle together into a git alias :

Create and switch to an new branch where you'll commit separately staged and unstaged changes : see here

At any moment you can git cherry-pick -e one commit from the created branch to apply it where you want (-e to change its commit message).

When you don't need it anymore, you can delete this "stash branch". You may have to use the -D option to force deletion (instead of the -d normal option) because said branch is not merged and git might consider that you risk losing data if you delete it. That is true if you haven't cherry-picked commits that were on it before deletion :

git branch -D separated-stashes

You can also add an alias to your ~/.gitconfig in order to automate this behavior :

git config --global alias.bratisla '!git switch -c separated-stashes; git commit -m "staged changes"; git add -u; git commit -m "unstaged changes"; git switch -' # why this name ? : youtu.be/LpE1bJp8-4w

before "stashing"
after "stashing"



Of course, you can also achieve the same result using two consecutive stashes

As stated in other answers, you have some ways to stash only unstaged or only staged changes using git stash (-k|--keep-index) in combination with other commands.

I personally find the -k option very confusing, as it stashes everything but keeps staged changes in staged state (that explains why "--keep-index"). Whereas stashing something usually moves it to a stash entry. With -k the unstaged changes are stashed normally, but staged ones are just copied to the same stash entry.


Step 0 : you have two things in your git status : a file containing staged changes, and another one containing unstaged changes.

Step 1 : stash unstaged + staged changes but keep the staged ones in the index :

git stash -k -m "all changes"

The -m "..." part is optional, git stash -k is actually an alias for git stash push -k (that does not push anything remotely btw don't worry) which accepts a -m option to label you stash entries for clarity (like a commit message or a tag but for a stash entry). It is the newer version of the deprecated git stash save.


Step 1bis (optional) :

git stash

Stash staged changes (that are still in the index). This step is not necessary for the following, but shows that you can put only staged changes in a stash entry if you want to. If you use this line you have to git stash (pop|apply) && git add -u before continuing on step 2.


Step 2 :

git commit -m "staged changes"

Makes a commit containing only staged changes from step 0, it contains the same thing as the stash entry from step 1bis.


Step 3 :

git stash (pop|apply)

Restores the stash from step 1. Note that this stash entry contained everything, but since you already committed staged changes, this stash will only add unstaged changes from step 0.

nb: "restore" here does NOT mean "git restore", which is a different command.


Step 4 :

git add -u

Adds the popped stash's content to the index


Step 5 :

git commit -m "unstaged changes"

"Unstaged" here, as "staged" in steps 2 and 3's comments, refers to step 0. You are actually staging and committing the "staged changes" from step 0.


Done ! You now have two separated commits containing (un)staged changes from step 0. You may want to amend/rebase them for either additional changes or to rename/drop/squash them. Depending on what you did with your stash's stack (pop or apply), you might also want to git stash (drop|clear) it. You can see you stash entries with git stash (list|show)

What's the meaning of System.out.println in Java?

System is a class in java.lang package.

out is the static data member in System class and reference variable of PrintStream class.

Println() is a normal (overloaded) method of PrintStream class.

View the change history of a file using Git versioning

If you are using eclipse with the git plugin, it has an excellent comparison view with history. Right click the file and select "compare with"=> "history"

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Which selector do I need to select an option by its text?

For jquery version 1.10.2 below worked for me

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });

How to get all of the IDs with jQuery?

for(i=1;i<13;i++)     
{

   alert($("#tdt"+i).val());  

}  

Copy file from source directory to binary directory using CMake

I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$ Directory of main file (.exe, .so.1.2, .a).

add_custom_command(
  TARGET ${PROJECT_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy 
    ${CMAKE_CURRENT_SOURCE_DIR}/input.txt 
    $<TARGET_FILE_DIR:${PROJECT_NAME}>)

In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

How do you log content of a JSON object in Node.js?

This will work with any object:

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));

JQuery Calculate Day Difference in 2 date textboxes

   **This is a simple way of getting the DAYS between two dates** 
    var d1 = moment($("#StartDate").data("DateTimePicker").date());
    var d2 = moment($("#EndDate").data("DateTimePicker").date());

    var diffInDays = d2.diff(d1, 'days');

    if (diffInDays > 0)
    {
        $("#Total").val(diffInDays);
    }
    else
    {
        $("#Total").val(0);
    }

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

Laravel Eloquent groupBy() AND also return count of each group

This is working for me:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

How to iterate through table in Lua?

To iterate over all the key-value pairs in a table you can use pairs:

for k, v in pairs(arr) do
  print(k, v[1], v[2], v[3])
end

outputs:

pears   2   p   green
apples  0   a   red
oranges 1   o   orange

Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr and sort it. Then access arr through the sorted keys:

local ordered_keys = {}

for k in pairs(arr) do
    table.insert(ordered_keys, k)
end

table.sort(ordered_keys)
for i = 1, #ordered_keys do
    local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
    print(k, v[1], v[2], v[3])
end

outputs:

  apples  a   red     5
  oranges o   orange  12
  pears   p   green   7

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

PHP Foreach Arrays and objects

Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

foreach ($arr as $item) {
    echo $item->sm_id;
}

In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

foreach ($arr as $index => $item) {
    echo "Item at index {$index} has sm_id value {$item->sm_id}";
}

Convert Data URI to File then append to FormData

Here is an ES6 version of Stoive's answer:

export class ImageDataConverter {
  constructor(dataURI) {
    this.dataURI = dataURI;
  }

  getByteString() {
    let byteString;
    if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
      byteString = atob(this.dataURI.split(',')[1]);
    } else {
      byteString = decodeURI(this.dataURI.split(',')[1]);
    }
    return byteString;
  }

  getMimeString() {
    return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
  }

  convertToTypedArray() {
    let byteString = this.getByteString();
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return ia;
  }

  dataURItoBlob() {
    let mimeString = this.getMimeString();
    let intArray = this.convertToTypedArray();
    return new Blob([intArray], {type: mimeString});
  }
}

Usage:

const dataURL = canvas.toDataURL('image/jpeg', 0.5);
const blob = new ImageDataConverter(dataURL).dataURItoBlob();
let fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);

How can I check if a string is null or empty in PowerShell?

PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace() is string -notmatch "\S"

("\S" = any non-whitespace character)

> $null  -notmatch "\S"
True
> "   "  -notmatch "\S"
True
> " x "  -notmatch "\S"
False

Performance is very close:

> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
TotalMilliseconds : 3641.2089

> Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
TotalMilliseconds : 4040.8453

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

col = ['a','b','c']

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

What's the difference between git reset --mixed, --soft, and --hard?

Basic difference between various options of git reset command are as below.

  • --soft: Only resets the HEAD to the commit you select. Works basically the same as git checkout but does not create a detached head state.
  • --mixed (default option): Resets the HEAD to the commit you select in both the history and undoes the changes in the index.
  • --hard: Resets the HEAD to the commit you select in both the history, undoes the changes in the index, and undoes the changes in your working directory.

How do I pass the this context to a function?

Another basic example:

NOT working:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
};
img.src = reader.result;

Working:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;

So basically: just add .bind(this) to your function

Set a variable if undefined in JavaScript

It seems to me, that for current javascript implementations,

var [result='default']=[possiblyUndefinedValue]

is a nice way to do this (using object deconstruction).

SQL Server : SUM() of multiple rows including where clauses

The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

What is a .NET developer?

CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

How about simply:

#!/bin/bash

pids=""

for i in `seq 0 9`; do
   doCalculations $i &
   pids="$pids $!"
done

wait $pids

...code continued here ...

Update:

As pointed by multiple commenters, the above waits for all processes to be completed before continuing, but does not exit and fail if one of them fails, it can be made to do with the following modification suggested by @Bryan, @SamBrightman, and others:

#!/bin/bash

pids=""
RESULT=0


for i in `seq 0 9`; do
   doCalculations $i &
   pids="$pids $!"
done

for pid in $pids; do
    wait $pid || let "RESULT=1"
done

if [ "$RESULT" == "1" ];
    then
       exit 1
fi

...code continued here ...

How to have the cp command create any necessary folders for copying a file to a destination

There is no such option. What you can do is to run mkdir -p before copying the file

I made a very cool script you can use to copy files in locations that doesn't exist

#!/bin/bash
if [ ! -d "$2" ]; then
    mkdir -p "$2"
fi
cp -R "$1" "$2"

Now just save it, give it permissions and run it using

./cp-improved SOURCE DEST

I put -R option but it's just a draft, I know it can be and you will improve it in many ways. Hope it helps you

Raising a number to a power in Java

1) We usually do not use int data types to height, weight, distance, temperature etc.(variables which can have decimal points) Therefore height, weight should be double or float. but double is more accurate than float when you have more decimal points

2) And instead of ^, you can change that calculation as below using Math.pow()

bmi = (weight/(Math.pow(height/100, 2)));

3) Math.pow() method has below definition

Math.pow(double var_1, double var_2);

Example:

i) Math.pow(8, 2) is produced 64 (8 to the power 2)

ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

Is there a way to delete all the data from a topic or delete the topic before every run?

As I mentioned here Purge Kafka Queue:

Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:

delete.topic.enable=true

then, you can run this command:

bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test

Running Selenium Webdriver with a proxy in Python

This worked for me and allow to use an headless browser, you just need to call the method passing your proxy.

def setProxy(proxy):
        options = Options()
        options.headless = True
        #options.add_argument("--window-size=1920,1200")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        prox = Proxy()
        prox.proxy_type = ProxyType.MANUAL
        prox.http_proxy = proxy
        prox.ssl_proxy = proxy
        capabilities = webdriver.DesiredCapabilities.CHROME
        prox.add_to_capabilities(capabilities)
        return webdriver.Chrome(desired_capabilities=capabilities, options=options, executable_path=DRIVER_PATH)

Angular 5 Scroll to top on every Route click

I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

Answer from zurfyx original post

to call onChange event after pressing Enter key

You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().

<input
    type="text"
    placeholder="Search..."
    onChange={event => {this.setState({query: event.target.value})}}
    onKeyPress={event => {
                if (event.key === 'Enter') {
                  this.search()
                }
              }}
/>

Close Current Tab

Try this:

<script>
    var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
    this.window.close();
</script>

This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have written a little helper function to replace text in a file:

function Replace-TextInFile
{
    Param(
        [string]$FilePath,
        [string]$Pattern,
        [string]$Replacement
    )

    [System.IO.File]::WriteAllText(
        $FilePath,
        ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
    )
}

Example:

Get-ChildItem . *.config -rec | ForEach-Object { 
    Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new' 
}

How do I remove accents from characters in a PHP string?

The easiest way is to use iconv() PHP native function.

 echo iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', "Thîs îs à vêry wrong séntènce!");

 // output: This is a very wrong sentence!

TypeError: 'str' object is not callable (Python)

In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.

How to delete row in gridview using rowdeleting event?

See the following code and make some changes to get the answer for your question

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    void CustomersGridView_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }  

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView RowDeleting Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        GridView RowDeleting Example
    </h3>
    <asp:Label ID="Message" ForeColor="Red" runat="server" />
    <br />
    <asp:GridView ID="CustomersGridView" runat="server" 
        DataSourceID="CustomersSqlDataSource" 
        AutoGenerateColumns="False"
        AutoGenerateDeleteButton="True" 
        OnRowDeleting="CustomersGridView_RowDeleting"
        DataKeyNames="CustomerID,AddressID">
        <Columns>
            <asp:BoundField DataField="FirstName" 
                HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" 
                SortExpression="City" />
            <asp:BoundField DataField="StateProvince" HeaderText="State" 
                SortExpression="StateProvince" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
        SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
            SalesLT.CustomerAddress.AddressID, 
            SalesLT.Customer.FirstName, 
            SalesLT.Customer.LastName, 
            SalesLT.Address.City, 
            SalesLT.Address.StateProvince 
            FROM SalesLT.Customer 
            INNER JOIN SalesLT.CustomerAddress 
            ON SalesLT.Customer.CustomerID = 
                SalesLT.CustomerAddress.CustomerID 
            INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
                SalesLT.Address.AddressID"
        DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
            @CustomerID and AddressID = @AddressID" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
        <DeleteParameters>
            <asp:Parameter Name="AddressID" />
            <asp:Parameter Name="CustomerID" />
        </DeleteParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

How to change mysql to mysqli?

In case of big projects, many files to change and also if the previous project version of PHP was 5.6 and the new one is 7.1, you can create a new file sql.php and include it in the header or somewhere you use it all the time and needs sql connection. For example:

//local
$sql_host =     "localhost";      
$sql_username = "root";    
$sql_password = "";       
$sql_database = "db"; 


$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

// /* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    // printf("Current character set: %s\n", $mysqli->character_set_name());
}
if (!function_exists('mysql_real_escape_string')) {
    function mysql_real_escape_string($string){
        global $mysqli;
        if($string){
            // $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );            
            $newString =  $mysqli->real_escape_string($string);
            return $newString;
        }
    }
}
// $mysqli->close();
$conn = null;
if (!function_exists('mysql_query')) {
    function mysql_query($query) {
        global $mysqli;
        // echo "DAAAAA";
        if($query) {
            $result = $mysqli->query($query);
            return $result;
        }
    }
}
else {
    $conn=mysql_connect($sql_host,$sql_username, $sql_password);
    mysql_set_charset("utf8", $conn);
    mysql_select_db($sql_database);
}

if (!function_exists('mysql_fetch_array')) {
    function mysql_fetch_array($result){
        if($result){
            $row =  $result->fetch_assoc();
            return $row;
        }
    }
}

if (!function_exists('mysql_num_rows')) {
    function mysql_num_rows($result){
        if($result){
            $row_cnt = $result->num_rows;;
            return $row_cnt;
        }
    }
}

if (!function_exists('mysql_free_result')) {
    function mysql_free_result($result){
        if($result){
            global $mysqli;
            $result->free();

        }
    }
}

if (!function_exists('mysql_data_seek')) {
    function mysql_data_seek($result, $offset){
        if($result){
            global $mysqli;
            return $result->data_seek($offset);

        }
    }
}

if (!function_exists('mysql_close')) {
    function mysql_close(){
        global $mysqli;
        return $mysqli->close();
    }
}

if (!function_exists('mysql_insert_id')) {
    function mysql_insert_id(){
            global $mysqli;
            $lastInsertId = $mysqli->insert_id;
            return $lastInsertId;
    }
}

if (!function_exists('mysql_error')) {
    function mysql_error(){
        global $mysqli;
        $error = $mysqli->error;
        return $error;
    }
}

Convert Long into Integer

The best simple way of doing so is:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }

How to delete an app from iTunesConnect / App Store Connect

Edit December 2018: Apple seem to have finally added a button for removing the app in certain situations, including apps that never went on sale (thanks to @iwill for pointing that out), basically making the below answer irrelevant.

Edit: turns out the deleted apps still appear in Xcode -> Organizer -> Archives and there is no way to delete them from there even if there are no archives! So more looks like a fake delete of sorts.


Currently (Edit: as of July 2016) there is no way of deleting your app if it never went on sale.

However, all information except for SKU can be edited and thus reused for a new app, including the app name, Bundle ID, icon, etc etc. Because SKU can be anything (some people say they use numbers 1, 2, 3 for example) then it shouldn't be a big deal to use something unrelated for your new app.

(Honestly though I'm hoping Apple will fix this soon. I almost hear some Apple devs finding excuses for not implementing it (you know, it will break the database and will kill innocent pandas) and some managers telling the devs to just frigging do it regardless.)

How do I install a color theme for IntelliJ IDEA 7.0.x

Themes downloaded from IntelliJ can be installed as a Plugin.

Take these steps:

Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE ->  Preferences -> Appearance -> Theme -> Select your theme.

case statement in SQL, how to return multiple variables?

In a SQL CASE clause, the first successfully matched condition is applied and any subsequent matching conditions are ignored.

How do I iterate through table rows and cells in JavaScript?

Better solution: use Javascript's native Array.from() and to convert HTMLCollection object to an array, after which you can use standard array functions.

var t = document.getElementById('mytab1');
if(t) {
    Array.from(t.rows).forEach((tr, row_ind) => {
        Array.from(tr.cells).forEach((cell, col_ind) => {
            console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
        });
    });
}

You could also reference tr.rowIndex and cell.colIndex instead of using row_ind and col_ind.

I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i, j, row and col, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery).

If you require this to run in an old version (pre-ES2015) of Javascript, Array.from can be polyfilled.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

Retrieve only the queried element in an object array in MongoDB collection

Along with $project it will be more appropriate other wise matching elements will be clubbed together with other elements in document.

db.test.aggregate(
  { "$unwind" : "$shapes" },
  { "$match" : { "shapes.color": "red" } },
  { 
    "$project": {
      "_id":1,
      "item":1
    }
  }
)

How can I provide multiple conditions for data trigger in WPF?

Use MultiDataTrigger type

<Style TargetType="ListBoxItem">
    <Style.Triggers>
      <DataTrigger Binding="{Binding Path=State}" Value="WA">
        <Setter Property="Foreground" Value="Red" />
      </DataTrigger>    
      <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding Path=Name}" Value="Portland" />
          <Condition Binding="{Binding Path=State}" Value="OR" />
        </MultiDataTrigger.Conditions>
        <Setter Property="Background" Value="Cyan" />
      </MultiDataTrigger>
    </Style.Triggers>
  </Style>

python pandas extract year from datetime: df['year'] = df['date'].year is not working

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

EDIT

It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

Using HTML and Local Images Within UIWebView

Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

You can then refer to your images like this:

<img src="myimage.png">

(from uiwebview revisited)

Google MAP API v3: Center & Zoom on displayed markers

Try this function....it works...

$(function() {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var latlng_pos=[];
        var j=0;
         $(".property_item").each(function(){
            latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
            j++;
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                // position: new google.maps.LatLng(-35.397, 150.640),
                map: map
            });
        }
        );
        // map: an instance of google.maps.Map object
        // latlng: an array of google.maps.LatLng objects
        var latlngbounds = new google.maps.LatLngBounds( );
        for ( var i = 0; i < latlng_pos.length; i++ ) {
            latlngbounds.extend( latlng_pos[ i ] );
        }
        map.fitBounds( latlngbounds );



    });

Possible reasons for timeout when trying to access EC2 instance

For me it was the apache server hosted on a t2.micro linux EC2 instance, not the EC2 instance itself.

I fixed it by doing:

sudo su

service httpd restart

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

DevTools failed to load SourceMap: Could not load content for chrome-extension

Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:

  1. Right click on the extension icon.

Or

  1. Go to extensions.
  2. Click the three-dot in the row of React developer tool.

Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.

write newline into a file

To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.

To write each word on a new line, use String.split to break your text into an array of words.

So here's a simple test of your requirement:

public static void main(String[] args) throws Exception {
    String nodeValue = "i am mostafa";

    // you want to output to file
    // BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
    // but let's print to console while debugging
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    String[] words = nodeValue.split(" ");
    for (String word: words) {
        writer.write(word);
        writer.newLine();
    }
    writer.close();
}

The output is:

i
am
mostafa

getting only name of the class Class.getName()

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

Add new row to dataframe, at specific row-index, not appended?

Here's a solution that avoids the (often slow) rbind call:

existingDF <- as.data.frame(matrix(seq(20),nrow=5,ncol=4))
r <- 3
newrow <- seq(4)
insertRow <- function(existingDF, newrow, r) {
  existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
  existingDF[r,] <- newrow
  existingDF
}

> insertRow(existingDF, newrow, r)
  V1 V2 V3 V4
1  1  6 11 16
2  2  7 12 17
3  1  2  3  4
4  3  8 13 18
5  4  9 14 19
6  5 10 15 20

If speed is less important than clarity, then @Simon's solution works well:

existingDF <- rbind(existingDF[1:r,],newrow,existingDF[-(1:r),])
> existingDF
   V1 V2 V3 V4
1   1  6 11 16
2   2  7 12 17
3   3  8 13 18
4   1  2  3  4
41  4  9 14 19
5   5 10 15 20

(Note we index r differently).

And finally, benchmarks:

library(microbenchmark)
microbenchmark(
  rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
  insertRow(existingDF,newrow,r)
)

Unit: microseconds
                                                    expr     min       lq   median       uq       max
1                       insertRow(existingDF, newrow, r) 660.131 678.3675 695.5515 725.2775   928.299
2 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 801.161 831.7730 854.6320 881.6560 10641.417

Benchmarks

As @MatthewDowle always points out to me, benchmarks need to be examined for the scaling as the size of the problem increases. Here we go then:

benchmarkInsertionSolutions <- function(nrow=5,ncol=4) {
  existingDF <- as.data.frame(matrix(seq(nrow*ncol),nrow=nrow,ncol=ncol))
  r <- 3 # Row to insert into
  newrow <- seq(ncol)
  m <- microbenchmark(
   rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
   insertRow(existingDF,newrow,r),
   insertRow2(existingDF,newrow,r)
  )
  # Now return the median times
  mediansBy <- by(m$time,m$expr, FUN=median)
  res <- as.numeric(mediansBy)
  names(res) <- names(mediansBy)
  res
}
nrows <- 5*10^(0:5)
benchmarks <- sapply(nrows,benchmarkInsertionSolutions)
colnames(benchmarks) <- as.character(nrows)
ggplot( melt(benchmarks), aes(x=Var2,y=value,colour=Var1) ) + geom_line() + scale_x_log10() + scale_y_log10()

@Roland's solution scales quite well, even with the call to rbind:

                                                              5       50     500    5000    50000     5e+05
insertRow2(existingDF, newrow, r)                      549861.5 579579.0  789452 2512926 46994560 414790214
insertRow(existingDF, newrow, r)                       895401.0 905318.5 1168201 2603926 39765358 392904851
rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 787218.0 814979.0 1263886 5591880 63351247 829650894

Plotted on a linear scale:

linear

And a log-log scale:

log-log

How do I break a string in YAML over multiple lines?

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: | In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.

How to select the nth row in a SQL database table?

1 small change: n-1 instead of n.

select *
from thetable
limit n-1, 1

How to determine the current iPhone/device model?

Simplest way to get model name (marketing name)

Use private API -[UIDevice _deviceInfoForKey:] carefully, you won't be rejected by Apple,

// works on both simulators and real devices, iOS 8 to iOS 12
NSString *deviceModelName(void) {
    // For Simulator
    NSString *modelName = NSProcessInfo.processInfo.environment[@"SIMULATOR_DEVICE_NAME"];
    if (modelName.length > 0) {
        return modelName;
    }

    // For real devices and simulators, except simulators running on iOS 8.x
    UIDevice *device = [UIDevice currentDevice];
    NSString *selName = [NSString stringWithFormat:@"_%@ForKey:", @"deviceInfo"];
    SEL selector = NSSelectorFromString(selName);
    if ([device respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        modelName = [device performSelector:selector withObject:@"marketing-name"];
#pragma clang diagnostic pop
    }
    return modelName;
}

How did I get the key "marketing-name"?

Running on a simulator, NSProcessInfo.processInfo.environment contains a key named "SIMULATOR_CAPABILITIES", the value of which is a plist file. Then you open the plist file, you will get the model name's key "marketing-name".

JavaScript function to add X months to a date

Taken from @bmpsini and @Jazaret responses, but not extending prototypes: using plain functions (Why is extending native objects a bad practice?):

function isLeapYear(year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
}

function getDaysInMonth(year, month) {
    return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}

function addMonths(date, value) {
    var d = new Date(date),
        n = date.getDate();
    d.setDate(1);
    d.setMonth(d.getMonth() + value);
    d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));
    return d;
}

Use it:

var nextMonth = addMonths(new Date(), 1);

How to get all checked checkboxes

Get all the checked checkbox value in an array - one liner

_x000D_
_x000D_
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

Android Studio AVD - Emulator: Process finished with exit code 1

These are known errors from libGL and libstdc++

You can quick fix this by change to use Software for Emulated Performance Graphics option, in the AVD settings.

Or try to use the libstdc++.so.6 (which is available in your system) instead of the one bundled inside Android SDK. There are 2 ways to replace it:

  • The emulator has a switch -use-system-libs. You can found it here: ~/Android/Sdk/tools/emulator -avd Nexus_5_API_23 -use-system-libs.

    This option force Linux emulator to load the system libstdc++ (but not Qt libraries), in cases where the bundled ones (from Android SDK) prevent it from loading or working correctly. See this commit

  • Alternatively you can set the ANDROID_EMULATOR_USE_SYSTEM_LIBS environment variable to 1 for your user/system.

    This has the benefit of making sure that the emulator will work even if you launched it from within Android Studio.

See: libGL error and libstdc++: Cannot launch AVD in emulator - Issue Tracker

To get specific part of a string in c#

To avoid getting expections at run time , do something like this.

There are chances of having empty string sometimes,

string a = "abc,xyz,wer";
string b=string.Empty;

if(!string.IsNullOrEmpty(a ))
{
  b = a.Split(',')[0];
}

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

List all employee's names and their managers by manager name using an inner join

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno

If you want to get the result for all the records (irrespective of whether they report to anyone or not), append (+) on the second table's name

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno(+)

check android application is in foreground or not?

None of the solutions base on getRunningTasks() works in recent Android versions, getRunningTasks() was deprecated in API level 21. Even if it is still used it does not return enough information to determine if the app is in the foreground.

Instead extend the Application class and use Application.ActivityLifecycleCallbacks to track application visibility state.

public class MyApplication extends Application {
    static final String APP_STATE_FOREGROUND = "com.xxx.appstate.FOREGROUND";
    static final String APP_STATE_BACKGROUND = "com.xxx.appstate.BACKGROUND";
    private static int m_foreground = -1;
    private Handler m_handler = new Handler();
    private Runnable m_guard;

    public static boolean isForeground() {
        return m_foreground == 1;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if(m_guard != null) {
                    m_handler.removeCallbacks(m_guard);
                    m_guard = null;
                }
                if(m_foreground == 1)
                    return;
                m_foreground = 1;
                sendBroadcast(new Intent(APP_STATE_FOREGROUND));
            }

            @Override
            public void onActivityPaused(Activity activity) {
                if(m_foreground == 0)
                    return;
                /*
                 * Use a 400ms guard to protect against jitter
                 * when switching between two activities
                 * in the same app
                 */
                m_guard = new Runnable() {
                    @Override
                    public void run() {
                        if(m_foreground == 1) {
                            m_foreground = 0;
                            sendBroadcast(new Intent(APP_STATE_BACKGROUND));
                        }
                    }
                };
                m_handler.postDelayed(m_guard, 400);
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }
}

Using the 400ms guard timer eliminates false detection of background state when switching between activities in the same app. The background/foreground state can be queried at anytime using:

MyApplication.isForeground();

A class can also listen for the broadcast events if it is interested in the state transitions:

private static IntentFilter m_appStateFilter;

static {
    m_appStateFilter = new IntentFilter();
    m_appStateFilter.addAction(MyApplication.APP_STATE_FOREGROUND);
    m_appStateFilter.addAction(MyApplication.APP_STATE_BACKGROUND);
}

private BroadcastReceiver m_appStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(MyApplication.APP_STATE_FOREGROUND)) {
            /* application entered foreground */
        } else if (action.equals(MyApplication.APP_STATE_BACKGROUND)) {
            /* application entered background */
        }
    }
};
registerReceiver(m_appStateReceiver, m_appStateFilter);

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

How do I delete an exported environment variable?

Because the original question doesn't mention how the variable was set, and because I got to this page looking for this specific answer, I'm adding the following:

In C shell (csh/tcsh) there are two ways to set an environment variable:

  1. set x = "something"
  2. setenv x "something"

The difference in the behaviour is that variables set with setenv command are automatically exported to subshell while variable set with set aren't.

To unset a variable set with set, use

unset x

To unset a variable set with setenv, use

unsetenv x

Note: in all the above, I assume that the variable name is 'x'.

credits:

https://www.cyberciti.biz/faq/unix-linux-difference-between-set-and-setenv-c-shell-variable/ https://www.oreilly.com/library/view/solaristm-7-reference/0130200484/0130200484_ch18lev1sec24.html

How to determine whether a substring is in a different string

foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something

(By the way - try to not name a variable string, since there's a Python standard library with the same name. You might confuse people if you do that in a large project, so avoiding collisions like that is a good habit to get into.)

Postgresql Select rows where column = array

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])

or ANSI-compatible:

SELECT  *
FROM    table
WHERE   some_id IN (1, 2)

The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

SELECT  *
FROM    table
WHERE   some_id = ANY(?::INT[])

You would need to pass a string representation of the array: {1,2}

How does data binding work in AngularJS?

I wondered this myself for a while. Without setters how does AngularJS notice changes to the $scope object? Does it poll them?

What it actually does is this: Any "normal" place you modify the model was already called from the guts of AngularJS, so it automatically calls $apply for you after your code runs. Say your controller has a method that's hooked up to ng-click on some element. Because AngularJS wires the calling of that method together for you, it has a chance to do an $apply in the appropriate place. Likewise, for expressions that appear right in the views, those are executed by AngularJS so it does the $apply.

When the documentation talks about having to call $apply manually for code outside of AngularJS, it's talking about code which, when run, doesn't stem from AngularJS itself in the call stack.

How to use requirements.txt to install all dependencies in a python project

Python 3:

pip3 install -r requirements.txt

Python 2:

pip install -r requirements.txt

To get all the dependencies for the virtual environment or for the whole system:

pip freeze

To push all the dependencies to the requirements.txt (Linux):

pip freeze > requirements.txt

Click event doesn't work on dynamically generated elements

The Jquery .on works ok but I had some problems with the rendering implementing some of the solutions above. My problem using the .on is that somehow it was rendering the events differently than the .hover method.

Just fyi for anyone else that may also have the problem. I solved my problem by re-registering the hover event for the dynamically added item:

re-register the hover event because hover doesn't work for dynamically created items. so every time i create the new/dynamic item i add the hover code again. works perfectly

$('#someID div:last').hover(
    function() {
       //...
    },
    function() {
       //...
    }
);

Update with two tables?

The answers didn't work for me with postgresql 9.1+

This is what I had to do (you can check more in the manual here)

UPDATE schema.TableA as A
SET "columnA" = "B"."columnB"
FROM schema.TableB as B
WHERE A.id = B.id;

You can omit the schema, if you are using the default schema for both tables.

Escaping ampersand in URL

Try using http://www.example.org?candy_name=M%26M.

See also this reference and some more information on Wikipedia.

What is middleware exactly?

Some examples of middleware: CORBA, Remote Method Invocation (RMI),...

The examples mentioned above are all pieces of software allowing you to take care of communication between different processes (either running on the same machine or distributed over e.g. the internet).

Make Bootstrap 3 Tabs Responsive

Pure CSS only for nav tabs, very simple for small screens:

@media (max-width: 767px) {
     .nav-tabs {
         min-width: 100%;
         display: inline-grid;
     }
}

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How to add action listener that listens to multiple buttons

There are good answers here but let me address the more global point of adding action listener that listens to multiple buttons.

There are two popular approaches.

Using a Common Action Listener

You can get the source of the action in your actionPerformed(ActionEvent e) implementation:

JButton button1, button2; //your button

@Override
public void actionPerformed(ActionEvent e) {

    JButton actionSource = (JButton) e.getSource();

    if(actionSource.equals(button1)){
        // YOU BUTTON 1 CODE HERE
    } else if (actionSource.equals(button2)) {
        // YOU BUTTON 2 CODE HERE
    }
}

Using ActionCommand

With this approach you setting the actionCommand field of your button which later will allow you to use switch:

button1.setActionCommand("actionName1");
button2.setActionCommand("actionName2");

And later:

@Override
public void actionPerformed(ActionEvent e) {
    String actionCommand = ((JButton) e.getSource()).getActionCommand();

    switch (actionCommand) {
        case "actionName1": 
            // YOU BUTTON 1 CODE HERE
        break;
        case "actionName2": 
            // YOU BUTTON 2 CODE HERE
        break;
    }
}

Check out to learn more about JFrame Buttons, Listeners and Fields.

How to refresh a page with jQuery by passing a parameter to URL

Concision counts: I prefer window.location = "?single"; or window.location += "?single";

how to convert a string to an array in php

Take a look at the explode function.

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

How to get cumulative sum

Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

Pretty graphs and charts in Python

PLplot is a cross-platform software package for creating scientific plots. They aren't very pretty (eye catching), but they look good enough. Have a look at some examples (both source code and pictures).

The PLplot core library can be used to create standard x-y plots, semi-log plots, log-log plots, contour plots, 3D surface plots, mesh plots, bar charts and pie charts. It runs on Windows (2000, XP and Vista), Linux, Mac OS X, and other Unices.

How to set the current working directory?

import os
print os.getcwd()  # Prints the current working directory

To set the working directory:

os.chdir('c:\\Users\\uname\\desktop\\python')  # Provide the new path here

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

Can someone explain the dollar sign in Javascript?

A '$' in a variable means nothing special to the interpreter, much like an underscore.

From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.

The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Generating an MD5 checksum of a file

change the file_path to your file

import hashlib
def getMd5(file_path):
    m = hashlib.md5()
    with open(file_path,'rb') as f:
        line = f.read()
        m.update(line)
    md5code = m.hexdigest()
    return md5code

How to check all checkboxes using jQuery?

html :

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

    try:
        res = math.exp(420000)
    except OverflowError:
        res = float('inf')
    

Notes

Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

How to convert float number to Binary?

Keep multiplying the number after decimal by 2 till it becomes 1.0:

0.25*2 = 0.50
0.50*2 = 1.00

and the result is in reverse order being .01

Invalid date in safari

To have a solution working on most browsers, you should create your date-object with this format

(year, month, date, hours, minutes, seconds, ms)

e.g.:

dateObj = new Date(2014, 6, 25); //UTC time / Months are mapped from 0 to 11
alert(dateObj.getTime()); //gives back timestamp in ms

works fine with IE, FF, Chrome and Safari. Even older versions.

IE Dev Center: Date Object (JavaScript)

Mozilla Dev Network: Date

Setting timezone to UTC (0) in PHP

UTC is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set accepts one of the following values:

    $timezones=array(
    "America/Adak",
    "America/Argentina/Buenos_Aires",
    "America/Argentina/La_Rioja",
    "America/Argentina/San_Luis",
    "America/Atikokan",
    "America/Belem",
    "America/Boise",
    "America/Caracas",
    "America/Chihuahua",
    "America/Cuiaba",
    "America/Denver",
    "America/El_Salvador",
    "America/Godthab",
    "America/Guatemala",
    "America/Hermosillo",
    "America/Indiana/Tell_City",
    "America/Inuvik",
    "America/Kentucky/Louisville",
    "America/Lima",
    "America/Managua",
    "America/Mazatlan",
    "America/Mexico_City",
    "America/Montreal",
    "America/Nome",
    "America/Ojinaga",
    "America/Port-au-Prince",
    "America/Rainy_River",
    "America/Rio_Branco",
    "America/Santo_Domingo",
    "America/St_Barthelemy",
    "America/St_Vincent",
    "America/Tijuana",
    "America/Whitehorse",
    "America/Anchorage",
    "America/Argentina/Catamarca",
    "America/Argentina/Mendoza",
    "America/Argentina/Tucuman",
    "America/Atka",
    "America/Belize",
    "America/Buenos_Aires",
    "America/Catamarca",
    "America/Coral_Harbour",
    "America/Curacao",
    "America/Detroit",
    "America/Ensenada",
    "America/Goose_Bay",
    "America/Guayaquil",
    "America/Indiana/Indianapolis",
    "America/Indiana/Vevay",
    "America/Iqaluit",
    "America/Kentucky/Monticello",
    "America/Los_Angeles",
    "America/Manaus",
    "America/Mendoza",
    "America/Miquelon",
    "America/Montserrat",
    "America/Noronha",
    "America/Panama",
    "America/Port_of_Spain",
    "America/Rankin_Inlet",
    "America/Rosario",
    "America/Sao_Paulo",
    "America/St_Johns",
    "America/Swift_Current",
    "America/Toronto",
    "America/Winnipeg",
    "America/Anguilla",
    "America/Argentina/ComodRivadavia",
    "America/Argentina/Rio_Gallegos",
    "America/Argentina/Ushuaia",
    "America/Bahia",
    "America/Blanc-Sablon",
    "America/Cambridge_Bay",
    "America/Cayenne",
    "America/Cordoba",
    "America/Danmarkshavn",
    "America/Dominica",
    "America/Fort_Wayne",
    "America/Grand_Turk",
    "America/Guyana",
    "America/Indiana/Knox",
    "America/Indiana/Vincennes",
    "America/Jamaica",
    "America/Knox_IN",
    "America/Louisville",
    "America/Marigot",
    "America/Menominee",
    "America/Moncton",
    "America/Nassau",
    "America/North_Dakota/Beulah",
    "America/Pangnirtung",
    "America/Porto_Acre",
    "America/Recife",
    "America/Santa_Isabel",
    "America/Scoresbysund",
    "America/St_Kitts",
    "America/Tegucigalpa",
    "America/Tortola",
    "America/Yakutat",
    "America/Antigua",
    "America/Argentina/Cordoba",
    "America/Argentina/Salta",
    "America/Aruba",
    "America/Bahia_Banderas",
    "America/Boa_Vista",
    "America/Campo_Grande",
    "America/Cayman",
    "America/Costa_Rica",
    "America/Dawson",
    "America/Edmonton",
    "America/Fortaleza",
    "America/Grenada",
    "America/Halifax",
    "America/Indiana/Marengo",
    "America/Indiana/Winamac",
    "America/Jujuy",
    "America/Kralendijk",
    "America/Lower_Princes",
    "America/Martinique",
    "America/Merida",
    "America/Monterrey",
    "America/New_York",
    "America/North_Dakota/Center",
    "America/Paramaribo",
    "America/Porto_Velho",
    "America/Regina",
    "America/Santarem",
    "America/Shiprock",
    "America/St_Lucia",
    "America/Thule",
    "America/Vancouver",
    "America/Yellowknife",
    "America/Araguaina",
    "America/Argentina/Jujuy",
    "America/Argentina/San_Juan",
    "America/Asuncion",
    "America/Barbados",
    "America/Bogota",
    "America/Cancun",
    "America/Chicago",
    "America/Creston",
    "America/Dawson_Creek",
    "America/Eirunepe",
    "America/Glace_Bay",
    "America/Guadeloupe",
    "America/Havana",
    "America/Indiana/Petersburg",
    "America/Indianapolis",
    "America/Juneau",
    "America/La_Paz",
    "America/Maceio",
    "America/Matamoros",
    "America/Metlakatla",
    "America/Montevideo",
    "America/Nipigon",
    "America/North_Dakota/New_Salem",
    "America/Phoenix",
    "America/Puerto_Rico",
    "America/Resolute",
    "America/Santiago",
    "America/Sitka",
    "America/St_Thomas",
    "America/Thunder_Bay",
    "America/Virgin",
    "Indian/Antananarivo",
    "Indian/Kerguelen",
    "Indian/Reunion",
    "Australia/ACT",
    "Australia/Currie",
    "Australia/Lindeman",
    "Australia/Perth",
    "Australia/Victoria",
    "Europe/Amsterdam",
    "Europe/Berlin",
    "Europe/Chisinau",
    "Europe/Helsinki",
    "Europe/Kiev",
    "Europe/Madrid",
    "Europe/Moscow",
    "Europe/Prague",
    "Europe/Sarajevo",
    "Europe/Tallinn",
    "Europe/Vatican",
    "Europe/Zagreb",
    "Pacific/Apia",
    "Pacific/Efate",
    "Pacific/Galapagos",
    "Pacific/Johnston",
    "Pacific/Marquesas",
    "Pacific/Noumea",
    "Pacific/Ponape",
    "Pacific/Tahiti",
    "Pacific/Wallis",
    "Indian/Chagos",
    "Indian/Mahe",
    "Australia/Adelaide",
    "Australia/Darwin",
    "Australia/Lord_Howe",
    "Australia/Queensland",
    "Australia/West",
    "Europe/Andorra",
    "Europe/Bratislava",
    "Europe/Copenhagen",
    "Europe/Isle_of_Man",
    "Europe/Lisbon",
    "Europe/Malta",
    "Europe/Nicosia",
    "Europe/Riga",
    "Europe/Simferopol",
    "Europe/Tirane",
    "Europe/Vienna",
    "Europe/Zaporozhye",
    "Pacific/Auckland",
    "Pacific/Enderbury",
    "Pacific/Gambier",
    "Pacific/Kiritimati",
    "Pacific/Midway",
    "Pacific/Pago_Pago",
    "Pacific/Port_Moresby",
    "Pacific/Tarawa",
    "Pacific/Yap",
    "Africa/Abidjan",
    "Africa/Asmera",
    "Africa/Blantyre",
    "Africa/Ceuta",
    "Africa/Douala",
    "Africa/Johannesburg",
    "Africa/Kinshasa",
    "Africa/Lubumbashi",
    "Africa/Mbabane",
    "Africa/Niamey",
    "Africa/Timbuktu",
    "Africa/Accra",
    "Africa/Bamako",
    "Africa/Brazzaville",
    "Africa/Conakry",
    "Africa/El_Aaiun",
    "Africa/Juba",
    "Africa/Lagos",
    "Africa/Lusaka",
    "Africa/Mogadishu",
    "Africa/Nouakchott",
    "Africa/Tripoli",
    "Africa/Addis_Ababa",
    "Africa/Bangui",
    "Africa/Bujumbura",
    "Africa/Dakar",
    "Africa/Freetown",
    "Africa/Kampala",
    "Africa/Libreville",
    "Africa/Malabo",
    "Africa/Monrovia",
    "Africa/Ouagadougou",
    "Africa/Tunis",
    "Africa/Algiers",
    "Africa/Banjul",
    "Africa/Cairo",
    "Africa/Dar_es_Salaam",
    "Africa/Gaborone",
    "Africa/Khartoum",
    "Africa/Lome",
    "Africa/Maputo",
    "Africa/Nairobi",
    "Africa/Porto-Novo",
    "Africa/Windhoek",
    "Africa/Asmara",
    "Africa/Bissau",
    "Africa/Casablanca",
    "Africa/Djibouti",
    "Africa/Harare",
    "Africa/Kigali",
    "Africa/Luanda",
    "Africa/Maseru",
    "Africa/Ndjamena",
    "Africa/Sao_Tome",
    "Atlantic/Azores",
    "Atlantic/Faroe",
    "Atlantic/St_Helena",
    "Atlantic/Bermuda",
    "Atlantic/Jan_Mayen",
    "Atlantic/Stanley",
    "Atlantic/Canary",
    "Atlantic/Madeira",
    "Atlantic/Cape_Verde",
    "Atlantic/Reykjavik",
    "Atlantic/Faeroe",
    "Atlantic/South_Georgia",
    "Asia/Aden",
    "Asia/Aqtobe",
    "Asia/Baku",
    "Asia/Calcutta",
    "Asia/Dacca",
    "Asia/Dushanbe",
    "Asia/Hong_Kong",
    "Asia/Jayapura",
    "Asia/Kashgar",
    "Asia/Kuala_Lumpur",
    "Asia/Magadan",
    "Asia/Novokuznetsk",
    "Asia/Pontianak",
    "Asia/Riyadh",
    "Asia/Shanghai",
    "Asia/Tehran",
    "Asia/Ujung_Pandang",
    "Asia/Vladivostok",
    "Asia/Almaty",
    "Asia/Ashgabat",
    "Asia/Bangkok",
    "Asia/Choibalsan",
    "Asia/Damascus",
    "Asia/Gaza",
    "Asia/Hovd",
    "Asia/Jerusalem",
    "Asia/Kathmandu",
    "Asia/Kuching",
    "Asia/Makassar",
    "Asia/Novosibirsk",
    "Asia/Pyongyang",
    "Asia/Saigon",
    "Asia/Singapore",
    "Asia/Tel_Aviv",
    "Asia/Ulaanbaatar",
    "Asia/Yakutsk",
    "Asia/Amman",
    "Asia/Ashkhabad",
    "Asia/Beirut",
    "Asia/Chongqing",
    "Asia/Dhaka",
    "Asia/Harbin",
    "Asia/Irkutsk",
    "Asia/Kabul",
    "Asia/Katmandu",
    "Asia/Kuwait",
    "Asia/Manila",
    "Asia/Omsk",
    "Asia/Qatar",
    "Asia/Sakhalin",
    "Asia/Taipei",
    "Asia/Thimbu",
    "Asia/Ulan_Bator",
    "Asia/Yekaterinburg",
    "Asia/Anadyr",
    "Asia/Baghdad",
    "Asia/Bishkek",
    "Asia/Chungking",
    "Asia/Dili",
    "Asia/Hebron",
    "Asia/Istanbul",
    "Asia/Kamchatka",
    "Asia/Kolkata",
    "Asia/Macao",
    "Asia/Muscat",
    "Asia/Oral",
    "Asia/Qyzylorda",
    "Asia/Samarkand",
    "Asia/Tashkent",
    "Asia/Thimphu",
    "Asia/Urumqi",
    "Asia/Yerevan",
    "Asia/Aqtau",
    "Asia/Bahrain",
    "Asia/Brunei",
    "Asia/Colombo",
    "Asia/Dubai",
    "Asia/Ho_Chi_Minh",
    "Asia/Jakarta",
    "Asia/Karachi",
    "Asia/Krasnoyarsk",
    "Asia/Macau",
    "Asia/Nicosia",
    "Asia/Phnom_Penh",
    "Asia/Rangoon",
    "Asia/Seoul",
    "Asia/Tbilisi",
    "Asia/Tokyo",
    "Asia/Vientiane",
    "Australia/Canberra",
    "Australia/LHI",
    "Australia/NSW",
    "Australia/Tasmania",
    "Australia/Broken_Hill",
    "Australia/Hobart",
    "Australia/North",
    "Australia/Sydney",
    "Pacific/Chuuk",
    "Pacific/Fiji",
    "Pacific/Guam",
    "Pacific/Kwajalein",
    "Pacific/Niue",
    "Pacific/Pitcairn",
    "Pacific/Saipan",
    "Pacific/Truk",
    "Pacific/Chatham",
    "Pacific/Fakaofo",
    "Pacific/Guadalcanal",
    "Pacific/Kosrae",
    "Pacific/Nauru",
    "Pacific/Palau",
    "Pacific/Rarotonga",
    "Pacific/Tongatapu",
    "Pacific/Easter",
    "Pacific/Funafuti",
    "Pacific/Honolulu",
    "Pacific/Majuro",
    "Pacific/Norfolk",
    "Pacific/Pohnpei",
    "Pacific/Samoa",
    "Pacific/Wake",
    "Antarctica/Casey",
    "Antarctica/McMurdo",
    "Antarctica/Vostok",
    "Antarctica/Davis",
    "Antarctica/Palmer",
    "Antarctica/DumontDUrville",
    "Antarctica/Rothera",
    "Antarctica/Macquarie",
    "Antarctica/South_Pole",
    "Antarctica/Mawson",
    "Antarctica/Syowa",
    "Arctic/Longyearbyen",
    "Europe/Athens",
    "Europe/Brussels",
    "Europe/Dublin",
    "Europe/Istanbul",
    "Europe/Ljubljana",
    "Europe/Mariehamn",
    "Europe/Oslo",
    "Europe/Rome",
    "Europe/Skopje",
    "Europe/Tiraspol",
    "Europe/Vilnius",
    "Europe/Zurich",
    "Europe/Belfast",
    "Europe/Bucharest",
    "Europe/Gibraltar",
    "Europe/Jersey",
    "Europe/London",
    "Europe/Minsk",
    "Europe/Paris",
    "Europe/Samara",
    "Europe/Sofia",
    "Europe/Uzhgorod",
    "Europe/Volgograd",
    "Europe/Belgrade",
    "Europe/Budapest",
    "Europe/Guernsey",
    "Europe/Kaliningrad",
    "Europe/Luxembourg",
    "Europe/Monaco",
    "Europe/Podgorica",
    "Europe/San_Marino",
    "Europe/Stockholm",
    "Europe/Vaduz",
    "Europe/Warsaw",
    "Indian/Cocos",
    "Indian/Mauritius",
    "Indian/Christmas",
    "Indian/Maldives",
    "Indian/Comoro",
    "Indian/Mayotte",
    "Australia/Brisbane",
    "Australia/Eucla",
    "Australia/Melbourne",
    "Australia/South",
    "Australia/Yancowinna",
    );

Timezones in PHP at http://www.php.net/manual/en/timezones.php

Printing HashMap In Java

If the map holds a collection as value, the other answers require additional effort to convert them as strings, such as Arrays.deepToString(value.toArray()) (if its a map of list values), etc.

I faced these issues quite often and came across the generic function to print all objects using ObjectMappers. This is quite handy at all the places, especially during experimenting things, and I would recommend you to choose this way.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public static String convertObjectAsString(Object object) {
    String s = "";
    ObjectMapper om = new ObjectMapper();
    try {
        om.enable(SerializationFeature.INDENT_OUTPUT);
        s = om.writeValueAsString(object);
    } catch (Exception e) {
        log.error("error converting object to string - " + e);
    }
    return s;
}

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

I'm facing the same issue.

The issue because of X-Code.

Solution: 1. Open X-code and accept user agreement (T&C). or 2. Restart your MAC, It will resolve automatically.

Suppress/ print without b' prefix for bytes in Python 3

If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

The most obvious workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

Installing Python 2.7 on Windows 8

i'm using python 2.7 in win 8 too but no problem with that. maybe you need to reastart your computer like wclear said, or you can run python command line program that included in python installation folder, i think below IDLE program. hope it help.

Error: Cannot access file bin/Debug/... because it is being used by another process

Recently I've been in a trouble with Visual Studio 2012 with same error description: "The process cannot access the file because it is being used by another process..."

To fix this first of all you need to understand the application which still use it. I've shutdown all processes like "MSBuild" and "MSBuild host". But this is not enough. If you have installed "Code Contracts" and turned on then it sometimes takes your DLLs for checking and hanging up on this operation.

So, you need to stop all processes of "CCCheck.exe" and that's all.

Finally, to understand that process is using your DLL you always may try to just Delete "obj" folder in your File Manager and this operation will fail, you may see the "Message Window" with description of the hanging operation. Also, as a variant, you can try to use "Sys Internals Suite" application.

HTML/Javascript Button Click Counter

Use var instead of int for your clicks variable generation and onClick instead of click as your function name:

_x000D_
_x000D_
var clicks = 0;

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
_x000D_
_x000D_

In JavaScript variables are declared with the var keyword. There are no tags like int, bool, string... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for function names so you have to use something else.

How to filter keys of an object with lodash?

Native ES2019 one-liner

_x000D_
_x000D_
const data = {
  aaa: 111,
  abb: 222,
  bbb: 333
};

const filteredByKey = Object.fromEntries(Object.entries(data).filter(([key, value]) => key.startsWith("a")))

console.log(filteredByKey);
_x000D_
_x000D_
_x000D_

How to find the lowest common ancestor of two nodes in any binary tree?

The lowest common ancestor between two nodes node1 and node2 is the lowest node in a tree that has both nodes as descendants.

The binary tree is traversed from the root node, until both nodes are found. Every time a node is visited, it is added to a dictionary (called parent). Once both nodes are found in the binary tree, the ancestors of node1 are obtained using the dictionary and added to a set (called ancestors). This step is followed in the same manner for node2. If the ancestor of node2 is present in the ancestors set for node1, it is the first common ancestor between them.

Below is the iterative python solution implemented using stack and dictionary with the following points:

  • A node can be a descendant of itself
  • All nodes in the binary tree are unique
  • node1 and node2 will exist in the binary tree
class Node:
    def __init__(self, data=None, left=None, right=None):
        self.data  = data
        self.left  = left
        self.right = right

def lowest_common_ancestor(root, node1, node2):
    parent = {root: None}
    stack = [root]
    
    while node1 not in parent or node2 not in parent:
        node = stack[-1]
        stack.pop()
        if node.left:
            parent[node.left] = node
            stack.append(node.left)
        if node.right:
            parent[node.right] = node
            stack.append(node.right)
    
    ancestors = set()
    while node1:
        ancestors.add(node1)
        node1 = parent[node1]
    while node2 not in ancestors:
        node2 = parent[node2]
    
    return node2.data

def main():
    '''
    Construct the below binary tree:

            30
           /  \
          /    \
         /      \
        11      29
       /  \    /  \
      8   12  25  14

    '''
    root = Node(30)
    root.left  = Node(11)
    root.right = Node(29)
    root.left.left  = Node(8)
    root.left.right = Node(12)
    root.right.left  = Node(25)
    root.right.right = Node(14)

    print(lowest_common_ancestor(root, root.left.left, root.left.right))       # 11
    print(lowest_common_ancestor(root, root.left.left, root.left))             # 11
    print(lowest_common_ancestor(root, root.left.left, root.right.right))      # 30


if __name__ == '__main__':
    main()

The complexity of this approach is: O(n)

java.util.Date to XMLGregorianCalendar

Just thought I'd add my solution below, since the answers above did not meet my exact needs. My Xml schema required seperate Date and Time elements, not a singe DateTime field. The standard XMLGregorianCalendar constructor used above will generate a DateTime field

Note there a couple of gothca's, such as having to add one to the month (since java counts months from 0).

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(yourDate);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), 0);
XMLGregorianCalendar xmlTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), 0);

Linq style "For Each"

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

Call a Javascript function every 5 seconds continuously

Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();

How to get the list of all database users

Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.

Run Sql Profiler. Attach it to your database of course.

Then right click in the GUI (in SSMS) and click "Refresh".
And then go see what Profiler "catches".

I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".

Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.

But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.

SELECT
u.name AS [Name],
'Server[@Name=' + quotename(CAST(
        serverproperty(N'Servername')
       AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC

Android Studio cannot resolve R in imported project?

Here's what worked for me in IntelliJ (Not Studio), in addition to the replies presented above:

You need to attach an Android facet to an existing Android module. To do this, select the module from the module list in 'Module Settings', hit the '+' button on top and select 'Android'. See https://www.jetbrains.com/idea/webhelp/enabling-android-support.html.

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I spend a hour finding out what was wrong.. But Clean Project did the trick.

Build -> Clean All

The accepted solution is probably also working.. but this was enough for me.

PHP date() with timezone?

Try this. You can pass either unix timestamp, or datetime string

public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s') 
    {
        $datetime = is_numeric($timestamp) ?
                    DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
                    new DateTime($timestamp, new DateTimeZone($fromTimezone));

        $datetime->setTimezone(new DateTimeZone($toTimezone));

        return $datetime->format($format);
    }

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

dotnet ef not found in .NET Core 3

Run PowerShell or command prompt as Administrator and run below command.

dotnet tool install --global dotnet-ef --version 3.1.3

Fast check for NaN in NumPy

Related to this is the question of how to find the first occurrence of NaN. This is the fastest way to handle that that I know of:

index = next((i for (i,n) in enumerate(iterable) if n!=n), None)

Which SchemaType in Mongoose is Best for Timestamp?

I would like to use this field in order to return all the records that have been updated in the last 5 minutes.

This means you need to update the date to "now" every time you save the object. Maybe you'll find this useful: Moongoose create-modified plugin

What does functools.wraps do?

As of python 3.5+:

@functools.wraps(f)
def g():
    pass

Is an alias for g = functools.update_wrapper(g, f). It does exactly three things:

  • it copies the __module__, __name__, __qualname__, __doc__, and __annotations__ attributes of f on g. This default list is in WRAPPER_ASSIGNMENTS, you can see it in the functools source.
  • it updates the __dict__ of g with all elements from f.__dict__. (see WRAPPER_UPDATES in the source)
  • it sets a new __wrapped__=f attribute on g

The consequence is that g appears as having the same name, docstring, module name, and signature than f. The only problem is that concerning the signature this is not actually true: it is just that inspect.signature follows wrapper chains by default. You can check it by using inspect.signature(g, follow_wrapped=False) as explained in the doc. This has annoying consequences:

  • the wrapper code will execute even when the provided arguments are invalid.
  • the wrapper code can not easily access an argument using its name, from the received *args, **kwargs. Indeed one would have to handle all cases (positional, keyword, default) and therefore to use something like Signature.bind().

Now there is a bit of confusion between functools.wraps and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: decopatch to write decorators easily, and makefun to provide a signature-preserving replacement for @wraps. Note that makefun relies on the same proven trick than the famous decorator library.

Cloning specific branch

you can use this command for particular branch clone :

git clone <url of repo> -b <branch name to be cloned>

Eg: git clone https://www.github.com/Repo/FirstRepo -b master

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

Endless loop in C/C++

They are the same. But I suggest "while(ture)" which has best representation.

`React/RCTBridgeModule.h` file not found

Make sure you disable Parallelise Build and add React target above your target

enter image description here

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

Set height of <div> = to height of another <div> through .css

You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:

Please check the example: http://jsfiddle.net/xLA4q/

HTML:

<div class="nav-content-wrapper">
 <div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
 <div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>

CSS:

.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

How do I merge my local uncommitted changes into another Git branch?

Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.

git checkout branch2

This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m option to checkout.

git checkout -m branch2

If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)

git reset

How to test multiple variables against a value?

Your problem is more easily addressed with a dictionary structure like:

x = 0
y = 1
z = 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]

How do I make a Docker container start automatically on system boot?

I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:

? docker.service - Docker Application Container Engine

   Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

     Active: inactive (dead)    TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

On a system where "docker ps" had been run with no other Docker commands, I got the following:

? docker.service - Docker Application Container Engine
    Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

    Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago

TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

   Main PID: 3135 (dockerd)
      Tasks: 13

    Memory: 116.9M
     CGroup: /system.slice/docker.service
             +-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
 ... [various messages not shown ]

The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:

[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run.  This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service

[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps

[Install]

WantedBy=multi-user.target

So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

How to count total lines changed by a specific author in a Git repository?

In addition to Charles Bailey's answer, you might want to add the -C parameter to the commands. Otherwise file renames count as lots of additions and removals (as many as the file has lines), even if the file content was not modified.

To illustrate, here is a commit with lots of files being moved around from one of my projects, when using the git log --oneline --shortstat command:

9052459 Reorganized project structure
 43 files changed, 1049 insertions(+), 1000 deletions(-)

And here the same commit using the git log --oneline --shortstat -C command which detects file copies and renames:

9052459 Reorganized project structure
 27 files changed, 134 insertions(+), 85 deletions(-)

In my opinion the latter gives a more realistic view of how much impact a person has had on the project, because renaming a file is a much smaller operation than writing the file from scratch.

Creating dummy variables in pandas for python

Handling categorical features scikit-learn expects all features to be numeric. So how do we include a categorical feature in our model?

Ordered categories: transform them to sensible numeric values (example: small=1, medium=2, large=3) Unordered categories: use dummy encoding (0/1) What are the categorical features in our dataset?

Ordered categories: weather (already encoded with sensible numeric values) Unordered categories: season (needs dummy encoding), holiday (already dummy encoded), workingday (already dummy encoded) For season, we can't simply leave the encoding as 1 = spring, 2 = summer, 3 = fall, and 4 = winter, because that would imply an ordered relationship. Instead, we create multiple dummy variables:

# An utility function to create dummy variable
`def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df`

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Get local IP address in Node.js

Here's my variant that allows getting both IPv4 and IPv6 addresses in a portable manner:

/**
 * Collects information about the local IPv4/IPv6 addresses of
 * every network interface on the local computer.
 * Returns an object with the network interface name as the first-level key and
 * "IPv4" or "IPv6" as the second-level key.
 * For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
 * (as string) of eth0
 */
getLocalIPs = function () {
    var addrInfo, ifaceDetails, _len;
    var localIPInfo = {};
    //Get the network interfaces
    var networkInterfaces = require('os').networkInterfaces();
    //Iterate over the network interfaces
    for (var ifaceName in networkInterfaces) {
        ifaceDetails = networkInterfaces[ifaceName];
        //Iterate over all interface details
        for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
            addrInfo = ifaceDetails[_i];
            if (addrInfo.family === 'IPv4') {
                //Extract the IPv4 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv4 = addrInfo.address;
            } else if (addrInfo.family === 'IPv6') {
                //Extract the IPv6 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv6 = addrInfo.address;
            }
        }
    }
    return localIPInfo;
};

Here's a CoffeeScript version of the same function:

getLocalIPs = () =>
    ###
    Collects information about the local IPv4/IPv6 addresses of
      every network interface on the local computer.
    Returns an object with the network interface name as the first-level key and
      "IPv4" or "IPv6" as the second-level key.
    For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
      (as string) of eth0
    ###
    networkInterfaces = require('os').networkInterfaces();
    localIPInfo = {}
    for ifaceName, ifaceDetails of networkInterfaces
        for addrInfo in ifaceDetails
            if addrInfo.family=='IPv4'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv4 = addrInfo.address
            else if addrInfo.family=='IPv6'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv6 = addrInfo.address
    return localIPInfo

Example output for console.log(getLocalIPs())

{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
  wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
  tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }

Render HTML to an image

I read the answer by Sjeiti which I found very interesting, where you with just a few plain JavaScript lines can render HTML in an image.

We of course have to be aware of the limitations of this method (please read about some of them in his answer).

Here I have taken his code a couple of steps further.

An SVG-image has in principle infinite resolution, since it is vector graphics. But you might have noticed that the image that Sjeiti's code generated did not have a high resolution. This can be fixed by scaling the SVG-image before transferring it to the canvas-element, which I have done in the last one of the two (runnable) example codes i give below. The other thing I have implemented in that code is the last step, namely saving it as a PNG-file. Just to complete the whole thing.

So, I give two runnable snippets of code:

The first one demonstrates the infinite resolution of an SVG. Run it and zoom in with your browser to see that the resolution does not diminish as you zoom in.

In the snippet that you can run I have used backticks to specify a so called template string with line breaks so that you can more clearly see the HTML that is rendered. But otherwise, if that HTML is within one line, then the code will be very short, like this.

const body = document.getElementsByTagName('BODY')[0];
const img = document.createElement('img')
img.src = 'data:image/svg+xml,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;"><style>em {color:red;}.test {color:blue;}</style>What you see here is only an image, nothing else.<br /><br /><em>I</em> really like <span class="test">cheese.</span><br /><br />Zoom in to check the resolution!</div></foreignObject></svg>`);        
body.appendChild(img);

Here it comes as a runnable snippet.

_x000D_
_x000D_
const body = document.getElementsByTagName('BODY')[0];
const img = document.createElement('img')
img.src = 'data:image/svg+xml,' + encodeURIComponent(`
  <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <foreignObject width="100%" height="100%">
      <div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;">
        <style>
          em {
            color:red;
          }
          .test {
            color:blue;
          }
        </style>
        What you see here is only an image, nothing
        else.<br />
        <br />
        <em>I</em> really like <span class="test">cheese.</span><br />
        <br />
        Zoom in to check the resolution!
      </div>
    </foreignObject>
  </svg>
`);
body.appendChild(img);
_x000D_
_x000D_
_x000D_

Zoom in and check the infinite resolution of the SVG.

The next runnable, below, is the one that implements the two extra steps which I mentioned above, namely improving resolution by first scaling the SVG, and then the saving as a PNG-image.

_x000D_
_x000D_
window.addEventListener("load", doit, false)
var canvas;
var ctx;
var tempImg;
function doit() {
    const body = document.getElementsByTagName('BODY')[0];
    const scale = document.getElementById('scale').value;
    let trans = document.getElementById('trans').checked;
  if (trans) {
    trans = '';
  } else {
    trans = 'background-color:white;';
  }
    let source = `
        <div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;${trans}">
            <style>
                em {
                    color:red;
                }
                .test {
                    color:blue;
                }
            </style>
            What you see here is only an image, nothing
            else.<br />
            <br />
            <em>I</em> really like <span class="test">cheese.</span><br />
            <br />
            <div style="text-align:center;">
                Scaling:
                <br />
                ${scale} times!
            </div>
        </div>`
    document.getElementById('source').innerHTML = source;
    canvas = document.createElement('canvas');
    ctx = canvas.getContext('2d');
    canvas.width = 200*scale;
    canvas.height = 200*scale;
    tempImg = document.createElement('img');
    tempImg.src = 'data:image/svg+xml,' + encodeURIComponent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="${200*scale}" height="${200*scale}">
            <foreignObject 
                style="
                    width:200px;
                    height:200px;
                    transform:scale(${scale});
                "
            >` + source + `
            </foreignObject>
        </svg>
    `);
}
function saveAsPng(){
    ctx.drawImage(tempImg, 0, 0);
    var a  = document.createElement('a');
    a.href = canvas.toDataURL('image/png');
    a.download = 'image.png';
    a.click();
}
_x000D_
<table border="0">
    <tr>
        <td colspan="2">
            The claims in the HTML-text is only true for the image created when you click the button.
        </td>
    </tr>
    <tr>
        <td width="250">
            <div id="source" style="width:200px;height:200px;">
            </div>
        </td>
        <td valign="top">
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;In this example the PNG-image will be squarish even if the HTML here on the left is not exactly squarish. That can be fixed.<br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To increase the resolution of the image you can change the scaling with this slider.
                <div style="text-align:right;margin:5px 0px;">
                    <label style="background-color:#FDD;border:1px solid #F77;padding:0px 10px;"><input id="trans" type="checkbox" onchange="doit();" />&nbsp;&nbsp;Make it transparent</label>
                </div>
                <span style="white-space:nowrap;">1<input id="scale" type="range" min="1" max="10" step="0.25" value="2" oninput="doit();" style="width:150px;vertical-align:-8px;" />10&nbsp;&nbsp;<button onclick="saveAsPng();">Save as PNG-image</button></span>
            </div>
            
        </td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

Try with different scalings. If you for example set scaling to 10, then you get a very good resolution in the generated PNG-image. And I added a little extra feature: a checkbox so that you can make the PNG-image transparent if you like.

Notice:

The Save-button does not work in Chrome and Edge when this script is run here at Stack Overflow. The reason is this https://www.chromestatus.com/feature/5706745674465280 .

Therefore I have also put this snippet on https://jsfiddle.net/7gozdq5v/ where it works for those browsers.

How to trim leading and trailing white spaces of a string?

A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.

(example: the string value of {"first_name":" I have whitespace "} will convert to "\" I have whitespace \"")

Before you can trim anything, you'll need to remove the extra quotes first:

playground example

// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string

// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
    ns := string(data)
    // Make sure we don't have a blank string of "\"\"".
    if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
        *s = ""
        return nil
    }
    // Remove the added wrapping quotes.
    ns, err := strconv.Unquote(ns)
    if err != nil {
        return err
    }
    // We can now trim the whitespace.
    *s = ScrubString(strings.TrimSpace(ns))

    return nil
}

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

How to generate random positive and negative numbers in Java

Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);

Linear Layout and weight in Android

In the above XML, set the android:layout_weight of the linear layout as 2: android:layout_weight="2"

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

A full list of all the new/popular databases and their uses?

What about CassandraDB, Project Voldemort, TokyoCabinet?

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

How to add two strings as if they were numbers?

I've always just subtracted zero.

num1-0 + num2-0;

Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.

jQuery selector regular expressions

I'm just giving my real time example:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

$("[id^='select2-qownerName_select-result']")

Best radio-button implementation for IOS

Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.

Convert all strings in a list to int

I also want to add Python | Converting all strings in list to integers

Method #1 : Naive Method

# Python3 code to demonstrate 
# converting list of strings to int 
# using naive method 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using naive method to 
# perform conversion 
for i in range(0, len(test_list)): 
    test_list[i] = int(test_list[i]) 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Method #2 : Using list comprehension

# Python3 code to demonstrate 
# converting list of strings to int 
# using list comprehension 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using list comprehension to 
# perform conversion 
test_list = [int(i) for i in test_list] 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Method #3 : Using map()

# Python3 code to demonstrate 
# converting list of strings to int 
# using map() 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using map() to 
# perform conversion 
test_list = list(map(int, test_list)) 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

NodeJs : TypeError: require(...) is not a function

Just wrap in Arrow function where you requiring the files

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

How to convert std::string to lower case?

Adapted from Not So Frequently Asked Questions:

#include <algorithm>
#include <cctype>
#include <string>

std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
    [](unsigned char c){ return std::tolower(c); });

You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.

If you really hate tolower(), here's a specialized ASCII-only alternative that I don't recommend you use:

char asciitolower(char in) {
    if (in <= 'Z' && in >= 'A')
        return in - ('Z' - 'z');
    return in;
}

std::transform(data.begin(), data.end(), data.begin(), asciitolower);

Be aware that tolower() can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Resolve absolute path from relative path and/or file name

Files See all other answers

Directories

With .. being your relative path, and assuming you are currently in D:\Projects\EditorProject:

cd .. & cd & cd EditorProject (the relative path)

returns absolute path e.g.

D:\Projects

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Assuming all data is formatted like your example, use 'cut' to get the first column only.

cat $file | cut -d ' ' -f 1  

or to get the first 10 chars.

cat $file | cut -c 1-10

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Run the command below;

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
pip install psycopg2

Specify multiple attribute selectors in CSS

[class*="test"],[class="second"] {
background: #ffff00;
}

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

Loop through Map in Groovy?

Another option:

def map = ['a':1, 'b':2, 'c':3]
map.each{
  println it.key +" "+ it.value
}

python pandas remove duplicate columns

If I'm not mistaken, the following does what was asked without the memory problems of the transpose solution and with fewer lines than @kalu 's function, keeping the first of any similarly named columns.

Cols = list(df.columns)
for i,item in enumerate(df.columns):
    if item in df.columns[:i]: Cols[i] = "toDROP"
df.columns = Cols
df = df.drop("toDROP",1)

Is there a way to get the source code from an APK file?

There's an app for that and generally takes just a few clicks and you are done. https://github.com/Nuvolect/DeepDive-Android

  1. Select Apps, under "Installed Apps" select your app. If it is not there you can load the APK.
  2. Select "Extract APK"
  3. Select "Unpack APK"
  4. Select "Decompile with Jadx". This can take a few seconds or a few minutes depending on the speed of your device

After that you can browse the source code, download it to another computer with elFinder or search through it using Lucene.

In addition to Jadx it has CFR and Fernflower decompilers.

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How to open remote files in sublime text 3

On macOS, one option is to install FUSE for macOS and use sshfs to mount a remote directory:

mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir

Some caveats apply with mounting network volumes, so YMMV.

Find the files that have been changed in last 24 hours

This command worked for me

find . -mtime -1 -print

How to display Base64 images in HTML?

put base64()

_x000D_
_x000D_
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAIAAABEtEjdAAAACXBIWXMAAA7zAAAO8wEcU5k6AAAAEXRFWHRUaXRsZQBQREYgQ3JlYXRvckFevCgAAAATdEVYdEF1dGhvcgBQREYgVG9vbHMgQUcbz3cwAAAALXpUWHREZXNjcmlwdGlvbgAACJnLKCkpsNLXLy8v1ytISdMtyc/PKdZLzs8FAG6fCPGXryy4AAPW0ElEQVR42uy9Z5djV3Yl+ByAB+9deG8yMzLSMA1tkeWk6pJKKmla06MlafRB3/UX9BP0eTSj1RpperpLKpXKscgii0xDZpLpIyMiM7yPQCCAgLfPzr73AUikYVVR00sqUvcwVxABIICHB2Dfc/fZZx/eNE2OBQsWLFh8uUJgp4AFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMGCgTsLFixYsGDgzoIFCxYsGLizYMGCBQN3FixYsGDBwJ0FCxYsWDBwZ8GCBQsWDNxZsGDBggUDdxYsWLBg4M6CBQsWLBi4s2DBggULBu4sWLBgwYKBOwsWLFiwYODOggULFiwYuLNgwYIFA3cWLFiwYMHAnQULFixYMHBnwYIFCxYM3FmwYMGCBQN3FixYsGDgzoIFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMHi3zokdgpY/FuG/oLrjK4Uw+hc4lv315/LRfjnHsHsuoftcx0P/8Jrzc+4jOMRtBclRoLJvmAsGLizYPE0NAodTOe7LrdvE1/0R93Aavz/O5AXgTXf/tV8Fv6F5za7xnOLhMneXRa/AcGbJvsosvi3C/MzE2fjV68CvxI4+c8NrDynfs7MXnj+qF74pNbrEdlbzoKBOwuG9//KO3Tf9wlt8q9/ev7FsG7dXfocCwELFv9+wWgZFr95gG4+jZj85/rzz5us2D7XQ/DmZyO7yRCfBQN3Fv/Rd4yfAaKfdQ3/6yIm/znR1DQ/J/6an3EMJoNyFgzcWfyHTtnBRQv8Z+Hj8+DIW9y18auy6s5ffj51L99+SJP/9f/g107PGdazYODO4j9IGJ8NwDz/QgB/BtZ/Vd3V/JytG60nNZ7DYcN88YbC9vnwnQULBu4svmxJOo02cJPABc0E+hpmG8itO9DbeKF1TRfKc1YB06R/a3Ql2fxnpu0muaNp0IdrPSJn6hwv0T82n1tY+ObzGwfT1Dh6SO3lxTBNXSCPiOsIR28YTxYkXngW/s2uI2SYz+LfK5hahsW/aaifAXyarlkoL/K8wAtdH9DOUkF/FZ5K5+nyYX2GBfqAPK9a8NuGa6NLjai3wd1aKSwwtzW7l6MWYwTwFgR6hcF3HYxu6KLgemoBo/c1DIMcBw5eFAD3RmdN0XWHyPInFgzcWXyJQtM0viusjxl+6vyz2b1FqYiC+BRqI/nWdICmYMitnFzkhDZMA0sFke/gq6FTWBYI9Bs1DZCq0sAFC3ZxL6fTics4EjsNwDBnpfbNJidJFMrN9qPwLemLQZcOod23pJt4UdhIWFsQ63UJ1hrQtToYZFtC7mKR+IJpbTtYsGDgzuLLzdV05eFt1DO6eByd0iFdaKhKTzJ85Mi6oWpNTVNqtRruCbxuNtV6va40gekEu7VmQVGUZrOJx5IkyWazWc8CQG/SsK7Hrw6HAz9lIYBfRZvNulKWXaJNslYjySZw9vZBd/gc24s6Wk1B1VQAvSiypiUWDNxZ/IfC9A75bj5dNgXxoaumbogSxXTKihiqWqtVqtWq0mgUsgqSY4A+MB0ZuSCaokiwF6htAbTN5hAESeAlkYTk9ds5kpULLXaFPKbwJK+2lg1VVer1RqNBMvGGBz8B+vhVaaqaoSsktIaiOJ1up9tlkxx4XDwdLjudLldAtX7lke/zrWchFD9+7TgW6ISQAdbz0vNuBa1ShCAwzz4WDNxZ/Cah87MfoM/gHICYHe6iU00loVjceYd413FXQ1MqFaB5pVjIAdMB4gBuECn46fc4ZVkGhguiwYuWLZjB6SqBbItCMSnJTdQuFqPS3gdYdwC+k8fXBAvxAcG4gNeCw8NPkmi7WsuATqFfJLQLeUDcQTcB99VGvVrBPqGGBUCjqwHAnaT4suxBuH0ul1uw2w1VF/Dgkv3pHQpniuYzZ4mBOwsG7iy+wOBuPsc14xqwKKIuck2lRqC8ivQc/0jKrDZ8Pq/ssAEtfT6PwyUTFKYENieVwMdzkK80arrWaDarpXKhXC4eHBzoNEh2ziGVBsciI6HeP8yTB1QUJPVerxc/cRm8DdYJi64BFw909vl8yWQyEom47IROwaHq0PHwYG9ku0MGQyN7vXhUAtat9NzaByDr9+qNRqVSK5VK1Uodj6kjTzc5t9uL1cjr9fu8AZvLxVklAZPTRf3Z5e1FJ4cFCwbuLL4Y4N4J4C8gtU4DwFo/KIAxB8oDiP1+bzDkd/v9nN1GZTEGzcrh8quYzUaz3sD9d3ZvVCqlo6PD9FGqXC40mkDVQrFY4AWTgHWDVE3B0ABbkUQDynNVrkHDegpgukh5nHK5jF9xB0A58m/c2mJ1uENcQMJOrtQB5lhgfE7Z5fJ4w+FoNB4PBsOy0+V2u32+AH4K2jDJ90kNlspgNINTDVRac4VCuVQtFEpYPvCwfl/Q7/cju5ciLqEd7FPEgoE7i/+JqPzMG/55705YDqAX5Ilgx7mOGBEQTFkRvXU3qGDafUDIY1WTkxxcVatmq8fpUiFX0RqmW/YhsXX0V/0Br+TzcrxGOBlIF034MjY5Qctm9ra213Z21/cPd/P541qd8DPp7Gy9jnRbtwF3bU7Cm0gOu01G7gs0pul/DWAai8Wi0ShyZ87lQE5dLBZJkq5rQHbsBpBPA7sJiAuCpZ/Bz0qtCsRPF/cB2X5PSLa7eY1XGyrodggzRVMz1JqhVjijbhc1l8wHgq6A39c/RfYHHo8rEvZHo5FQwIdUnxPAFoGQcXCmzCmiWlRyx9VsJl8p1W3KqM/njiSCgbjEeaEKwvmsc4KC1B7HYZgSLzhxslRaHSCEUFuNyeMguCrPNSRk/4R7ElpPYbjJmTbaak77c+9s91vMd/d8WZeZNJOBO4svHbb/OkSARpnnTj8RmBGelAsNodNGBOk3pOOE7DaRkDtcpmroPAqikpszbWpVKx6Xq8Xa7va2XQKG28MhfyTs5X1ODuwzcNxxTPDF1Bvl6nE2nzrMHBwcHudKa2vrtYZWKVNyW4GMUgRSkww6OkAB2hcKRTxuv8PhlMHayG5JtBMuhagedaA2yByXy0XEKrLNKpAiWum5ywk4xj0hg+FoMYBKHE3sJPBkxUbDCSJGlrF0cLqmKyoKAKi4FnM5pVFp1spKs9qs15RGVcf1nHFU2IOuBkJMCHZUtely2qPRMDB+aGAw4Pci1Y8EQzanh6xtJASuqteL5XT6KHtcrDcNtyeQ6OmPxhKSbOPtdFXE2SXgDVTXsVuxO3wWEPOk19akHbcG7Yoi7BM1NZZasG7p9H+5PId/vqGXbSAYuLP4MibubeD4zC+8otEqI9+6lsIK/un0oUzak88T8Tcwx5Kdm3WAk6ma+Ux5Zzt1nC3JdmcgEBgfG7I7kWjqnIg7VMk/rgYdTKNR290/WFx4tLK8dZTO1xqm2hQ0FTR1xO0Mef0xlxwkjUK8zSl7oFcJDtWAz6BcgO9QxWChgVYFEI9dBCAbXAc+wLTCicsASgMcic1GDgyKF/x0OCRcj7xYsgqlBq2k0moraqNkATBlgb4UkkljaTOanIGfioryKRYZRcMrRYMrdg/1ah2bgVpToYuKWq/WiqV8sXBcrRY1BeR72Wbn3E7B55MjUd/gQHJkdDAej9qdJU4A0Hs5062V+KOjRi7brNVMrycYCAX9AbckQ3OpC7JJGrzI5BAvPfuC1W2L12uarQau1vtC8Bo7I4W+KbgcetHb3oXpz/gxMKqfgTuLLwu4Gy/+zj8B8KdCb19jWjDCQzwOeCD31SkrDR7burlZM4vFci2rZrPpfCHj9shDw8megSiYA86sgX8w1apuKEhzkeFu7+0uLi5ub29njyhX3gSQ8Xabyy67RcEJTUkgGA8Foz29Q6FgTBQdOrhsUYIM0RU6hqKQ4rhInl8jOhOUPSnYSRSvDdoaCuQzqACR3Bm/GUarJwk/UXaVHALdbLTkkVa9FtySRAU1LR8Z8P68Dg6KpwQUcnxdAwsFkaYNrak4ZkVRRZvYANAjCdegdzQb1drx8XGxkMXCoCrlSu0YBYJKLavrVZvdxH4gGFJARvX1Do6NTfX3jUj2AKcJWtMs5atH6eNcroADDvmDIRqCx8MpKsn6hbaqsu2JYPV64WhMQmc1DbISqHRCYejp9/RpA7XnnXYYuDNwZ/FlAffPHF7xwvzdmlkKAQhvWEJG0VIZilyrb1NXuEIeIpd6Hrz4cb7XNdI/EHYmLX6gyIkFTqwBfY4LqWwunz4qZdKV3d38/n5BU5CMe2VuiBQ2nQ7Q1h6vCz/dXpfsROVTsDsdbg9ELxIMBdCrRPNxCX2qlsEArdyCjhZstOHIklqS9QpaFXJrqwPWaXe2nQBE0hOl63QZIDVVof2KO+VN0gFLlgHDuhvfupIk8A67jOvB4ND2VyxxWNsMwteLNfIrTg9ZArBlQSmCnCKw/LpKKseNRimfz2SyB4X8cb1eVUzQULrTKURjgcH+2OBgvDcZDQZ8AuFtZMKhF7W9neP0QZ7nZK/L3z86jBICLztaPvMdfLfRAoipmeSNMemaDUYHzy0KTy3SAj1LfOsyA3cG7iy+rKF3jZ"></img>
_x000D_
_x000D_
_x000D_

in Javascript

var id=document.getElementById("image");

id.src=base64Url;

Can I prevent text in a div block from overflowing?

If your div has a set height in css that will cause it to overflow outside of the div.

You could give the div a min-height if you need to have it be a minimum height on the div at all times.

Min-height will not work in IE6 though, if you have an IE6 specific stylesheet you can give it a regular height for IE6. Height changes in IE6 according to the content within.

How to find specified name and its value in JSON-string from Java?

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.

Uncaught SyntaxError: Unexpected token < On Chrome

I got the same error ("Uncaught SyntaxError: Unexpected token <" ) at these two lines when testing a sample application .

<script type = "text/javascript"  src="raphael-min.js"></script>
<script type = "text/javascript"  src="kuma-gauge.jquery.js"></script>

After a control, I realized that, local file locations are not correct and my local server app returns default page as the result. Client app can find the files but the founded files are default page, not the *.js files. So I receive Uncaught SyntaxError: Unexpected token <

I changed to orginal location on the intenet andit solved.

<script type = "text/javascript"  src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
<script type = "text/javascript"  src="//www.jqueryscript.net/demo/Creating-Animated-Gauges-Using-jQuery-Raphael-js-kumaGauge/js/kuma-gauge.jquery.js"></script>

Design Patterns web based applications

In the beaten-up MVC pattern, the Servlet is "C" - controller.

Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.

I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Android Fragment no view found for ID?

This exception can also happen if the layout ID which you are passing to FragmentTransaction.replace(int ID, fragment) exists in other layouts that are being inflated. Make sure the layout ID is unique and it should work.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:

    class mydict(dict): pass
    a = mydict()        
    a["b=c"] = 'value'
    a.test = False

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

Algorithm to randomly generate an aesthetically-pleasing color palette

Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together".

estimating of testing effort as a percentage of development time

When you're estimating testing you need to identify the scope of your testing - are we talking unit test, functional, UAT, interface, security, performance stress and volume?

If you're on a waterfall project you probably have some overhead tasks that are fairly constant. Allow time to prepare any planning documents, schedules and reports.

For a functional test phase (I'm a "system tester" so that's my main point of reference) don't forget to include planning! A test case often needs at least as much effort to extract from requirements / specs / user stories as it will take to execute. In addition you need to include some time for defect raising / retesting. For a larger team you'll need to factor in test management - scheduling, reporting, meetings.

Generally my estimates are based on the complexity of the features being delivered rather than a percentage of dev effort. However this does require access to at least a high-level set of instructions. Years of doing testing enables me to work out that a test of a particular complexity will take x hours of effort for preparation and execution. Some tests may require extra effort for data setup. Some tests may involve negotiating with external systems and have a duration far in excess of the effort required.

In the end, though, you need to review it in the context of the overall project. If your estimate is well above that for BA or Development then there may be something wrong with your underlying assumptions.

I know this is an old topic but it's something I'm revisiting at the moment and is of perennial interest to project managers.

There is an error in XML document (1, 41)

In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map

Reverse Contents in Array

You are not printing the array, you are printing the value of temp - which is only half the array...

HTML Canvas Full Screen

I hope it will be useful.

// Get the canvas element
var canvas = document.getElementById('canvas');

var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
    (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
    (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
    (document.msFullscreenElement && document.msFullscreenElement !== null);

// Enter fullscreen
function fullscreen(){
    if(canvas.RequestFullScreen){
        canvas.RequestFullScreen();
    }else if(canvas.webkitRequestFullScreen){
        canvas.webkitRequestFullScreen();
    }else if(canvas.mozRequestFullScreen){
        canvas.mozRequestFullScreen();
    }else if(canvas.msRequestFullscreen){
        canvas.msRequestFullscreen();
    }else{
        alert("This browser doesn't supporter fullscreen");
    }
}

// Exit fullscreen
function exitfullscreen(){
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }else{
        alert("Exit fullscreen doesn't work");
    }
}

How to call an async method from a getter or setter?

There is no technical reason that async properties are not allowed in C#. It was a purposeful design decision, because "asynchronous properties" is an oxymoron.

Properties should return current values; they should not be kicking off background operations.

Usually, when someone wants an "asynchronous property", what they really want is one of these:

  1. An asynchronous method that returns a value. In this case, change the property to an async method.
  2. A value that can be used in data-binding but must be calculated/retrieved asynchronously. In this case, either use an async factory method for the containing object or use an async InitAsync() method. The data-bound value will be default(T) until the value is calculated/retrieved.
  3. A value that is expensive to create, but should be cached for future use. In this case, use AsyncLazy from my blog or AsyncEx library. This will give you an awaitable property.

Update: I cover asynchronous properties in one of my recent "async OOP" blog posts.

Deserialize JSON to ArrayList<POJO> using Jackson

I am also having the same problem. I have a json which is to be converted to ArrayList.

Account looks like this.

Account{
  Person p ;
  Related r ;

}

Person{
    String Name ;
    Address a ;
}

All of the above classes have been annotated properly. I have tried TypeReference>() {} but is not working.

It gives me Arraylist but ArrayList has a linkedHashMap which contains some more linked hashmaps containing final values.

My code is as Follows:

public T unmarshal(String responseXML,String c)
{
    ObjectMapper mapper = new ObjectMapper();

    AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

    mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);

    mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
    try
    {
      this.targetclass = (T) mapper.readValue(responseXML,  new TypeReference<ArrayList<T>>() {});
    }
    catch (JsonParseException e)
    {
      e.printStackTrace();
    }
    catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return this.targetclass;
}

I finally solved the problem. I am able to convert the List in Json String directly to ArrayList as follows:

JsonMarshallerUnmarshaller<T>{

     T targetClass ;

     public ArrayList<T> unmarshal(String jsonString)
     {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
                    constructCollectionType(ArrayList.class, targetclass.getClass()) ;
        try
        {
        Class c1 = this.targetclass.getClass() ;
        Class c2 = this.targetclass1.getClass() ;
            ArrayList<T> temp = (ArrayList<T>) mapper.readValue(jsonString,  type);
        return temp ;
        }
       catch (JsonParseException e)
       {
        e.printStackTrace();
       }
       catch (JsonMappingException e) {
           e.printStackTrace();
       } catch (IOException e) {
          e.printStackTrace();
       }

     return null ;
    }  

}

Properties private set;

Depending on the scope of my application, I like to put the object hydration mechanisms in the object itself. I'll wrap the data reader with a custom object and pass it a delegate that gets executed once the query returns. The delegate gets passed the DataReader. Then, since I'm in my smart business object, I can hydrate away with my private setters.

Edit for Pseudo-Code

The "DataAccessWrapper" wraps all of the connection and object lifecycle management for me. So, when I call "ExecuteDataReader," it creates the connection, with the passed proc (there's an overload for params,) executes it, executes the delegate and then cleans up after itself.

public class User
{
    public static List<User> GetAllUsers()
    {
        DataAccessWrapper daw = new DataAccessWrapper();
        return (List<User>)(daw.ExecuteDataReader("MyProc", new ReaderDelegate(ReadList)));
    }

    protected static object ReadList(SQLDataReader dr)
    {
        List<User> retVal = new List<User>();
        while(dr.Read())
        {
            User temp = new User();
            temp.Prop1 = dr.GetString("Prop1");
            temp.Prop2 = dr.GetInt("Prop2");
            retVal.Add(temp);
        }
        return retVal;
    }
}

How to recover just deleted rows in mysql?

There is another solution, if you have binary logs active on your server you can use mysqlbinlog

generate a sql file with it

mysqlbinlog binary_log_file > query_log.sql

then search for your missing rows. If you don't have it active, no other solution. Make backups next time.

jQuery get value of selected radio button

Simplest way to get the selected radio button's value is as follows:

$("input[name='optradio']:checked").val();

No space should be used in between selector.

Is there any JSON Web Token (JWT) example in C#?

I've never used it but there is a JWT implementation on NuGet.

Package: https://nuget.org/packages/JWT

Source: https://github.com/johnsheehan/jwt

.NET 4.0 compatible: https://www.nuget.org/packages/jose-jwt/

You can also go here: https://jwt.io/ and click "libraries".