Programs & Examples On #Refactoring

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

It's all in your things.size() type. It isn't int, but size_t (it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int for x86_32.

Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.

It would be correct to write it like

for (size_t i = 0; i < things.size(); ++i) { /**/ }

or even faster

for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }

How to change a package name in Eclipse?

Create your directory structure in src folder like

.

means to create subpkg1 folder under pkg1 folder (source folder in eclipse) then place your source code inside and then modify its package declaration.

Find and replace Android studio

On Windows:

Find : Ctrl+F

Find And Replace In Single Class: Ctrl+R

Find And Replace In Whole Project: Ctrl+Shift+R

on OS X ,it is similar, just replace Ctrl with Command

What is in your .vimrc?

" **************************
" * vim general options ****
" **************************
set nocompatible
set history=1000
set mouse=a

" don't have files trying to override this .vimrc:
set nomodeline

" have <F1> prompt for a help topic, rather than displaying the introduction
" page, and have it do this from any mode:
nnoremap <F1> :help<Space>
vmap <F1> <C-C><F1>
omap <F1> <C-C><F1>
map! <F1> <C-C><F1>

set title

" **************************
" * set visual options *****
" **************************
set nu
set ruler
syntax on

" colorscheme oceandeep
set background=dark

set wildmenu
set wildmode=list:longest,full

" use "[RO]" for "[readonly]"
set shortmess+=r

set scrolloff=3

" display the current mode and partially-typed commands in the status line:
set showmode
set showcmd

" don't make it look like there are line breaks where there aren't:
set nowrap

" **************************
" * set editing options ****
" **************************
set autoindent
filetype plugin indent on
set backspace=eol,indent,start
autocmd FileType text setlocal textwidth=80
autocmd FileType make set noexpandtab shiftwidth=8

" * Search & Replace
" make searches case-insensitive, unless they contain upper-case letters:
set ignorecase
set smartcase
" show the `best match so far' as search strings are typed:
set incsearch
" assume the /g flag on :s substitutions to replace all matches in a line:
set gdefault

" ***************************
" * tab completion **********
" ***************************
setlocal omnifunc=syntaxcomplete#Complete
imap <Tab> <C-x><C-o>
inoremap <tab> <c-r>=InsertTabWrapper()<cr>

" ***************************
" * keyboard mapping ********
" ***************************
imap <A-1> <Esc>:tabn 1<CR>i
imap <A-2> <Esc>:tabn 2<CR>i
imap <A-3> <Esc>:tabn 3<CR>i
imap <A-4> <Esc>:tabn 4<CR>i
imap <A-5> <Esc>:tabn 5<CR>i
imap <A-6> <Esc>:tabn 6<CR>i
imap <A-7> <Esc>:tabn 7<CR>i
imap <A-8> <Esc>:tabn 8<CR>i
imap <A-9> <Esc>:tabn 9<CR>i

map <A-1> :tabn 1<CR>
map <A-2> :tabn 2<CR>
map <A-3> :tabn 3<CR>
map <A-4> :tabn 4<CR>
map <A-5> :tabn 5<CR>
map <A-6> :tabn 6<CR>
map <A-7> :tabn 7<CR>
map <A-8> :tabn 8<CR>
map <A-9> :tabn 9<CR>

" ***************************
" * Utilities Needed ********
" ***************************
function InsertTabWrapper()
      let col = col('.') - 1
      if !col || getline('.')[col - 1] !~ '\k'
          return "\<tab>"
      else
          return "\<c-p>"
      endif
endfunction

" end of .vimrc

Find unused code

FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.

I think NDepend looks like a more likely candidate.

What are some alternatives to ReSharper?

Keep in mind that with Visual Studio 2010 you may not need/want any addon. A lot of the ReSharper features were added into the Visual Studio 2010 core features. ReSharper, CodeRush, etc. have other features above and beyond Visual Studio for sure, but see what's been added vs. what you need. It could be that the core install takes care of what you are interested in now.

I personally use ReSharper 5 still as it has many uses, for me. What each coder finds most important though varies widely. You'll have to test each for yourself, but luckily all the alternatives have trial periods as well.

Replace Multiple String Elements in C#

string input = "it's worth a lot of money, if you can find a buyer.";
for (dynamic i = 0, repl = new string[,] { { "'", "''" }, { "money", "$" }, { "find", "locate" } }; i < repl.Length / 2; i++) {
    input = input.Replace(repl[i, 0], repl[i, 1]);
}

Detecting superfluous #includes in C/C++?

Google's cppclean (links to: download, documentation) can find several categories of C++ problems, and it can now find superfluous #includes.

There's also a Clang-based tool, include-what-you-use, that can do this. include-what-you-use can even suggest forward declarations (so you don't have to #include so much) and optionally clean up your #includes for you.

Current versions of Eclipse CDT also have this functionality built in: going under the Source menu and clicking Organize Includes will alphabetize your #include's, add any headers that Eclipse thinks you're using without directly including them, and comments out any headers that it doesn't think you need. This feature isn't 100% reliable, however.

How to simplify a null-safe compareTo() implementation?

Using Java 8:

private static Comparator<String> nullSafeStringComparator = Comparator
        .nullsFirst(String::compareToIgnoreCase); 

private static Comparator<Metadata> metadataComparator = Comparator
        .comparing(Metadata::getName, nullSafeStringComparator)
        .thenComparing(Metadata::getValue, nullSafeStringComparator);

public int compareTo(Metadata that) {
    return metadataComparator.compare(this, that);
}

How to find unused/dead code in java projects

We've started to use Find Bugs to help identify some of the funk in our codebase's target-rich environment for refactorings. I would also consider Structure 101 to identify spots in your codebase's architecture that are too complicated, so you know where the real swamps are.

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

Python: avoiding pylint warnings about too many arguments

I came across the same nagging error, which I realized has something to do with a cool feature PyCharm automatically detects...just add the @staticmethod decorator, and it will automatically remove that error where the method is used

Error:Cause: unable to find valid certification path to requested target

I faced the same issue, but fixed it by adding

maven { url "http://jcenter.bintray.com"}

in the project Level Gradle File

buildscript {
repositories {
    jcenter()
    maven { url "http://jcenter.bintray.com"}
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
    mavenCentral()
    jcenter{ url "http://jcenter.bintray.com/" }
    maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

Password Protect a SQLite DB. Is it possible?

Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net

Removing pip's cache?

If using pip 6.0 or newer, try adding the --no-cache-dir option (source).

If using pip older than pip 6.0, upgrade it with pip install -U pip.

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

How to get the Google Map based on Latitude on Longitude?

Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.

If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:

UPDATE  student_queues 
SET  Deleted=0, 
     last_accessed_by='raja', 
     last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'

Or if you want to use CAST, replace with:

CAST('2014-07-23 09:37:00.000' AS datetime2)

This is using the SQL ISO Date Format.

Key existence check in HashMap

Better way is to use containsKey method of HashMap. Tomorrow somebody will add null to the Map. You should differentiate between key presence and key has null value.

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Why use a ReentrantLock if one can use synchronized(this)?

From oracle documentation page about ReentrantLock:

A reentrant mutual exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

  1. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.

  2. The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.

ReentrantLock key features as per this article

  1. Ability to lock interruptibly.
  2. Ability to timeout while waiting for lock.
  3. Power to create fair lock.
  4. API to get list of waiting thread for lock.
  5. Flexibility to try for lock without blocking.

You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock to further acquire control on granular locking on read and write operations.

Have a look at this article by Benjamen on usage of different type of ReentrantLocks

Single line if statement with 2 actions

Sounds like you really want a Dictionary<int, string> or possibly a switch statement...

You can do it with the conditional operator though:

userType = user.Type == 0 ? "Admin"
         : user.Type == 1 ? "User"
         : user.Type == 2 ? "Employee"
         : "The default you didn't specify";

While you could put that in one line, I'd strongly urge you not to.

I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.

What does the ELIFECYCLE Node.js error mean?

It's basically saying it fails to spawn your process not due to permission but to an error in your script. Source

You don't have any problem executing NODE_ENV=production node app.js ?

MySQL Workbench not opening on Windows

As per the current setup on June, 2017 Here is the downloadable link for Visual C++ 2015 Redistributable package : https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe

Hope this will help, who are struggling with the download link.

Note: This is with regards to MySQL Workbench 6.3.9

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

Read next word in java

You already get the next line in this line of your code:

 String line = sc.nextLine();  

To get the words of a line, I would recommend to use:

String[] words = line.split(" ");

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Bootstrap 3: Keep selected tab on page refresh

My code, it work for me, I use localStorage HTML5

$('#tabHistory  a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href");
  localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');

jQuery: enabling/disabling datepicker

You can replace form field with its copy:

var copy = $('#from').clone(); $('#from').replaceWith(copy);

And after that initialize datetimepicker again.

In Java, what does NaN mean?

NaN stands for Not a Number. It is used to signify any value that is mathematically undefined. Like dividing 0.0 by 0.0. You can look here for more information: https://web.archive.org/web/20120819091816/http://www.concentric.net/~ttwang/tech/javafloat.htm

Post your program here if you need more help.

Styling twitter bootstrap buttons

I know this is an older thread, but just to add another perspective. I'd assert that using overrides is really a bit of a code smell and will quickly get out of hand on larger projects. Today you're overriding Buttons, tomorrow Modals, the next day it Dropdowns, etc., etc.

I'd advise to try possibly commenting out the include for buttons.less and either define my own, or, find another Buttons library that's more suitable to my project. Shameless plug: here's an example of how easy it is to mix our Buttons library with TB: Using Buttons with Twitter Bootstrap. In practice, again, you'd likely want to remove the buttons.less include altogether to improve performance but this shows how you can make things look a bit less "generic". I haven't done this exercise yet myself but I'd imagine you could start by simply commenting out lines like:

https://github.com/twbs/bootstrap/blob/master/less/bootstrap.less#L17

And then recompiling using `lessc using one of your own buttons modules. That way you get the battle tested core of TB but can still customize things without resorting to major overrides. There's absolutely no reason not to use only parts of a library like Bootstrap. Of course the same applies to the Sass version of TB

Filter array to have unique values

I've always used:

unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);

But recently I had to get unique values for:

["1", 1, "2", 2, "3", 3]

And my old standby didn't cut it, so I came up with this:

uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));

Is < faster than <=?

Historically (we're talking the 1980s and early 1990s), there were some architectures in which this was true. The root issue is that integer comparison is inherently implemented via integer subtractions. This gives rise to the following cases.

Comparison     Subtraction
----------     -----------
A < B      --> A - B < 0
A = B      --> A - B = 0
A > B      --> A - B > 0

Now, when A < B the subtraction has to borrow a high-bit for the subtraction to be correct, just like you carry and borrow when adding and subtracting by hand. This "borrowed" bit was usually referred to as the carry bit and would be testable by a branch instruction. A second bit called the zero bit would be set if the subtraction were identically zero which implied equality.

There were usually at least two conditional branch instructions, one to branch on the carry bit and one on the zero bit.

Now, to get at the heart of the matter, let's expand the previous table to include the carry and zero bit results.

Comparison     Subtraction  Carry Bit  Zero Bit
----------     -----------  ---------  --------
A < B      --> A - B < 0    0          0
A = B      --> A - B = 0    1          1
A > B      --> A - B > 0    1          0

So, implementing a branch for A < B can be done in one instruction, because the carry bit is clear only in this case, , that is,

;; Implementation of "if (A < B) goto address;"
cmp  A, B          ;; compare A to B
bcz  address       ;; Branch if Carry is Zero to the new address

But, if we want to do a less-than-or-equal comparison, we need to do an additional check of the zero flag to catch the case of equality.

;; Implementation of "if (A <= B) goto address;"
cmp A, B           ;; compare A to B
bcz address        ;; branch if A < B
bzs address        ;; also, Branch if the Zero bit is Set

So, on some machines, using a "less than" comparison might save one machine instruction. This was relevant in the era of sub-megahertz processor speed and 1:1 CPU-to-memory speed ratios, but it is almost totally irrelevant today.

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Performance-wise bash outperforms python in the process startup time.

Here are some measurements from my core i7 laptop running Linux Mint:

Starting process                       Startup time

empty /bin/sh script                   1.7 ms
empty /bin/bash script                 2.8 ms
empty python script                    11.1 ms
python script with a few libs*         110 ms

*Python loaded libs are: os, os.path, json, time, requests, threading, subprocess

This shows a huge difference however bash execution time degrades quickly if it has to do anything sensible since it usually must call external processes.

If you care about performance use bash only for:

  • really simple and frequently called scripts
  • scripts that mainly call other processes
  • when you need minimal friction between manual administrative actions and scripting - fast check a few commands and place them in the file.sh

What does the @ symbol before a variable name mean in C#?

The @ symbol serves 2 purposes in C#:

Firstly, it allows you to use a reserved keyword as a variable like this:

int @int = 15;

The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:

var myString = "c:\\myfolder\\myfile.txt"

alternatively you can do this:

var myString = @"c:\myFolder\myfile.txt"

Docker official registry (Docker Hub) URL

You're able to get the current registry-url using docker info:

...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...

That's also the url you may use to run your self hosted-registry:

docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2

Grep & use it right away:

$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/

When do I need to do "git pull", before or after "git add, git commit"?

pull = fetch + merge.

You need to commit what you have done before merging.

So pull after commit.

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

Call break in nested if statements

You need that it breaks the outer if statement. Why do you use second else?

IF condition THEN  
    IF condition THEN 
        sequence 1
    // ELSE sequence 4
       // break //?  
    // ENDIF    
ELSE    
    sequence 3    
ENDIF

sequence 4

What does the servlet <load-on-startup> value signify

The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute "load-on-startup" in "web.xml" file. If the attribute has a positive integer(0 to 128) then the servlet is load with the loading of the container otherwise it loads when the first request comes for service.

When the servlet is loaded once it gets request then it is called "Lazy loading".

How to merge remote master to local branch

Switch to your local branch

> git checkout configUpdate

Merge remote master to your branch

> git rebase master configUpdate

In case you have any conflicts, correct them and for each conflicted file do the command

> git add [path_to_file/conflicted_file] (e.g. git add app/assets/javascripts/test.js)

Continue rebase

> git rebase --continue

PHP: How to check if a date is today, yesterday or tomorrow

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

String concatenation in Jinja

You can use + if you know all the values are strings. Jinja also provides the ~ operator, which will ensure all values are converted to string first.

{% set my_string = my_string ~ stuff ~ ', '%}

How to convert an Instant to a date format?

An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).

To print it as a date/time, you first need to decide which timezone to use. For example:

System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));

This will print the date/time in iso format: 2015-06-02T10:15:02.325

If you want a different format you can use a formatter:

LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

Calculating the SUM of (Quantity*Price) from 2 different tables

I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.

select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
    select o.orderID, o.price * o.qty as subtotal
    from product p inner join orderitem o on p.ProductID= o.productID
    where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

Sometime in the future Comment out the following code in web.config

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>

How do I obtain the frequencies of each value in an FFT?

Your kth FFT result's frequency is 2*pi*k/N.

How to refresh page on back button click?

Ahem u_u

As i've stated the back button is for every one of us a pain in some place... that said...

As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this

The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.

But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.

From a Sybase Database, how I can get table description ( field names and types)?

Here a different approach to get meta data. This very helpful SQL command returns you the table / view definition as text:

SELECT text FROM syscomments WHERE id = OBJECT_ID('MySchema.MyTable') ORDER BY number, colid2, colid

Enjoy Patrick

Undo working copy modifications of one file in Git?

You can use

git checkout -- file

You can do it without the -- (as suggested by nimrodm), but if the filename looks like a branch or tag (or other revision identifier), it may get confused, so using -- is best.

You can also check out a particular version of a file:

git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file         # stable branch
git checkout origin/master -- file  # upstream master
git checkout HEAD -- file           # the version from the most recent commit
git checkout HEAD^ -- file          # the version before the most recent commit

How do I use a custom deleter with a std::unique_ptr member?

You can simply use std::bind with a your destroy function.

std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
    std::placeholders::_1));

But of course you can also use a lambda.

std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});

How to get IntPtr from byte[] in C#

IntPtr GetIntPtr(Byte[] byteBuf)
{
    IntPtr ptr = Marshal.AllocHGlobal(byteBuf.Length);
    for (int i = 0; i < byteBuf.Length; i++)
    {
       Marshal.WriteByte(ptr, i, byteBuf[i]);
    }
    return ptr;
}

How can I bind a background color in WPF/XAML?

You can still use "Background" as the property name, as long as you give your window a name and use this name on the "Source" of the Binding.

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

Reverse each individual word of "Hello World" string with Java

No one here is considering unicode characters. You need to use java.text.BreakIterator to find word boundaries and then use another one within each word boundary to enumerate character boundaries:

String helloWorld = "He\u0308llo World"; // Hëllo World
StringBuilder reverseStringBuilder = new StringBuilder(helloWorld.length());
BreakIterator wordBreakIterator = BreakIterator.getWordInstance();
wordBreakIterator.setText(helloWorld);

int wordStart = wordIterator.first();
int wordEnd = wordIterator.next();

while (wordEnd != BreakIterator.DONE) {
    String word = helloWorld.substring(wordStart,wordEnd);
    if (Character.isLetterOrDigit(word.charAt(0))) {
        // "Hello" or "World" in our example
        BreakIterator characterBreakIterator = BreakIterator.getCharacterInstance();
        characterBreakIterator.setText(word);
        int characterEnd = characterBreakIterator.last();
        int characterStart = characterBreakIterator.previous();
        while (characterStart != BreakIterator.DONE) {
            reverseStringBuilder.append(word.substring(characterStart, characterEnd));

            characterEnd = characterStart;
            characterStart = characterBreakIterator.previous();
        }
    } else {
        // " " in our example
        reverseStringBuilder.append(word);
    }
    wordStart = wordEnd;
    wordEnd = wordIterator.next();
}

String dlroWolleh = reverseStringBuilder.toString(); // "dlroW ollëH"

Using naive methods above will shift the diacritic character \u0308 above the first l when you reverse the String. You want it to stay above the e.

Hide all elements with class using plain Javascript

In the absence of jQuery, I would use something like this:

<script>
    var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
    for(var i = 0; i < divsToHide.length; i++){
        divsToHide[i].style.visibility = "hidden"; // or
        divsToHide[i].style.display = "none"; // depending on what you're doing
    }
<script>

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

Check table exist or not before create it in Oracle

declare n number(10);

begin
   select count(*) into n from tab where tname='TEST';

   if (n = 0) then 
      execute immediate 
      'create table TEST ( ID NUMBER(3), NAME VARCHAR2 (30) NOT NULL)';
   end if;
end;

phpMyAdmin - The MySQL Extension is Missing

Your installation is missing some php modules, there should be a list of required modules in the phpmyadmin readme. If you recently enabled the modules, try restarting the apache service / daemon.

Edit: As it seems, there is no single "enable these modules" in the docs, so enable either mysql or mysqli in your php.ini (you might need to install it first).

The two messages are not important if you do not intend to upload or download compressed file within phpMyAdmin. If you do, enable the zlib and / or bz2 modules.

How to implode array with key and value without foreach in PHP

and another way:

$input = array(
    'item1'  => 'object1',
    'item2'  => 'object2',
    'item-n' => 'object-n'
);

$output = implode(', ', array_map(
    function ($v, $k) {
        if(is_array($v)){
            return $k.'[]='.implode('&'.$k.'[]=', $v);
        }else{
            return $k.'='.$v;
        }
    }, 
    $input, 
    array_keys($input)
));

or:

$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
    $input,
    array_keys($input)
));

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

You can find details about these in this Android - Command Line Tools


tl;dr:

SDK Tools:

  1. Android SDK Manager (sdkmanager)
  2. AVD Manager (avdmanager)
  3. Dalvik Debug Monitor Server (ddms)

Build Tools:

  1. signer
  2. proGuard
  3. zipalign
  4. jobb

Platform Tools:

  1. adb
  2. aidl, aapt, dexdump, and dx
  3. bmgr
  4. logcat

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

In my case, in the initializer from the class I was using in the database's table, I wasn't setting any default value to my DateTime property, therefore resulting in the problem explained in @Andrew Orsich' answer. So I just made the property nullable. Or I could also have given it DateTime.Now in the constructor. Hope it helps someone.

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

How to get Latitude and Longitude of the mobile device in android?

Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will do the business.

LocationFinder

public class LocationFinder extends Activity {

    int increment = 4;
    MyLocation myLocation = new MyLocation();

    // private ProgressDialog dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intermediat);
        myLocation.getLocation(getApplicationContext(), locationResult);

        boolean r = myLocation.getLocation(getApplicationContext(),
            locationResult);

        startActivity(new Intent(LocationFinder.this,
        // Nearbyhotelfinder.class));
            GPSMyListView.class));
        finish();
    }

    public LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            // TODO Auto-generated method stub
            double Longitude = location.getLongitude();
            double Latitude = location.getLatitude();

            Toast.makeText(getApplicationContext(), "Got Location",
                Toast.LENGTH_LONG).show();

            try {
                SharedPreferences locationpref = getApplication()
                    .getSharedPreferences("location", MODE_WORLD_READABLE);
                SharedPreferences.Editor prefsEditor = locationpref.edit();
                prefsEditor.putString("Longitude", Longitude + "");
                prefsEditor.putString("Latitude", Latitude + "");
                prefsEditor.commit();
                System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    // handler for the background updating

}

MyLocation

public class MyLocation {

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();


        timer1.schedule(new GetLastLocation(), 10000);
    //    Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override

        public void run() {

            //Context context = getClass().getgetApplicationContext();
             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

Concatenating string and integer in python

Let's assume you want to concatenate string and integer in a situation like this:

for i in range(1,11):
   string="string"+i 

and you are getting type or concatenation error

The best way to go about it is to do something like this:

for i in range(1,11):
   print("string",i)    

This will give you concatenated results like string 1, string 2, string 3 ...etc

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

How to retry image pull in a kubernetes Pods?

Most probably the issue of ImagePullBackOff is due to either the image not being present or issue with the pod YAML file.

What I will do is this

kubectl get pod -n $namespace $POD_NAME --export > pod.yaml | kubectl -f apply -

I would also see the pod.yaml to see the why the earlier pod didn't work

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to update UI from another thread running in another class

You're right that you should use the Dispatcher to update controls on the UI thread, and also right that long-running processes should not run on the UI thread. Even if you run the long-running process asynchronously on the UI thread, it can still cause performance issues.

It should be noted that Dispatcher.CurrentDispatcher will return the dispatcher for the current thread, not necessarily the UI thread. I think you can use Application.Current.Dispatcher to get a reference to the UI thread's dispatcher if that's available to you, but if not you'll have to pass the UI dispatcher in to your background thread.

Typically I use the Task Parallel Library for threading operations instead of a BackgroundWorker. I just find it easier to use.

For example,

Task.Factory.StartNew(() => 
    SomeObject.RunLongProcess(someDataObject));

where

void RunLongProcess(SomeViewModel someDataObject)
{
    for (int i = 0; i <= 1000; i++)
    {
        Thread.Sleep(10);

        // Update every 10 executions
        if (i % 10 == 0)
        {
            // Send message to UI thread
            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                (Action)(() => someDataObject.ProgressValue = (i / 1000)));
        }
    }
}

Create a unique number with javascript time

In 2020, you can use the in-browser Crypto API to generate cryptographically strong random values.

function getRandomNumbers() {
  const typedArray = new Uint8Array(10);
  const randomValues = window.crypto.getRandomValues(typedArray);
  return randomValues.join('');
}

console.log(getRandomNumbers());
// 1857488137147725264738

both Uint8Array and Crypto.getRandomValues are supported on all major browsers, including IE11

Angular4 - No value accessor for form control

For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.

const countryControl = new FormControl();

And inside template use like this

    <select multiple name="countries" [formControl]="countryControl">
      <option *ngFor="let country of countries" [ngValue]="country">
       {{ country.name }}
      </option>
    </select>

More details ref Official Docs

Uncaught ReferenceError: function is not defined with onclick

If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

How to get the primary IP address of the local machine on Linux and OS X?

This is easier to read: ifconfig | grep 'inet addr:' |/usr/bin/awk '{print $2}' | tr -d addr:

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

You shouldn't use CascadeType.ALL on @ManyToOne since entity state transitions should propagate from parent entities to child ones, not the other way around.

The @ManyToOne side is always the Child association since it maps the underlying Foreign Key column.

Therefore, you should move the CascadeType.ALL from the @ManyToOne association to the @OneToMany side, which should also use the mappedBy attribute since it's the most efficient one-to-many table relationship mapping.

How to convert current date to epoch timestamp?

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

Putting an if-elif-else statement on one line?

You can use nested ternary if statements.

# if-else ternary construct
country_code = 'USA'
is_USA = True if country_code == 'USA' else False
print('is_USA:', is_USA)

# if-elif-else ternary construct
# Create function to avoid repeating code.
def get_age_category_name(age):
    age_category_name = 'Young' if age <= 40 else ('Middle Aged' if age > 40 and age <= 65 else 'Senior')
    return age_category_name

print(get_age_category_name(25))
print(get_age_category_name(50))
print(get_age_category_name(75))

Full screen background image in an activity

Add android:background="@drawable/your_image" inside your Relativelayout/Linearlayout Worked.

How to convert a Hibernate proxy to a real entity object

Since Hibernate ORM 5.2.10, you can do it likee this:

Object unproxiedEntity = Hibernate.unproxy(proxy);

Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext implementation:

Object unproxiedEntity = ((SessionImplementor) session)
                         .getPersistenceContext()
                         .unproxy(proxy);

How to convert JSONObjects to JSONArray?

To deserialize the response need to use HashMap:

String resp = ...//String output from your source

Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);

class TheResponse{
 HashMap<String,Song> songs;
}

class Song{
  String id;
  String pos;
}

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

How to change the color of an svg element?

Open your image using a browser, right-click on the image click on view page source and you will see the svg tag of the image. Cope and paste into your html, then change the fill to the colour of your choice

How do you set the startup page for debugging in an ASP.NET MVC application?

Selecting a specific page from Project properties does not solve my problem.

In MVC 4 open App_Start/RouteConfig.cs

For example, if you want to change startup page to Login:

routes.MapRoute(
        "Default", // Route name
        "",        // URL with parameters
        new { controller = "Account", action = "Login"}  // Parameter defaults
    );

Access nested dictionary items via a list of keys?

Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.

The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:

def keysInDict(dataDict, parent=[]):
    if not isinstance(dataDict, dict):
        return [tuple(parent)]
    else:
        return reduce(list.__add__, 
            [keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])

One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).

def dict_to_df(dataDict):
    ret = []
    for k in keysInDict(dataDict):
        v = np.array( getFromDict(dataDict, k), )
        v = pd.DataFrame(v)
        v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
        ret.append(v)
    return reduce(pd.DataFrame.join, ret)

How to use boolean datatype in C?

C99 has a boolean datatype, actually, but if you must use older versions, just define a type:

typedef enum {false=0, true=1} bool;

align 3 images in same row with equal spaces?

This should be your answer

<div align="center">
 <img src="@Url.Content("~/images/image3.bmp")" alt="" align="right" style="float:right"/>
 <img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" style="float:left" />
 <div id="content" align="center"> 
     <img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" />
 </div>
 </div>

MySQL select one column DISTINCT, with corresponding other columns

try this query

 SELECT ID, FirstName, LastName FROM table GROUP BY(FirstName)

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

For me this happened within a class function.

In PHP 5.3 and above $this::$defaults worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.

The solution, in my case, was to use the keyword self instead of $this:

self::$defaults works just fine.

Logging best practices

As far as aspect oriented logging is concerned I was recommended PostSharp on another SO question -

Aspect Oriented Logging with Unity\T4\anything else

The link provided in the answer is worth visiting if you are evaluating logging frameworks.

Accessing a local website from another computer inside the local network in IIS 7

do not turn off firewall, Go Control Panel\System and Security\Windows Firewall then Advanced settings then Inbound Rules->From right pan choose New Rule-> Port-> TCP and type in port number 80 then give a name in next window, that's it.

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

How to load Spring Application Context

Add this at the start of main

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");

JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");

//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

Getting last day of the month in a given string date

This looks like your needs:

http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html

code:

import java.text.DateFormat;  
import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  

//Java 1.4+ Compatible  
//  
// The following example code demonstrates how to get  
// a Date object representing the last day of the month  
// relative to a given Date object.  

public class GetLastDayOfMonth {  

    public static void main(String[] args) {  

        Date today = new Date();  

        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(today);  

        calendar.add(Calendar.MONTH, 1);  
        calendar.set(Calendar.DAY_OF_MONTH, 1);  
        calendar.add(Calendar.DATE, -1);  

        Date lastDayOfMonth = calendar.getTime();  

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        System.out.println("Today            : " + sdf.format(today));  
        System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));  
    }  

} 

Output:

Today            : 2010-08-03  
Last Day of Month: 2010-08-31  

How do I implement onchange of <input type="text"> with jQuery?

There is one and only one reliable way to do this, and it is by pulling the value in an interval and comparing it to a cached value.

The reason why this is the only way is because there are multiple ways to change an input field using various inputs (keyboard, mouse, paste, browser history, voiceinput etc.) and you can never detect all of them using standard events in a cross-browser environment.

Luckily, thanks to the event infrastructure in jQuery, it’s quite easy to add your own inputchange event. I did so here:

$.event.special.inputchange = {
    setup: function() {
        var self = this, val;
        $.data(this, 'timer', window.setInterval(function() {
            val = self.value;
            if ( $.data( self, 'cache') != val ) {
                $.data( self, 'cache', val );
                $( self ).trigger( 'inputchange' );
            }
        }, 20));
    },
    teardown: function() {
        window.clearInterval( $.data(this, 'timer') );
    },
    add: function() {
        $.data(this, 'cache', this.value);
    }
};

Use it like: $('input').on('inputchange', function() { console.log(this.value) });

There is a demo here: http://jsfiddle.net/LGAWY/

If you’re scared of multiple intervals, you can bind/unbind this event on focus/blur.

What is the email subject length limit?

after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO" inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!

I have several examples like this one:

Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=

TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=

To:

As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.

It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.

If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Environment variable substitution in sed

With your question edit, I see your problem. Let's say the current directory is /home/yourname ... in this case, your command below:

sed 's/xxx/'$PWD'/'

will be expanded to

sed `s/xxx//home/yourname//

which is not valid. You need to put a \ character in front of each / in your $PWD if you want to do this.

Maintain model of scope when changing between views in AngularJS

I had the same problem, This is what I did: I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:

var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);

app.config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/:page', {
        templateUrl: function(page){return page.page + '.html';},
        controller:'otisCtrl'
    })
    .otherwise({redirectTo:'/otis'});
}]);

I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:

app.factory('otisService', function($http){
    var service = {            
        answers:[],
        ...

    }        
    return service;
});

app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',  
function($scope, $window, otisService, $routeParams){        
    $scope.message = "Hello from page: " + $routeParams.page;
    $scope.update = function(answer){
        otisService.answers.push(answers);
    };
    ...
}]);

Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).

How to display raw html code in PRE or something like it but without escaping it

If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.

<pre>
  ${fn:escapeXml('
    <!-- all your code --> 
  ')};
</pre>

PHPExcel auto size column width

$col = 'A';
while(true){
    $tempCol = $col++;
    $objPHPExcel->getActiveSheet()->getColumnDimension($tempCol)->setAutoSize(true);
    if($tempCol == $objPHPExcel->getActiveSheet()->getHighestDataColumn()){
        break;
    }
}

Where does the slf4j log file get saved?

slf4j is only an API. You should have a concrete implementation (for example log4j). This concrete implementation has a config file which tells you where to store the logs.

enter image description here

When slf4j catches a log messages with a logger, it is given to an appender which decides what to do with the message. By default, the ConsoleAppender displays the message in the console.

The default configuration file is :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

  <Appenders>
    <!-- By default => console -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
  </Appenders>

  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

If you put a configuration file available in the classpath, then your concrete implementation (in your case, log4j) will find and use it. See Log4J documentation.

Example of file appender :

<Appenders>
<File name="File" fileName="${filename}">
  <PatternLayout>
    <pattern>%d %p %C{1.} [%t] %m%n</pattern>
  </PatternLayout>
</File>

...
</Appenders>

Complete example with a file appender :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

  <Appenders>
    <File name="File" fileName="${filename}">
      <PatternLayout>
        <pattern>%d %p %C{1.} [%t] %m%n</pattern>
      </PatternLayout>
    </File>
  </Appenders>

  <Loggers>
    <Root level="error">
      <AppenderRef ref="File"/>
    </Root>
  </Loggers>

</Configuration>

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

How to write a cron that will run a script every day at midnight?

from the man page

linux$ man -S 5 crontab

   cron(8) examines cron entries once every minute.

   The time and date fields are:

          field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sun, or use names)
   ...
   # run five minutes after midnight, every day
   5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
   ...

It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.

   # Run once after reboot.
   @reboot         /usr/local/sbin/run_only_once_after_reboot.sh

You can also use this trick to run your cron job multiple times per minute.

   # Run every minute at 0, 20, and 40 second intervals
   * * * * *       sleep 00; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 20; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 40; /usr/local/sbin/run_3times_per_minute.sh

To add a cron job, you can do one of three things:

  1. add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).

    • edit a user's crontab as root with crontab -e -u <username>
    • or edit the current user's crontab with just crontab -e
    • You can set the editor with the EDITOR environment variable
      • env EDITOR=nano crontab -e -u <username>
      • or set the value of EDITOR for your entire shell session
        1. export EDITOR=vim
        2. crontab -e
    • Make scripts executable with chmod a+x <file>


  1. create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly directories

    • anacron /etc/cron.*ly directories:
      • /etc/cron.daily
      • /etc/cron.hourly
      • /etc/cron.monthly
      • /etc/cron.weekly
    • as in:
      • /etc/cron.daily/script_runs_daily.sh
      • chmod a+x /etc/cron.daily/script_runs_daily.sh -- make it executable
    • See also the anacron man page: man anacron
    • Make scripts executable with chmod a+x <file>
    • When do these cron.*ly script run?
      • For RHEL/CentOS 5.x, they are configured in /etc/crontab or /etc/anacrontab to run at a set time
      • RHEL/CentOS 6.x+ and Fedora 17+ Linux systems only define this in /etc/anacrontab, and define cron.hourly in /etc/cron.d/0hourly


  1. Or, One can create system crontables in /etc/cron.d.

    • The previously described crontab syntax (with additionally providing a user to execute each job as) is put into a file, and the file is dropped into the /etc/cron.d directory.
    • These are easy to manage in system packaging (e.g. RPM packages), so may usually be application specific.
    • The syntax difference is that a user must be specified for the cron job after the time/date fields and before the command to execute.
    • The files added to /etc/cron.d do not need to be executable.
    • Here is an example job that is executed as the user someuser, and the use of /bin/bash as the shell is forced.


   File: /etc/cron.d/myapp-cron
   # use /bin/bash to run commands, no matter what /etc/passwd says
   SHELL=/bin/bash
   # Execute a nightly (11:00pm) cron job to scrub application records
   00 23 * * * someuser /opt/myapp/bin/scrubrecords.php

How to programmatically set style attribute in a view

I faced the same problem recently. here is how i solved it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <!-- This is the special two colors background START , after this LinearLayout, you can add all view that have it for main background-->
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:weightSum="2"

    android:background="#FFFFFF"
    android:orientation="horizontal"
    >

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0000FF" />

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#F000F0" />
    </LinearLayout>
    <!-- This is the special two colors background END-->

   <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="This Text is centered with a special backgound,
    You can add as much elements as you want as child of this RelativeLayout"
    android:textColor="#FFFFFF"
    android:textSize="20sp" />
</RelativeLayout>
  • I used a LinearLayout with android:weightSum="2"
  • I gave to the two child elements android:layout_weight="1" (I gave each 50% of the parent space(width & height))
  • And finally, i gave the two child element different background colors to have the final effect.

Thanks !

How do I delete a local repository in git?

In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but

cd repository-path/
rm -r .git

should do the trick.

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Kubernetes service external ip pending

If it is your private k8s cluster, MetalLB would be a better fit. Below are the steps.

Step 1: Install MetalLB in your cluster

kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/namespace.yaml
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/metallb.yaml
# On first install only
kubectl create secret generic -n metallb-system memberlist --from-literal=secretkey="$(openssl rand -base64 128)"

Step 2: Configure it by using a configmap

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 172.42.42.100-172.42.42.105 #Update this with your Nodes IP range 

Step 3: Create your service to get an external IP (would be a private IP though).

FYR:

Before MetalLB installation: enter image description here

After MetalLB installation: enter image description here

enter image description here

How to check if a network port is open on linux?

If you only care about the local machine, you can rely on the psutil package. You can either:

  1. Check all ports used by a specific pid:

    proc = psutil.Process(pid)
    print proc.connections()
    
  2. Check all ports used on the local machine:

    print psutil.net_connections()
    

It works on Windows too.

https://github.com/giampaolo/psutil

What are native methods in Java and where should they be used?

What are native methods in Java and where should they be used?

Once you see a small example, it becomes clear:

Main.java:

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.

So it is clear that it allows you to:

  • call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
  • and get results back into Java

This could be used to:

  • write faster code on a critical section with better CPU assembly instructions (not CPU portable)
  • make direct system calls (not OS portable)

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

UILabel Align Text to center

In xamarin ios suppose your label name is title then do the following

title.TextAlignment = UITextAlignment.Center;

How do I create a folder in a GitHub repository?

To add a new directory all you have to do is create a new folder in your local repository. Create a new folder, and add a file in it.

Now go to your terminal and add it like you add the normal files in Git. Push them into the repository, and check the status to make sure you have created a directory.

Force DOM redraw/refresh on Chrome/Mac

I had a react component list which when scrolled, then opened another page, then when returning back the list was not rendered on Safari iOS until page was scrolled. So this is the fix.

    componentDidMount() {
        setTimeout(() => {
            window.scrollBy(0, 0);
        }, 300);
    }

Detect Route Change with react-router

React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;

How can I resolve the error: "The command [...] exited with code 1"?

I know this is too late for sure, but, this could help someone as well.

In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).

Make sure that you can copy from the command prompt,

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

How to change Elasticsearch max memory size

For anyone looking to do this on Centos 7 or with another system running SystemD, you change it in

/etc/sysconfig/elasticsearch 

Uncomment the ES_HEAP_SIZE line, and set a value, eg:

# Heap Size (defaults to 256m min, 1g max)
ES_HEAP_SIZE=16g

(Ignore the comment about 1g max - that's the default)

Launching a website via windows commandline

Using a CLI, the easiest way (cross-platform) I've found is to use the NPM package https://github.com/sindresorhus/open-cli

npm install --global open-cli

Installing it globally allows running something like open-cli https://unlyed.github.io/next-right-now/.

You can also install it locally (e.g: in a project) and run npx open-cli https://unlyed.github.io/next-right-now/

Or, using a NPM script (which is how I actually use it): "doc:online": "open-cli https://unlyed.github.io/next-right-now/",

Running yarn doc:online will open the webpage, and this works on any platform (windows, mac, linux).

git rebase fatal: Needed a single revision

The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.

To query the remote (in this case origin) for its HEAD (typically master), and set that as the default branch:

$ git remote set-head origin --auto

If you want to use a different default remote branch locally, you can specify that branch:

$ git remote set-head origin new-default

Once the default branch is set, you can use just the remote name in git rebase <remote> and any other commands instead of explicit <remote>/<branch>.

Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD.

$ cat .git/refs/remotes/origin/HEAD 
ref: refs/remotes/origin/master

See the git-remote man page for further details.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

ICommand MVVM implementation

This is almost identical to how Karl Shifflet demonstrated a RelayCommand, where Execute fires a predetermined Action<T>. A top-notch solution, if you ask me.

public class RelayCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

This could then be used as...

public class MyViewModel
{
    private ICommand _doSomething;
    public ICommand DoSomethingCommand
    {
        get
        {
            if (_doSomething == null)
            {
                _doSomething = new RelayCommand(
                    p => this.CanDoSomething,
                    p => this.DoSomeImportantMethod());
            }
            return _doSomething;
        }
    }
}

Read more:
Josh Smith (introducer of RelayCommand): Patterns - WPF Apps With The MVVM Design Pattern

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

Check if a temporary table exists and delete if it exists before creating a temporary table

I usually hit this error when I have already created the temp table; the code that checks the SQL statement for errors sees the "old" temp table in place and returns a miscount on the number of columns in later statements, as if the temp table was never dropped.

After changing the number of columns in a temp table after already creating a version with less columns, drop the table and THEN run your query.

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

Warning: Failed propType: Invalid prop `component` supplied to `Route`

Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.

module.exports = Component should become export default Component.

CommonJS uses module.exports as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports, exoprts or exprots). There are no runtime or compile-time checks to tell you that you've messed up.

If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component then it will give you a compile error to let you know.

In your case, you can simplify the Speaker component.

import React from 'react';

export default React.createClass({
  render() {
    return (
      <h1>Speaker</h1>
    )
  }
});

Angular expression if array contains

You can accomplish this with a slightly different syntax:

ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"

Plnkr

XAMPP Apache Webserver localhost not working on MAC OS

I had to disable OSX's built-in Apache server (XAMPP support thread):

sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

This allowed XAMPP to start on 80, while POW runs on 20559.

What had failed: I reconfigured /etc/apache2/httpd.conf to listen on an alternate port and rebooted OSX. No luck.

How to create a trie in Python

There's no "should"; it's up to you. Various implementations will have different performance characteristics, take various amounts of time to implement, understand, and get right. This is typical for software development as a whole, in my opinion.

I would probably first try having a global list of all trie nodes so far created, and representing the child-pointers in each node as a list of indices into the global list. Having a dictionary just to represent the child linking feels too heavy-weight, to me.

android: stretch image in imageview to fit screen

just change your ImageView height and width to wrap_content and use

exampleImage.setScaleType(ImageView.ScaleType.FIT_XY);

in your code.

FirstOrDefault returns NullReferenceException if no match is found

Simply use the question mark trick for null checks:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

How to fix curl: (60) SSL certificate: Invalid certificate chain

After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

When I initiate a brew update, I was getting the following error:

fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

git config --global http.sslVerify false

I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

I tried rvm osx-ssl-certs update all which stated Already are up to date.

In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

How do I restore a dump file from mysqldump?

One-liner command to restore the generated SQL from mysqldump

mysql -u <username> -p<password> -e "source <path to sql file>;"

How to reload/refresh jQuery dataTable?

If you use the url attribute, just do

table.ajax.reload()

Hopes it helps someone

HTML: How to make a submit button with text + image in it?

I have found a very easy solution! If you have a form and you want to have a custom submit button you can use some code like this:

<button type="submit">
    <img src="login.png" onmouseover="this.src='login2.png';" onmouseout="this.src='login.png';" />
</button>

Or just direct it to a link of a page.

How to use type: "POST" in jsonp ajax call

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

Find a line in a file and remove it

Try this:

public static void main(String[] args) throws IOException {

    File file = new File("file.csv");

    CSVReader csvFileReader = new CSVReader(new FileReader(file));

    List<String[]> list = csvFileReader.readAll();

    for (int i = 0; i < list.size(); i++) {
        String[] filter = list.get(i);
        if (filter[0].equalsIgnoreCase("bbb")) {
            list.remove(i);
        }
    }
    csvFileReader.close();
    CSVWriter csvOutput = new CSVWriter(new FileWriter(file));

    csvOutput.writeAll(list);
    csvOutput.flush();

    csvOutput.close();
}

How to convert Blob to String and String to Blob in java

To convert Blob to String in Java:

byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String

How to use Servlets and Ajax?

I will show you a whole example of servlet & how do ajax call.

Here, we are going to create the simple example to create the login form using servlet.

index.html

<form>  
   Name:<input type="text" name="username"/><br/><br/>  
   Password:<input type="password" name="userpass"/><br/><br/>  
   <input type="button" value="login"/>  
</form>  

Here is ajax Sample

       $.ajax
        ({
            type: "POST",           
            data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
            url: url,
        success:function(content)
        {
                $('#center').html(content);           
            }           
        });

LoginServlet Servlet Code :-

    package abc.servlet;

import java.io.File;


public class AuthenticationServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {   
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try{
        HttpSession session = request.getSession();
        String username = request.getParameter("name");
        String password = request.getParameter("pass");

                /// Your Code
out.println("sucess / failer")
        } catch (Exception ex) {
            // System.err.println("Initial SessionFactory creation failed.");
            ex.printStackTrace();
            System.exit(0);
        } 
    }
}

No module named 'pymysql'

Use:

import pymysql

Not:

import PyMySQL

That works for me.

How to trim a list in Python

>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]

How to POST form data with Spring RestTemplate?

Your url String needs variable markers for the map you pass to work, like:

String url = "https://app.example.com/hr/email?{email}";

Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

String url = "https://app.example.com/hr/[email protected]";

See also https://stackoverflow.com/a/47045624/1357094

Appending values to dictionary in Python

Just use append:

list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

What's the whole point of "localhost", hosts and ports at all?

I heard a good description (parable) which illustrates ports as different delivery points for a large building, e.g. Post office for letters and small parcels, Goods In for large deliveries / pallets, Doors for people.

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

Print to standard printer from Python?

I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint.

Even though gsprint is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.

I convert the web page to PDF using Puppeteer, Chrome's headless browser. But you need to pass in the session cookie to maintain credentials.

cmd line rename file with date and time

I tried to do the same:

<fileName>.<ext> --> <fileName>_<date>_<time>.<ext> 

I found that :

rename 's/(\w+)(\.\w+)/$1'$(date +"%Y%m%d_%H%M%S)'$2/' *

Want to show/hide div based on dropdown box selection

Wrap the code within $(document).ready(function(){...........}); handler , also remove the ; after if

$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
        $("#business").show();
      }
      else
      {
        $("#business").hide();
      }
    });
});

Fiddle Demo

Set database timeout in Entity Framework

I just ran in to this problem and resolved it by updating my application configuration file. For the connection in question, specify "Connection Timeout=60" (I am using entity framework version 5.0.0.0)

ConnectionTimeout Setting

How to concatenate string variables in Bash

There's one particular case where you should take care:

user=daniel
cat > output.file << EOF
"$user"san
EOF

Will output "daniel"san, and not danielsan, as you might have wanted. In this case you should do instead:

user=daniel
cat > output.file << EOF
${user}san
EOF

.NET console application as Windows service

Firstly I embed the console application solution into the windows service solution and reference it.

Then I make the console application Program class public

/// <summary>
/// Hybrid service/console application
/// </summary>
public class Program
{
}

I then create two functions within the console application

    /// <summary>
    /// Used to start as a service
    /// </summary>
    public void Start()
    {
        Main();
    }

    /// <summary>
    /// Used to stop the service
    /// </summary>
    public void Stop()
    {
       if (Application.MessageLoop)
            Application.Exit();   //windows app
        else
            Environment.Exit(1);  //console app
    }

Then within the windows service itself I instantiate the Program and call the Start and Stop functions added within the OnStart and OnStop. See below

class WinService : ServiceBase
{
    readonly Program _application = new Program();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] servicesToRun = { new WinService() };
        Run(servicesToRun);
    }

    /// <summary>
    /// Set things in motion so your service can do its work.
    /// </summary>
    protected override void OnStart(string[] args)
    {
        Thread thread = new Thread(() => _application.Start());
        thread.Start();
    }

    /// <summary>
    /// Stop this service.
    /// </summary>
    protected override void OnStop()
    {
        Thread thread = new Thread(() => _application.Stop());
        thread.Start();
    }
}

This approach can also be used for a windows application / windows service hybrid

What is the right way to debug in iPython notebook?

Your return function is in line of def function(main function), you must give one tab to it. And Use

%%debug 

instead of

%debug 

to debug the whole cell not only line. Hope, maybe this will help you.

Text size of android design TabLayout tabs

TabLayout  tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);

private void changeTabsFont() {
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
    ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(font);
                ((TextView) tabViewChild).setTextSize(15);

            }
        }
    }
}

This code is works for me using tablayout. It will change size of fonts and also change font style.

This will also help you guys please check this link

https://stackoverflow.com/a/43156384/5973946

This code works for Tablayout change text color,type face (font style) and also text size.

Install windows service without InstallUtil.exe

You can still use installutil without visual studio, it is included with the .net framework

On your server, open a command prompt as administrator then:

CD C:\Windows\Microsoft.NET\Framework\v4.0.version (insert your version)

installutil "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)

To uninstall:

installutil /u "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)

Excel: the Incredible Shrinking and Expanding Controls

I've had this issue a few times and to resolve I did the following:

  1. Search through my C:\ drive for any file with the extension '.exd'
  2. Delete those files (it is okay to do so)
  3. Implement code that re-sizes the ActiveX objects each time the sheet is opened

I found this issue was caused everything we plugged the laptop into a projector and saved the file. Then everytime the issue came up I went just repeated steps 1. and 2. and my ActiveX objects were behaving again

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

Find Nth occurrence of a character in a string

Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.

Here's the string match version:

public static int IndexOfNth(this string source, string matchString, 
                             int charInstance, 
                             StringComparison stringComparison = StringComparison.CurrentCulture)
{
    if (string.IsNullOrEmpty(source))
        return -1;

    int lastPos = 0;
    int count = 0;

    while (count < charInstance )
    {
        var len = source.Length - lastPos;
        lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
        if (lastPos == -1)
            break;

        count++;
        if (count == charInstance)
            return lastPos;

        lastPos += matchString.Length;
    }
    return -1;
}

and the char match version:

public static int IndexOfNth(string source, char matchChar, int charInstance)        
{
    if (string.IsNullOrEmpty(source))
        return -1;

    if (charInstance < 1)
        return -1;

    int count = 0;
    for (int i = 0; i < source.Length; i++)
    {
        if (source[i] == matchChar)
        {
            count++;
            if (count == charInstance)                 
                return i;                 
        }
    }
    return -1;
}

I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.

Convert regular Python string to raw string

For Python 3, the way to do this that doesn't add double backslashes and simply preserves \n, \t, etc. is:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Which gives a value that can be written as CSV:

hello\nbobby\nsally\n

There doesn't seem to be a solution for other special characters, however, that may get a single \ before them. It's a bummer. Solving that would be complex.

For example, to serialize a pandas.Series containing a list of strings with special characters in to a textfile in the format BERT expects with a CR between each sentence and a blank line between each document:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

This outputs (for the Github CodeSearchNet docstrings for all languages tokenized into sentences):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

What's the easiest way to escape HTML in Python?

cgi.escape should be good to escape HTML in the limited sense of escaping the HTML tags and character entities.

But you might have to also consider encoding issues: if the HTML you want to quote has non-ASCII characters in a particular encoding, then you would also have to take care that you represent those sensibly when quoting. Perhaps you could convert them to entities. Otherwise you should ensure that the correct encoding translations are done between the "source" HTML and the page it's embedded in, to avoid corrupting the non-ASCII characters.

Static Initialization Blocks

Here's an example:

  private static final HashMap<String, String> MAP = new HashMap<String, String>();
  static {
    MAP.put("banana", "honey");
    MAP.put("peanut butter", "jelly");
    MAP.put("rice", "beans");
  }

The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.

It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

PHP Excel Header

Try this

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

Trigger to fire only if a condition is met in SQL Server

Given that a WHERE clause did not work, maybe this will:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON

      If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
      Begin
          Return
      End

      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      Attribute,
      ParameterValue,
      ParameterDescription,
      ChangeDate
    FROM Inserted AS I
END

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Try killing port 8600 with this command:

fuser -k 8600/tcp

That fixed it for me.

What is the best place for storing uploaded images, SQL database or disk file system?

If they are small files that will not need to be edited then option B is not a bad option. I prefer this to writing logic to store files and deal with crazy directory structure issues. Having a lot of files in one directory is bad. emkay?

If the files are large or require constant editing, especially from programs like office, then option A is your best bet.

For most cases, it's a matter of preference, but if you go option A, just make re the directories don't have too many files in them. If you choose option B, then make the table with the BLOBed data be in it's own database and/or file group. This will help with maintenance, especially backups/restores. Your regular data is probably fairly small, while your image data will be huge over time.

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

CSV parsing in Java - working example..?

Writing your own parser is fun, but likely you should have a look at Open CSV. It provides numerous ways of accessing the CSV and also allows to generate CSV. And it does handle escapes properly. As mentioned in another post, there is also a CSV-parsing lib in the Apache Commons, but that one isn't released yet.

Using current time in UTC as default value in PostgreSQL

Still another solution:

timezone('utc', now())

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to create a directive with a dynamic template in AngularJS?

If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

Retrieve list of tasks in a queue in Celery

if you are using rabbitMQ, use this in terminal:

sudo rabbitmqctl list_queues

it will print list of queues with number of pending tasks. for example:

Listing queues ...
0b27d8c59fba4974893ec22d478a7093    0
0e0a2da9828a48bc86fe993b210d984f    0
[email protected] 0
11926b79e30a4f0a9d95df61b6f402f7    0
15c036ad25884b82839495fb29bd6395    1
[email protected]    0
celery  166
celeryev.795ec5bb-a919-46a8-80c6-5d91d2fcf2aa   0
celeryev.faa4da32-a225-4f6c-be3b-d8814856d1b6   0

the number in right column is number of tasks in the queue. in above, celery queue has 166 pending task.

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

PHPMailer: SMTP Error: Could not connect to SMTP host

I had the same problem and it was because PHPMailer realized the server supported STARTTLS so it tried to automatically upgrade the connection to an encrypted connection. My mail server is on the same subnet as the web server within my network which is all behind our domain firewalls so I'm not too worried about using encryption (plus the generated emails don't contain sensitive data anyway).

So what I went ahead and did was change the SMTPAutoTLS to false in the class.phpmailer.php file.

/**
 * Whether to enable TLS encryption automatically if a server supports it,
 * even if `SMTPSecure` is not set to 'tls'.
 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
 * @var boolean
 */
public $SMTPAutoTLS = false;

Is it possible to insert multiple rows at a time in an SQLite database?

fearless_fool has a great answer for older versions. I just wanted to add that you need to make sure you have all the columns listed. So if you have 3 columns, you need to make sure select acts on 3 columns.

Example: I have 3 columns but I only want to insert 2 columns worth of data. Assume I don't care about the first column because it's a standard integer id. I could do the following...

INSERT INTO 'tablename'
      SELECT NULL AS 'column1', 'data1' AS 'column2', 'data2' AS 'column3'
UNION SELECT NULL, 'data3', 'data4'
UNION SELECT NULL, 'data5', 'data6'
UNION SELECT NULL, 'data7', 'data8'

Note: Remember the "select ... union" statement will lose the ordering. (From AG1)

How to format code in Xcode?

  1. Select the block of code that you want indented.

  2. Right-click (or, on Mac, Ctrl-click).

  3. Structure → Re-indent

How to get N rows starting from row M from sorted table in T-SQL

I read all of the responses here and finally came up with a usable solution that is simple. The performance issues arise from the BETWEEN statement, not the generation of the row numbers themselves. So I used an algorithm to do dynamic paging by passing the page number and the number of records.

The passes are not start row and number of rows, but rather "rows per page (500)" and "page number (4)" which would be rows 1501 - 2000. These values can be replaced by stored procedure variables so you are not locked into using a specific paging amount.

select * from (
    select
        (((ROW_NUMBER() OVER(ORDER BY MyField) - 1) / 500) + 1) AS PageNum
        , *
    from MyTable
) as PagedTable
where PageNum = 4;

Is there a way to get a list of all current temporary tables in SQL Server?

If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)

If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.

You can trace the SQL being executed using SQL Profiler:

[These articles target SQL Server versions later than 2000, but much of the advice is the same.]

If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

Start script missing error when running npm start

I got this error because I wasn't in the right directory in terminal.

App with the scripts was in folder B. Folder B was in folder A. I open folder A in vscode and enter "npm run start" into the built in terminal and got the error. try "cd folder B", opening folder B in the ide, or organizing your stuff better than I did in the first place.

Combine or merge JSON on node.js without jQuery

I see that this thread is too old, but I put my answer here just in logging purposes.

In one of the comments above you mentioned that you wanted to use 'express' in your project which has 'connect' library in the dependency list. Actually 'connect.utils' library contains a 'merge' method that does the trick. So you can use the 3rd party implementation without adding any new 3rd party libraries.

How do I keep CSS floats in one line?

Add this line to your floated element selector

.floated {
    float: left;
    ...
    box-sizing: border-box;
}

It will prevent padding and borders to be added to width, so element always stay in row, even if you have eg. three elements with width of 33.33333%

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

How to change sa password in SQL Server 2008 express?

This may help you to reset your sa password for SQL 2008 and 2012

EXEC sp_password NULL, 'yourpassword', 'sa'

pandas: find percentile stats of a given column

You can use the pandas.DataFrame.quantile() function, as shown below.

import pandas as pd
import random

A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]

df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
#    field_A  field_B
# 0       90       72
# 1       63       84
# 2       11       74
# 3       61       66
# 4       78       80
# 5       67       75
# 6       89       47
# 7       12       22
# 8       43        5
# 9       30       64

df.field_A.mean()   # Same as df['field_A'].mean()
# 54.399999999999999

df.field_A.median() 
# 62.0

# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.

df.field_A.quantile(0.1) # 10th percentile
# 11.9

df.field_A.quantile(0.5) # same as median
# 62.0

df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001

'this' is undefined in JavaScript class methods

Use arrow function:

Request.prototype.start = () => {
    if( this.stay_open == true ) {
        this.open({msg: 'listen'});
    } else {

    }
};

How to append one DataTable to another DataTable

Merge takes a DataTable, Load requires an IDataReader - so depending on what your data layer gives you access to, use the required method. My understanding is that Load will internally call Merge, but not 100% sure about that.

If you have two DataTables, use Merge.

Using jQuery to test if an input has focus

Here’s a more robust answer than the currently accepted one:

jQuery.expr[':'].focus = function(elem) {
  return elem === document.activeElement && (elem.type || elem.href);
};

Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.

(Taken from this gist by Ben Alman.)

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

Because you set visibility either true or false. try that setVisible(0) to visible true . and setVisible(4) to visible false.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

Here is the best solution I've found so far. It works great and it's cross-browser (IE 8+).

ul {
    list-style: none;
    margin-left: 0;
    padding-left: 1.2em;
    text-indent: -1.2em;
}

li:before {
    content: "?";
    display: block;
    float: left;
    width: 1.2em;
    color: #ff0000;
}

The important thing is to have the character in a floating block with a fixed width so that the text remains aligned if it's too long to fit on a single line. 1.2em is the width you want for your character, change it for your needs.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

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

How can I get useful error messages in PHP?

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

Android splash screen image sizes to fit all devices

Based off this answer from Lucas Cerro I calculated the dimensions using the ratios in the Android docs, using the baseline in the answer. I hope this helps someone else coming to this post!

  • xxxlarge (xxxhdpi): 1280x1920 (4.0x)
  • xxlarge (xxhdpi): 960x1440 (3.0x)
  • xlarge (xhdpi): 640x960 (2.0x)
  • large (hdpi): 480x800 (1.5x)
  • medium (mdpi): 320x480 (1.0x baseline)
  • small (ldpi): 240x320 (0.75x) 

How to print React component on click of a button?

There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:

var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();

This expects this html to exist

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>

The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

<style type="text/css" media="print">
   .no-print { display: none; }
</style>

Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.

How to remove non-alphanumeric characters?

[\W_]+

 

$string = preg_replace("/[\W_]+/u", '', $string);

It select all not A-Z, a-z, 0-9 and delete it.

See example here: https://regexr.com/3h1rj

MySQL: What's the difference between float and double?

Doubles are just like floats, except for the fact that they are twice as large. This allows for a greater accuracy.

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle