Programs & Examples On #Namespace organisation

Deploy a project using Git push

git config --local receive.denyCurrentBranch updateInstead

Added in Git 2.3, this could be a good possibility: https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155

You set it on the server repository, and it also updates the working tree if it is clean.

There have been further improvements in 2.4 with the push-to-checkout hook and handling of unborn branches.

Sample usage:

git init server
cd server
touch a
git add .
git commit -m 0
git config --local receive.denyCurrentBranch updateInstead

cd ..
git clone server local
cd local
touch b
git add .
git commit -m 1
git push origin master:master

cd ../server
ls

Output:

a
b

This does have the following shortcomings mentioned on the GitHub announcement:

  • Your server will contain a .git directory containing the entire history of your project. You probably want to make extra sure that it cannot be served to users!
  • During deploys, it will be possible for users momentarily to encounter the site in an inconsistent state, with some files at the old version and others at the new version, or even half-written files. If this is a problem for your project, push-to-deploy is probably not for you.
  • If your project needs a "build" step, then you will have to set that up explicitly, perhaps via githooks.

But all of those points are out of the scope of Git and must be taken care of by external code. So in that sense, this, together with Git hooks, are the ultimate solution.

How to add a second x-axis in matplotlib

I'm taking a cue from the comments in @Dhara's answer, it sounds like you want to set a list of new_tick_locations by a function from the old x-axis to the new x-axis. The tick_function below takes in a numpy array of points, maps them to a new value and formats them:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

X = np.linspace(0,1,1000)
Y = np.cos(X*20)

ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")

new_tick_locations = np.array([.2, .5, .9])

def tick_function(X):
    V = 1/(1+X)
    return ["%.3f" % z for z in V]

ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()

enter image description here

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

Checking password match while typing

Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times.

I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:

$(document).ready(function () {
   $("#txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example


Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:

$(document).ready(function () {
   $("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example

How do I request and receive user input in a .bat and use it to run a certain program?

I have improved batch file with yes or no prompt. If user enter any character except y and n , then it will again prompt user for valid input. It Works for me.

    @echo off

    :ConfirmBox 
        set /P c= Are you sure want to contine (y/n)?

    if /I "%c%" EQU "Y" (
    goto :FnYes 
    ) else if /I "%c%" EQU "N" ( 
    goto :FnNo
    ) else ( 
    goto :InValid 
    )


:FnYes
     echo You have entered Y
     goto :END

:FnNo
     echo You have entered N
     goto :END

:InValid
     echo Invalid selection. Enter Y or N
     goto :ConfirmBox

:END
    pause
    exit  

/I in if condition will validate both lowercase and uppercase characters.

How to get 0-padded binary representation of an integer in java?

Here a new answer for an old post.

To pad a binary value with leading zeros to a specific length, try this:

Integer.toBinaryString( (1 << len) | val ).substring( 1 )

If len = 4 and val = 1,

Integer.toBinaryString( (1 << len) | val )

returns the string "10001", then

"10001".substring( 1 )

discards the very first character. So we obtain what we want:

"0001"

If val is likely to be negative, rather try:

Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )

How to implement a FSM - Finite State Machine in Java

Consider the easy, lightweight Java library EasyFlow. From their docs:

With EasyFlow you can:

  • implement complex logic but keep your code simple and clean
  • handle asynchronous calls with ease and elegance
  • avoid concurrency by using event-driven programming approach
  • avoid StackOverflow error by avoiding recursion
  • simplify design, programming and testing of complex java applications

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box

Scroll to a div using jquery

OK guys, this is a small solution, but it works fine.

suppose the following code:

<div id='the_div_holder' style='height: 400px; overflow-y: scroll'>
  <div class='post'>1st post</div>
  <div class='post'>2nd post</div>
  <div class='post'>3rd post</div>
</div>

you want when a new post is added to 'the_div_holder' then it scrolls its inner content (the div's .post) to the last one like a chat. So, do the following whenever a new .post is added to the main div holder:

var scroll = function(div) {
    var totalHeight = 0;
    div.find('.post').each(function(){
       totalHeight += $(this).outerHeight();
    });
    div.scrollTop(totalHeight);
  }
  // call it:
  scroll($('#the_div_holder'));

HTML - Display image after selecting filename

This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

Which one is the best PDF-API for PHP?

http://sourceforge.net/projects/html2ps/, is the best if you need the css and 3c compatibily.

if you can install software on your server, i suggest you to use http://wkhtmltopdf.org/.

There is also a drupal module using wkhtmltopdf :)

PHP take many resources to convert html in pdf, imho, php is not the right language to do that (if you expect a large numbers of coversion or large files to convert)

Docker - Ubuntu - bash: ping: command not found

Alternatively you can use a Docker image which already has ping installed, e.g. busybox:

docker run --rm busybox ping SERVER_NAME -c 2

How do I extract the contents of an rpm?

For those who do not have rpm2cpio, here is the ancient rpm2cpio.sh script that extracts the payload from a *.rpm package.

Reposted for posterity … and the next generation.

Invoke like this: ./rpm2cpio.sh .rpm | cpio -dimv

#!/bin/sh

pkg=$1
if [ "$pkg" = "" -o ! -e "$pkg" ]; then
    echo "no package supplied" 1>&2
    exit 1
fi

leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "sig il: $il dl: $dl"

sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "hdr il: $il dl: $dl"

hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
EXTRACTOR="dd if=$pkg ibs=$o skip=1"

COMPRESSION=`($EXTRACTOR |file -) 2>/dev/null`
if echo $COMPRESSION |grep -q gzip; then
        DECOMPRESSOR=gunzip
elif echo $COMPRESSION |grep -q bzip2; then
        DECOMPRESSOR=bunzip2
elif echo $COMPRESSION |grep -iq xz; then # xz and XZ safe
        DECOMPRESSOR=unxz
elif echo $COMPRESSION |grep -q cpio; then
        DECOMPRESSOR=cat
else
        # Most versions of file don't support LZMA, therefore we assume
        # anything not detected is LZMA
        DECOMPRESSOR=`which unlzma 2>/dev/null`
        case "$DECOMPRESSOR" in
            /* ) ;;
            *  ) DECOMPRESSOR=`which lzmash 2>/dev/null`
             case "$DECOMPRESSOR" in
                     /* ) DECOMPRESSOR="lzmash -d -c" ;;
                     *  ) DECOMPRESSOR=cat ;;
                 esac
                 ;;
        esac
fi

$EXTRACTOR 2>/dev/null | $DECOMPRESSOR

ImportError: No module named pip

Tested below for Linux: You can directly download pip from https://pypi.org/simple/pip/ untar and use directly with your latest python.

tar -xvf  pip-0.2.tar.gz
cd pip-0.2

Check for the contents.

anant$ ls
docs  pip.egg-info  pip-log.txt  pip.py  PKG-INFO  regen-docs  scripts  setup.cfg  setup.py  tests

Execute directly:

anant$ python pip.py --help
Usage: pip.py COMMAND [OPTIONS]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -E DIR, --environment=DIR
                        virtualenv environment to run pip in (either give the
                        interpreter or the environment base directory)
  -v, --verbose         Give more output
  -q, --quiet           Give less output
  --log=FILENAME        Log file where a complete (maximum verbosity) record
                        will be kept
  --proxy=PROXY         Specify a proxy in the form
                        user:[email protected]:port. Note that the
                        user:password@ is optional and required only if you
                        are behind an authenticated proxy.  If you provide
                        [email protected]:port then you will be prompted for a
                        password.
  --timeout=SECONDS     Set the socket timeout (default 15 seconds)

How to add a border to a widget in Flutter?

Here, as the Text widget does not have a property that allows us to define a border, we should wrap it with a widget that allows us to define a border. There are several solutions.
But the best solution is the use of BoxDecoration in the Container widget.

Why choose to use BoxDecoration ?
Because BoxDecoration offers more customization like the possibility to define :
First, the border and also define:

  • border Color
  • border width
  • border radius
  • shape
  • and more ...

An example :

   Container(
     child:Text(' Hello Word '),
     decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(
                color: Colors.red ,
                width: 2.0 ,
              ),
          borderRadius: BorderRadius.circular(15),
            ),
          ),

Output :

enter image description here

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Most answers already cover getContext() and getApplicationContext() but getBaseContext() is rarely explained.

The method getBaseContext() is only relevant when you have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using:

ContextWrapper wrapper = new ContextWrapper(context);

The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”. For example, if you have an activity called myActivity then can create a View with a different theme than myActivity:

ContextWrapper customTheme = new ContextWrapper(myActivity) {
  @Override
  public Resources.Theme getTheme() { 
    return someTheme;
  }
}
View myView = new MyView(customTheme);

ContextWrapper is really powerful because it lets you override most functions provided by Context including code to access resources (e.g. openFileInput(), getString()), interact with other components (e.g. sendBroadcast(), registerReceiver()), requests permissions (e.g. checkCallingOrSelfPermission()) and resolving file system locations (e.g. getFilesDir()). ContextWrapper is really useful to work around device/version specific problems or to apply one-off customizations to components such as Views that require a context.

The method getBaseContext() can be used to access the “base” Context that the ContextWrapper wraps around. You might need to access the “base” context if you need to, for example, check whether it’s a Service, Activity or Application:

public class CustomToast {
  public void makeText(Context context, int resId, int duration) {
    while (context instanceof ContextWrapper) {
      context = context.baseContext();
    }
    if (context instanceof Service)) {
      throw new RuntimeException("Cannot call this from a service");
    }
    ...
  }
}

Or if you need to call the “unwrapped” version of a method:

class MyCustomWrapper extends ContextWrapper {
  @Override
  public Drawable getWallpaper() {
    if (BuildInfo.DEBUG) {
      return mDebugBackground;
    } else {
      return getBaseContext().getWallpaper();
    }
  }
}

SQL How to replace values of select return?

Replace the value in select statement itself...

(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)

How do I use $scope.$watch and $scope.$apply in AngularJS?

There are $watchGroup and $watchCollection as well. Specifically, $watchGroup is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.

Here, the documentation link.

Use component from another module

The main rule here is that:

The selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.

So, try to export it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

What should I export?

Export declarable classes that components in other modules should be able to reference in their templates. These are your public classes. If you don't export a class, it stays private, visible only to other component declared in this module.

The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state(as Ward Bell said in https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2)

Angular creates transitive module for each of @NgModules.

This module collects directives that either imported from another module(if transitive module of imported module has exported directives) or declared in current module.

When angular compiles template that belongs to module X it is used those directives that had been collected in X.transitiveModule.directives.

compiledTemplate = new CompiledTemplate(
    false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);

https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251

enter image description here

This way according to the picture above

  • YComponent can't use ZComponent in its template because directives array of Transitive module Y doesn't contain ZComponent because YModule has not imported ZModule whose transitive module contains ZComponent in exportedDirectives array.

  • Within XComponent template we can use ZComponent because Transitive module X has directives array that contains ZComponent because XModule imports module (YModule) that exports module (ZModule) that exports directive ZComponent

  • Within AppComponent template we can't use XComponent because AppModule imports XModule but XModule doesn't exports XComponent.

See also

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

You can just do:

@some_var.class == Hash

or also something like:

@some_var.is_a?(Hash)

It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:

@some_var.is_a?(Object)  # => true

the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.

Refresh a page using PHP

You can do it with PHP:

header("Refresh:0");

It refreshes your current page, and if you need to redirect it to another page, use following:

header("Refresh:0; url=page2.php");

Import CSV to mysql table

Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.

You can then import it into a MySQL table by running:

load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
  enclosed by '"'
  lines terminated by '\n'
    (uniqName, uniqCity, uniqComments)

as read on: Import CSV file directly into MySQL

EDIT

For your case, you'll need to write an interpreter first, for finding the first row, and assigning them as column names.


EDIT-2

From MySQL docs on LOAD DATA syntax:

The IGNORE number LINES option can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip over an initial header line containing column names:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;

Therefore, you can use the following statement:

LOAD DATA LOCAL INFILE 'uniq.csv'
INTO TABLE tblUniq
FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uniqName, uniqCity, uniqComments)

'\r': command not found - .bashrc / .bash_profile

SUBLIME TEXT

With sublime you just go to

View - > Line Endings -> (select)Unix

Then save the file. Will fix this issue.

Easy as that!

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

How to put a text beside the image?

make the image float: left; and the text float: right;

Take a look at this fiddle I used a picture online but you can just swap it out for your picture.

How to Diff between local uncommitted changes and origin

Given that the remote repository has been cached via git fetch it should be possible to compare against these commits. Try the following:

$ git fetch origin
$ git diff origin/master

Python regular expressions return true/false

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

Check if two lists are equal

List<T> equality does not check them element-by-element. You can use LINQ's SequenceEqual method for that:

var a = ints1.SequenceEqual(ints2);

To ignore order, use SetEquals:

var a = new HashSet<int>(ints1).SetEquals(ints2);

This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:

var counts = ints1
    .GroupBy(v => v)
    .ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
    int c;
    if (counts.TryGetValue(n, out c)) {
        counts[n] = c-1;
    } else {
        ok = false;
        break;
    }
}
var res = ok && counts.Values.All(c => c == 0);

Finally, if you are fine with an O(N*LogN) solution, you can sort the two sequences, and compare them for equality using SequenceEqual.

Parse date string and change format

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>

How do you initialise a dynamic array in C++?

C++ has no specific feature to do that. However, if you use a std::vector instead of an array (as you probably should do) then you can specify a value to initialise the vector with.

std::vector <char> v( 100, 42 );

creates a vector of size 100 with all values initialised to 42.

Attach the Java Source Code

You need to attach java sources which comes with JDK(C:\Program Files\Java\jdk1.8.0_71\src.zip).

Steps(**Source: link):

  1. Select any Java project
  2. Expand Referenced libraries
  3. Select any JAR file, in our case rt.jar which is Java runtime
  4. Right click and go to properties
  5. Attach source code by browsing source path.

Change Input to Upper Case

I think the most easiest way to do is by using Bootstrap's class ".text-uppercase"

<input type="text" class="text-uppercase" />

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

convert date string to mysql datetime field

SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) ,  '-', SUBSTRING( json_date, 7, 2 ) ,  '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();

json_date ["05/11/2011"]

"A lambda expression with a statement body cannot be converted to an expression tree"

9 years too late to the party, but a different approach to your problem (that nobody has mentioned?):

The statement-body works fine with Func<> but won't work with Expression<Func<>>. IQueryable.Select wants an Expression<>, because they can be translated for Entity Framework - Func<> can not.

So you either use the AsEnumerable and start working with the data in memory (not recommended, if not really neccessary) or you keep working with the IQueryable<> which is recommended. There is something called linq query which makes some things easier:

IQueryable<Obj> result = from o in objects
                         let someLocalVar = o.someVar
                         select new Obj
                         {
                           Var1 = someLocalVar,
                           Var2 = o.var2
                         };

with let you can define a variable and use it in the select (or where,...) - and you keep working with the IQueryable until you really need to execute and get the objects.

Afterwards you can Obj[] myArray = result.ToArray()

How to pad a string with leading zeros in Python 3

I suggest this ugly method but it works:

length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)

I came here to find a lighter solution than this one!

How do I convert from a string to an integer in Visual Basic?

Convert.ToIntXX doesn't like being passed strings of decimals.

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

How can I String.Format a TimeSpan object with a custom format in .NET?

You can also go with:

Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:

You can also look at Strings.Format.

    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")

forEach is not a function error with JavaScript array

A more naive version, at least you're sure that it'll work on all devices, without conversion and ES6 :

const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}

https://jsfiddle.net/swb12kqn/5/

SQL selecting rows by most recent date with two unique columns

I see most of the developers use inline query without looking out it's impact on huge data.

in simple you can achieve this by:

select a.chargeId, a.chargeType, a.serviceMonth 
from invoice a
left outer join invoice b
on a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth 
where b.chargeId is null
order by a.serviceMonth desc

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

The official way to detect .NET 3.0 is described here

http://msdn.microsoft.com/en-us/library/aa480198.aspx

Flawed, because it requires the caller to have registry access permissions.

MSDN also mentions a technique for detecting .NET 3.5 by checking the User Agent string:

http://msdn.microsoft.com/en-us/library/bb909885.aspx

I think Microsoft should have done a better job than this.

How to recover a dropped stash in Git?

To get the list of stashes that are still in your repository, but not reachable any more:

git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP

If you gave a title to your stash, replace "WIP" in -grep=WIP at the end of the command with a part of your message, e.g. -grep=Tesselation.

The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

How to get a dependency tree for an artifact?

If your artifact is not a dependency of a given project, your best bet is to use a repository search engine. Many of them describes the dependencies of a given artifact.

How should I pass multiple parameters to an ASP.Net Web API GET?

I just had to implement a RESTfull api where I need to pass parameters. I did this by passing the parameters in the query string in the same style as described by Mark's first example "api/controller?start=date1&end=date2"

In the controller I used a tip from URL split in C#?

// uri: /api/courses
public IEnumerable<Course> Get()
{
    NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
    var system = nvc["System"];
    // BL comes here
    return _courses;
}

In my case I was calling the WebApi via Ajax looking like:

$.ajax({
        url: '/api/DbMetaData',
        type: 'GET',
        data: { system : 'My System',
                searchString: '123' },
        dataType: 'json',
        success: function (data) {
                  $.each(data, function (index, v) {
                  alert(index + ': ' + v.name);
                  });
         },
         statusCode: {
                  404: function () {
                       alert('Failed');
                       }
        }
   });

I hope this helps...

Extracting .jar file with command line

To extract the jar into specified folder use this command via command prompt

C:\Java> jar xf myFile.jar -C "C:\tempfolder"

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

I know it's for a long time ago but may be helpful to any other new comers,

I decided to pass user name,password and domain while requesting SSRS reports, so I created one class which implements IReportServerCredentials.

 public class ReportServerCredentials : IReportServerCredentials   
{
    #region  Class Members
        private string username;
        private string password;
        private string domain;
    #endregion

    #region Constructor
        public ReportServerCredentials()
        {}
        public ReportServerCredentials(string username)
        {
            this.Username = username;
        }
        public ReportServerCredentials(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }
        public ReportServerCredentials(string username, string password, string domain)
        {
            this.Username = username;
            this.Password = password;
            this.Domain = domain;
        }
    #endregion

    #region Properties
        public string Username
        {
            get { return this.username; }
            set { this.username = value; }
        }
        public string Password
        {
            get { return this.password; }
            set { this.password = value; }
        }
        public string Domain
        {
            get { return this.domain; }
            set { this.domain = value; }
        }
        public WindowsIdentity ImpersonationUser
        {
            get { return null; }
        }
        public ICredentials NetworkCredentials
        {
            get
            {
                return new NetworkCredential(Username, Password, Domain);
            }
        }
    #endregion

    bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
    {
        authCookie = null;
        userName = password = authority = null;
        return false;
    }
}

while calling SSRS Reprots, put following piece of code

 ReportViewer rptViewer = new ReportViewer();
 string RptUserName = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUser"]);
        string RptUserPassword = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserPassword"]);
        string RptUserDomain = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserDomain"]);
        string SSRSReportURL = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportURL"]);
        string SSRSReportFolder = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportFolder"]);

        IReportServerCredentials reportCredentials = new ReportServerCredentials(RptUserName, RptUserPassword, RptUserDomain);
        rptViewer.ServerReport.ReportServerCredentials = reportCredentials;
        rptViewer.ServerReport.ReportServerUrl = new Uri(SSRSReportURL);

SSRSReportUser,SSRSReportUserPassword,SSRSReportUserDomain,SSRSReportFolder are defined in web.config files.

Python: fastest way to create a list of n lists

So I did some speed comparisons to get the fastest way. List comprehensions are indeed very fast. The only way to get close is to avoid bytecode getting exectuded during construction of the list. My first attempt was the following method, which would appear to be faster in principle:

l = [[]]
for _ in range(n): l.extend(map(list,l))

(produces a list of length 2**n, of course) This construction is twice as slow as the list comprehension, according to timeit, for both short and long (a million) lists.

My second attempt was to use starmap to call the list constructor for me, There is one construction, which appears to run the list constructor at top speed, but still is slower, but only by a tiny amount:

from itertools import starmap
l = list(starmap(list,[()]*(1<<n)))

Interesting enough the execution time suggests that it is the final list call that is makes the starmap solution slow, since its execution time is almost exactly equal to the speed of:

l = list([] for _ in range(1<<n))

My third attempt came when I realized that list(()) also produces a list, so I tried the apperently simple:

l = list(map(list, [()]*(1<<n)))

but this was slower than the starmap call.

Conclusion: for the speed maniacs: Do use the list comprehension. Only call functions, if you have to. Use builtins.

IOError: [Errno 32] Broken pipe: Python

The top answer (if e.errno == errno.EPIPE:) here didn't really work for me. I got:

AttributeError: 'BrokenPipeError' object has no attribute 'EPIPE'

However, this ought to work if all you care about is ignoring broken pipes on specific writes. I think it's safer than trapping SIGPIPE:

try:
    # writing, flushing, whatever goes here
except BrokenPipeError:
    exit( 0 )

You obviously have to make a decision as to whether your code is really, truly done if you hit the broken pipe, but for most purposes I think that's usually going to be true. (Don't forget to close file handles, etc.)

Embed HTML5 YouTube video without iframe?

Yes. Youtube API is the best resource for this.

There are 3 way to embed a video:

  • IFrame embeds using <iframe> tags
  • IFrame embeds using the IFrame Player API
  • AS3 (and AS2*) object embeds DEPRECATED

I think you are looking for the second one of them:

IFrame embeds using the IFrame Player API

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

<div id="ytplayer"></div>

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE'
    });
  }
</script>

Here are some instructions where you may take a look when starting using the API.


An embed example without using iframe is to use <object> tag:

<object width="640" height="360">
    <param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/
    <param name="allowFullScreen" value="true"/>
    <param name="allowscriptaccess" value="always"/>
    <embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

(replace yt-video-id with your video id)

JSFIDDLE

How can I find all the subsets of a set, with exactly n elements?

Here's a function that gives you all subsets of the integers [0..n], not just the subsets of a given length:

from itertools import combinations, chain

def allsubsets(n):
    return list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))

so e.g.

>>> allsubsets(3)
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

How to get coordinates of an svg element?

The element.getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.

See this question and answer.

While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.

Determine whether a key is present in a dictionary

My answer is "neither one".

I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.

This is usually done with enclosing the code in a try...except clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).

Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".

As a trivial example consider:

if 'name' in dct:
    value = dct['name'] * 3
else:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

vs

try:
    value = dct['name'] * 3
except KeyError:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).

Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict: is better for the reasons stated in the other answers.

If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).

How to combine two vectors into a data frame

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

MERGE INTO target
USING
(
    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    UNION ALL
    SELECT id, null some_value, 1 deleteMe
    FROM
    (
        SELECT id FROM target
        MINUS
        SELECT id FROM source
    )
) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
WHEN NOT MATCHED THEN
    INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;


--Results:
select * from target;

ID  SOME_VALUE   ISDELETED
1   new value 1  0
2   old value 2  1
3   new value 3  0

Angular2 - Focusing a textbox on component load

This answer is inspired by post Angular 2: Focus on newly added input element

Steps to set the focus on Html element in Angular2

  1. Import ViewChildren in your Component

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. Declare local template variable name for the html for which you want to set the focus

  3. Implement the function ngAfterViewInit() or other appropriate life cycle hooks
  4. Following is the piece of code which I used for setting the focus

    ngAfterViewInit() {vc.first.nativeElement.focus()}
    
  5. Add #input attribute to the DOM element you want to access.

_x000D_
_x000D_
///This is typescript_x000D_
import {Component, Input, Output, AfterContentInit, ContentChild,_x000D_
  AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';_x000D_
_x000D_
export class AppComponent implements AfterViewInit,AfterViewChecked { _x000D_
   @ViewChildren('input') vc;_x000D_
  _x000D_
   ngAfterViewInit() {            _x000D_
        this.vc.first.nativeElement.focus();_x000D_
    }_x000D_
  _x000D_
 }
_x000D_
<div>_x000D_
    <form role="form" class="form-horizontal ">        _x000D_
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />_x000D_
_x000D_
                </div>_x000D_
                <div class="col-md-2 col-sm-2">_x000D_
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">_x000D_
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>_x000D_
                    </select>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Visual Studio 2010 always thinks project is out of date, but nothing has changed

There are quite a few potential reasons and - as noted - you need to first diagnose them by setting MSBuild verbosity to 'Diagnostic'. Most of the time the stated reason would be self explanatory and you'd be able to act on it immediatelly, BUT occasionally MSBuild would erroneously claim that some files are modified and need to be copied.

If that is the case, you'd need to either disable NTFS tunneling or duplicate your output folder to a new location. Here it is in more words.

Change the default base url for axios

  1. Create .env.development, .env.production files if not exists and add there your API endpoint, for example: VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
  2. In main.js file, add this line after imports: axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

And that's it. Axios default base Url is replaced with build mode specific API endpoint. If you need specific baseURL for specific request, do it like this:

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

Finding and removing non ascii characters from an Oracle Varchar2

Answer given by Francisco Hayoz is the best. Don't use pl/sql functions if sql can do it for you.

Here is the simple test in Oracle 11.2.03

select s
     , regexp_replace(s,'[^'||chr(1)||'-'||chr(127)||']','') "rep ^1-127"
     , dump(regexp_replace(s,'['||chr(127)||'-'||chr(225)||']','')) "rep 127-255"
from (
select listagg(c, '') within group (order by c) s
  from (select 127+level l,chr(127+level) c from dual connect by level < 129))

And "rep 127-255" is

Typ=1 Len=30: 226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255

i.e for some reason this version of Oracle does not replace char(226) and above. Using '['||chr(127)||'-'||chr(225)||']' gives the desired result. If you need to replace other characters just add them to the regex above or use nested replace|regexp_replace if the replacement is different then '' (null string).

How to convert a char array back to a string?

package naresh.java;

public class TestDoubleString {

    public static void main(String args[]){
        String str="abbcccddef";    
        char charArray[]=str.toCharArray();
        int len=charArray.length;

        for(int i=0;i<len;i++){
            //if i th one and i+1 th character are same then update the charArray
            try{
                if(charArray[i]==charArray[i+1]){
                    charArray[i]='0';                   
                }}
                catch(Exception e){
                    System.out.println("Exception");
                }
        }//finally printing final character string
        for(int k=0;k<charArray.length;k++){
            if(charArray[k]!='0'){
                System.out.println(charArray[k]);
            }       }
    }
}

pull out p-values and r-squared from a linear regression

r-squared: You can return the r-squared value directly from the summary object summary(fit)$r.squared. See names(summary(fit)) for a list of all the items you can extract directly.

Model p-value: If you want to obtain the p-value of the overall regression model, this blog post outlines a function to return the p-value:

lmp <- function (modelobject) {
    if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
    f <- summary(modelobject)$fstatistic
    p <- pf(f[1],f[2],f[3],lower.tail=F)
    attributes(p) <- NULL
    return(p)
}

> lmp(fit)
[1] 1.622665e-05

In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same.

Coefficient p-values: If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:

summary(fit)$coefficients[,4]  

Alternatively, you can grab the p-value of coefficients from the anova(fit) object in a similar fashion to the summary object above.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

How to run function in AngularJS controller on document ready?

We can use the angular.element(document).ready() method to attach callbacks for when the document is ready. We can simply attach the callback in the controller like so:

angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    angular.element(document).ready(function () {
        document.getElementById('msg').innerHTML = 'Hello';
    });
}]);

http://jsfiddle.net/jgentes/stwyvq38/1/

Node.js getaddrinfo ENOTFOUND

I fixed this error with this

$ npm info express --verbose
# Error message: npm info retry will retry, error on last attempt: Error: getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
$ nslookup registry.npmjs.org
Server:     8.8.8.8
Address:    8.8.8.8#53

Non-authoritative answer:
registry.npmjs.org  canonical name = a.sni.fastly.net.
a.sni.fastly.net    canonical name = prod.a.sni.global.fastlylb.net.
Name:   prod.a.sni.global.fastlylb.net
Address: 151.101.32.162
$ sudo vim /etc/hosts 
# Add "151.101.32.162 registry.npmjs.org` to hosts file
$ npm info express --verbose
# Works now!

Original source: https://github.com/npm/npm/issues/6686

UICollectionView auto scroll to cell at IndexPath

I've found that scrolling in viewWillAppear may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.

I've also found that scrolling in viewDidAppear will cause a momentary flash of the unscrolled view to be visible.

And, if you scroll every time through viewDidLayoutSubviews, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.

Here's what I found works reliably:

Objective C :

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // If we haven't done the initial scroll, do it once.
    if (!self.initialScrollDone) {
        self.initialScrollDone = YES;

        [self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
                                    atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
    }
}

Swift :

 override func viewWillLayoutSubviews() {

    super.viewWillLayoutSubviews()

      if (!self.initialScrollDone) {

         self.initialScrollDone = true
         self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)
    }

}

How to know/change current directory in Python shell?

The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

How to update and order by using ms sql

UPDATE messages SET 
 status=10 
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);

How do I send an HTML Form in an Email .. not just MAILTO

You are making sense, but you seem to misunderstand the concept of sending emails.

HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.

Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).

Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.

A simple example code:

form.html:

<form method="post" action="email.php">
    <input type="text" name="subject" /><br />
    <textarea name="message"></textarea>
</form>

email.php:

<?php
    mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>

Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).

How to extract the first two characters of a string in shell scripting?

Quite late indeed but here it is

sed 's/.//3g'

Or

awk NF=1 FPAT=..

Or

perl -pe '$_=unpack a2'

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

Understanding unique keys for array children in React.js

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

This will sove the problem.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:

 TimeSpan ts = TimeSpan.FromSeconds(80);

You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.

Is there a function in python to split a word into a list?

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
}
.headerEnd{
    margin-left: auto;
}

json_decode returns NULL after webservice call

I just put this

$result = mb_convert_encoding($result,'UTF-8','UTF-8'); 
    $result = json_decode($result);

and it's working

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

What is the purpose of willSet and didSet in Swift?

One thing where didSet is really handy is when you use outlets to add additional configuration.

@IBOutlet weak var loginOrSignupButton: UIButton! {
  didSet {
        let title = NSLocalizedString("signup_required_button")
        loginOrSignupButton.setTitle(title, for: .normal)
        loginOrSignupButton.setTitle(title, for: .highlighted)
  }

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

What is a Sticky Broadcast?

sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

What does OpenCV's cvWaitKey( ) function do?

Note for anybody who may have had problems with the cvWaitKey( ) function. If you are finding that cvWaitKey(x) is not waiting at all, make sure you actually have a window open (i.e. cvNamedWindow(...)). Put the cvNamedWindow(...) declaration BEFORE any cvWaitKey() function calls.

How do I test if a recordSet is empty? isNull?

A simple way is to write it:

Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
   msgbox "There is no records" 
End if

Database design for a survey

You may choose to store the whole form as a JSON string.

Not sure about your requirement, but this approach would work in some circumstances.

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

There is the beforeShowDay option, which takes a function to be called for each date, returning true if the date is allowed or false if it is not. From the docs:


beforeShowDay

The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable and 1 equal to a CSS class name(s) or '' for the default presentation. It is called for each day in the datepicker before is it displayed.

Display some national holidays in the datepicker.

$(".selector").datepicker({ beforeShowDay: nationalDays})   

natDays = [
  [1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'],
  [4, 27, 'za'], [5, 25, 'ar'], [6, 6, 'se'],
  [7, 4, 'us'], [8, 17, 'id'], [9, 7, 'br'],
  [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']
];

function nationalDays(date) {
    for (i = 0; i < natDays.length; i++) {
      if (date.getMonth() == natDays[i][0] - 1
          && date.getDate() == natDays[i][1]) {
        return [false, natDays[i][2] + '_day'];
      }
    }
  return [true, ''];
}

One built in function exists, called noWeekends, that prevents the selection of weekend days.

$(".selector").datepicker({ beforeShowDay: $.datepicker.noWeekends })

To combine the two, you could do something like (assuming the nationalDays function from above):

$(".selector").datepicker({ beforeShowDay: noWeekendsOrHolidays})   

function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
    if (noWeekend[0]) {
        return nationalDays(date);
    } else {
        return noWeekend;
    }
}

Update: Note that as of jQuery UI 1.8.19, the beforeShowDay option also accepts an optional third paremeter, a popup tooltip

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

Password Protect a SQLite DB. Is it possible?

If you use FluentNHibernate you can use following configuration code:

private ISessionFactory createSessionFactory()
{
    return Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
            .ExposeConfiguration(this.buildSchema)
            .BuildSessionFactory();    
}

private void buildSchema(Configuration config)
{
        if (filename_not_exists == true)
        {
            new SchemaExport(config).Create(false, true);
        }
}    

Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

POST request with JSON body

<?php
// Example API call
$data = array(array (
    "REGION" => "MUMBAI",
    "LOCATION" => "NA",
    "STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data); 
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',       
    'Content-Length: ' . strlen($data_string) ,
    'API-TOKEN-KEY:'.$authToken ));   // API-TOKEN-KEY is keyword so change according to ur key word. like authorization 
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
    die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

Empty website template creates an ASP.NET website that includes a Web.config file but no other files. Means you have not any default page to show on browse or run.

This error message simply means that you did not setup and configure the default document properly on your IIS.

Once this is configured, the error message will go away.

Javascript - validation, numbers only

The simplest solution.

Thanks to my partner that gave me this answer.

You can set an onkeypress event on the input textbox like this:

onkeypress="validate(event)"

and then use regular expressions like this:

function validate(evt){
     evt.value = evt.value.replace(/[^0-9]/g,"");
}

It will scan and remove any letter or sign different from number in the field.

Iterating through all nodes in XML file

To iterate through all elements

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

angularjs - ng-repeat: access key and value from JSON array object

try this..

<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>

How can I select from list of values in Oracle

You can do this:

create type number_tab is table of number;

select * from table (number_tab(1,2,3,4,5,6));

The column is given the name COLUMN_VALUE by Oracle, so this works too:

select column_value from table (number_tab(1,2,3,4,5,6));

Which MySQL data type to use for storing boolean values

After reading the answers here I decided to use bit(1) and yes, it is somehow better in space/time, BUT after a while I changed my mind and I will never use it again. It complicated my development a lot, when using prepared statements, libraries etc (php).

Since then, I always use tinyint(1), seems good enough.

Super-simple example of C# observer/observable with delegates

Applying the Observer Pattern with delegates and events in c# is named "Event Pattern" according to MSDN which is a slight variation.

In this Article you will find well structured examples of how to apply the pattern in c# both the classic way and using delegates and events.

Exploring the Observer Design Pattern

public class Stock
{

    //declare a delegate for the event
    public delegate void AskPriceChangedHandler(object sender,
          AskPriceChangedEventArgs e);
    //declare the event using the delegate
    public event AskPriceChangedHandler AskPriceChanged;

    //instance variable for ask price
    object _askPrice;

    //property for ask price
    public object AskPrice
    {

        set
        {
            //set the instance variable
            _askPrice = value;

            //fire the event
            OnAskPriceChanged();
        }

    }//AskPrice property

    //method to fire event delegate with proper name
    protected void OnAskPriceChanged()
    {

        AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice));

    }//AskPriceChanged

}//Stock class

//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs : EventArgs
{

    //instance variable to store the ask price
    private object _askPrice;

    //constructor that sets askprice
    public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; }

    //public property for the ask price
    public object AskPrice { get { return _askPrice; } }

}//AskPriceChangedEventArgs

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

In all these scenarios outerScopeVar is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined

Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):

1.

enter image description here

Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png'; and alert(outerScopeVar); meanwhile the event may not occur. i.e, funtion img.onload wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.

2.

2

Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0, but still it registers an asynchronous event it will be added to the last position of the Event Queue for execution, which makes the guaranteed delay.

3.

enter image description here This time ajax callback.

4.

enter image description here

Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.

5.

enter image description here

Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

For me the issue was in the php.ini file. The property mysql.default_socket was pointing to file in a non-existent directory. The property was pointing to /var/mysql/mysql.sock but in OSX, the file was located in /tmp/mysql.sock.

Once I updated the entry in php.ini and restarted the webserver, the issue was resolved.

Do HTTP POST methods send data as a QueryString?

GET will send the data as a querystring, but POST will not. Rather it will send it in the body of the request.

Set a border around a StackPanel.

What about this one :

<DockPanel Margin="8">
    <Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            <TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
            <TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
            <Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />            
        </StackPanel>
    </Border>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>

In c++ what does a tilde "~" before a function name signify?

It's a destructor. The function is guaranteed to be called when the object goes out of scope.

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

How do I work with dynamic multi-dimensional arrays in C?

malloc will do.

 int rows = 20;
 int cols = 20;
 int *array;

  array = malloc(rows * cols * sizeof(int));

Refer the below article for help:-

http://courses.cs.vt.edu/~cs2704/spring00/mcquain/Notes/4up/Managing2DArrays.pdf

Googlemaps API Key for Localhost

Typing 'my IP' in google search I got my public IP address and pasted it in IP address (the third option). It works for me.

How do I pass a datetime value as a URI parameter in asp.net mvc?

i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Replace invalid values with None in Pandas DataFrame

Using replace and assigning a new df:

import pandas as pd
df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
dfnew = df.replace('-', 0)
print(dfnew)


(venv) D:\assets>py teste2.py
   0
0  0
1  3
2  2
3  5
4  1
5 -5

How do you list all triggers in a MySQL database?

The command for listing all triggers is:

show triggers;

or you can access the INFORMATION_SCHEMA table directly by:

select trigger_schema, trigger_name, action_statement
from information_schema.triggers

How to create an HTTPS server in Node.js?

Update

Use Let's Encrypt via Greenlock.js

Original Post

I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:

Snippet:

var options = {
  // this is the private key only
  key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))

// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))

// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};

var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
  console.log("Listening on " + server.address().address + ":" + server.address().port);
});

var insecureServer = http.createServer();
server.listen(80, function () {
  console.log("Listening on " + server.address().address + ":" + server.address().port);
});

This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https module handle it and then use that to serve you connect / express app.

Also, if you use server.on('request', app) instead of passing the app when creating the server, it gives you the opportunity to pass the server instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).

How to simulate key presses or a click with JavaScript?

Focus might be what your looking for. With tabbing or clicking I think u mean giving the element the focus. Same code as Russ (Sorry i stole it :P) but firing an other event.

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.focus();

best way to get folder and file list in Javascript

Why to invent the wheel?

There is a very popular NPM package, that let you do things like that easy.

var recursive = require("recursive-readdir");

recursive("some/path", function (err, files) {
  // `files` is an array of file paths
  console.log(files);
});

Lear more:

How to turn on/off MySQL strict mode in localhost (xampp)?

on Debian 10 I start mysql from ./opt/lampp/xampp start

I do strace ./opt/lampp/sbin/mysqld and see that my.cnf is there:

stat("/opt/lampp/etc/my.cnf", {st_mode=S_IFREG|0644, st_size=5050, ...}) = 0
openat(AT_FDCWD, "/opt/lampp/etc/my.cnf", O_RDONLY|O_CLOEXEC) = 3

hence, I add sql_mode config to /opt/lampp/etc/my.cnf instead of /etc/mysql/my.cnf

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Delete a closed pull request from GitHub

5 step to do what you want if you made the pull request from a forked repository:

  1. reopen the pull request
  2. checkout to the branch which you made the pull request
  3. reset commit to the last master commit(that means remove all you new code)
  4. git push --force
  5. delete your forked repository which made the pull request

And everything is done, good luck!

R define dimensions of empty data frame

seq_along may help to find out how many rows in your data file and create a data.frame with the desired number of rows

    listdf <- data.frame(ID=seq_along(df),
                              var1=seq_along(df), var2=seq_along(df))

Insert data into a view (SQL Server)

Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.

HTTP response header content disposition for attachments

Try changing your Content Type (media type) to application/x-download and your Content-Disposition to: attachment;filename=" + fileName;

response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);

Generating sql insert into for Oracle

Oracle's free SQL Developer will do this:

http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html

You just find your table, right-click on it and choose Export Data->Insert

This will give you a file with your insert statements. You can also export the data in SQL Loader format as well.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

I realise this is very old, but it was among the first hits on Google when I was looking for a solution to something similar, so I'll post what I did here. My scenario is slightly different as I basically just wanted to fully explode a jar, along with all jars contained within it, so I wrote the following bash functions:

function explode {
    local target="$1"
    echo "Exploding $target."
    if [ -f "$target" ] ; then
        explodeFile "$target"
    elif [ -d "$target" ] ; then
        while [ "$(find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)")" != "" ] ; do
            find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)" -exec bash -c 'source "<file-where-this-function-is-stored>" ; explode "{}"' \;
        done
    else
        echo "Could not find $target."
    fi
}

function explodeFile {
    local target="$1"
    echo "Exploding file $target."
    mv "$target" "$target.tmp"
    unzip -q "$target.tmp" -d "$target"
    rm "$target.tmp"
}

Note the <file-where-this-function-is-stored> which is needed if you're storing this in a file that is not read for a non-interactive shell as I happened to be. If you're storing the functions in a file loaded on non-interactive shells (e.g., .bashrc I believe) you can drop the whole source statement. Hopefully this will help someone.

A little warning - explodeFile also deletes the ziped file, you can of course change that by commenting out the last line.

How to merge remote changes at GitHub?

See the 'non-fast forward' section of 'git push --help' for details.

You can perform "git pull", resolve potential conflicts, and "git push" the result. A "git pull" will create a merge commit C between commits A and B.

Alternatively, you can rebase your change between X and B on top of A, with "git pull --rebase", and push the result back. The rebase will create a new commit D that builds the change between X and B on top of A.

How to format an inline code in Confluence?

I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.

Creating Colored Monospace with Wiki Markup

As rendered by Confluence

How to get base URL in Web API controller?

  1. Add a reference to System.Web using System.Web;

  2. Get the host or any other component of the url you want string host = HttpContext.Current.Request.Url.Host;

Pass by Reference / Value in C++

My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.

Modifications made in a called function are not in scope of the calling function when passing by value.

Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.

Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

You can use any of the substring methods in a Swift String extension I wrote https://bit.ly/JString.

var string = "hello"
var sub = string.substringFrom(3) // or string[3...5]
println(sub)// "lo"

ImportError: No module named BeautifulSoup

On Ubuntu 14.04 I installed it from apt-get and it worked fine:

sudo apt-get install python-beautifulsoup

Then just do:

from BeautifulSoup import BeautifulSoup

How do I limit the number of results returned from grep?

Awk approach:

awk '/pattern/{print; count++; if (count==10) exit}' file

Create pandas Dataframe by appending one row at a time

Make it simple. By taking list as input which will be appended as row in data-frame:-

import pandas as pd  
res = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))  
for i in range(5):  
    res_list = list(map(int, input().split()))  
    res = res.append(pd.Series(res_list,index=['lib','qty1','qty2']), ignore_index=True)

PHP - how to create a newline character?

Strings between double quotes "" interpolate, meaning they convert escaped characters to printable characters.

Strings between single quotes '' are literal, meaning they are treated exactly as the characters are typed in.

You can have both on the same line:

echo '$clientid $lastname ' . "\r\n";
echo "$clientid $lastname \r\n";

outputs:

$clientid $lastname
1 John Doe

What is the point of the diamond operator (<>) in Java 7?

When you write List<String> list = new LinkedList();, compiler produces an "unchecked" warning. You may ignore it, but if you used to ignore these warnings you may also miss a warning that notifies you about a real type safety problem.

So, it's better to write a code that doesn't generate extra warnings, and diamond operator allows you to do it in convenient way without unnecessary repetition.

Android soft keyboard covers EditText field

I know this is old but none of the above solutions worked for me. After extensive debugging, I figured out the issue. The solution is setting the android:windowTranslucentStatus attribute to false in my styles.xml

svn cleanup: sqlite: database disk image is malformed

Marked answer might be the correct one, according to subversion cleanup. But the error is definitely a generic one, which led me here, this question page.

Our project has the dependency System.Data.SQLite and the error message was the same:

database disk image is malformed

In my case, I've executed following check script and the followings via SQLiteStudio 3.1.1.

pragma integrity_check

(I don't have any idea if these statistics would help, but I'm going to share them anyway...)

The DataBase file is being used on everyday usage for 1.5 year, via the connection journal mode on Memory, and was about 750 MB large. There were approximately 140K records per table and 6 tables was this large.

After the execution of Integrity Check script, 11 rows was returned after 30 minutes of execution time.

wrong # of entries in index sqlite_autoindex_MyTableName_1
wrong # of entries in index MyOtherTableAndOrIndexName_1
wrong # of entries in index sqlite_autoindex_MyOtherTableAndOrIndexName_2
etc...

All the results were about the indexes. Following-up the re-building each indexes, my problem was resolved.

reindex sqlite_autoindex_MyTableName_1;
reindex MyOtherTableAndOrIndexName_1;
reindex sqlite_autoindex_MyOtherTableAndOrIndexName_2;

After re-indexing, the integrity check resulted "ok".

I've got this error last year, and I was restored the DB from the backup, and then re-committed all the changes, which was a real nightmare...

How do I find the date a video (.AVI .MP4) was actually recorded?

For me the mtime (modification time) is also earlier than the create date in a lot of (most) cases since, as you say, any reorganisation modifies the create time. However, the mtime AFAIUI is an accurate reflection of when the file contents were actually changed so should be an accurate record of video capture date.

After discovering this metadata failure for movie files, I am going to be renaming my videos based on their mtime so I have this stored in a more robust way!

How to return values in javascript

You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.

Then you can pass in the array, object literal, or custom object into a method to disseminate the values.

Object example:

function myFunction(value1,value2,value3)
{
     var returnedObject = {};
     returnedObject["value1"] = value1;
     returnedObject["value2"] = value2;
     return returnedObject;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue.value1  && returnValue.value2)
{
//Do some stuff
}

Array example:

function myFunction(value1,value2,value3)
{
     var returnedArray = [];
     returnedArray.push(value1);
     returnedArray.push(value2);
     return returnedArray;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue[0]  && returnValue[1])
{
//Do some stuff
}

Custom Object:

function myFunction(value1,value2,value3)
{
     var valueHolder = new ValueHolder(value1, value2);
     return valueHolder;
}

var returnValue = myFunction("1",value2,value3);

// hypothetical method that you could build to create an easier to read conditional 
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}

I would avoid the array method because you would have to access the values via indices rather than named object properties.

Static Classes In Java

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

public class Outer {
   static class Nested_Demo {
      public void my_method() {
          System.out.println("This is my nested class");
      }
   }
public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

How to export JSON from MongoDB using Robomongo

You can use tojson to convert each record to JSON in a MongoDB shell script.

Run this script in RoboMongo:

var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
    print(tojson(cursor.next()))
}

This prints all results as a JSON-like array.

The result is not really JSON! Some types, such as dates and object IDs, are printed as JavaScript function calls, e.g., ISODate("2016-03-03T12:15:49.996Z").

Might not be very efficient for large result sets, but you can limit the query. Alternatively, you can use mongoexport.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.

This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.

Why is char[] preferred over String for passwords?

There is nothing that char array gives you vs String unless you clean it up manually after use, and I haven't seen anyone actually doing that. So to me the preference of char[] vs String is a bit exaggerated.

Take a look at the widely used Spring Security library here and ask yourself - are Spring Security guys incompetent or char[] passwords just don't make much sense. When some nasty hacker grabs memory dumps of your RAM be sure s/he'll get all the passwords even if you use sophisticated ways to hide them.

However, Java changes all the time, and some scary features like String Deduplication feature of Java 8 might intern String objects without your knowledge. But that's a different conversation.

mailto using javascript

I don't know if it helps, but using jQuery, to hide an email address, I did :

    $(function() {
        // planque l'adresse mail
        var mailSplitted 
            = ['mai', 'to:mye', 'mail@', 'addre', 'ss.fr'];

        var link = mailSplitted.join('');
        link = '<a href="' + link + '"</a>';
        $('mytag').wrap(link);
    });

I hope it helps.

How remove border around image in css?

I usually use this on the top of css file.

img {
   border: none;
}

Find value in an array

I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

If you mean something else, check the Ruby Array API

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To address the question more generally...

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):

synchronized static void foo() {
    ...
}

is the same as

static void foo() {
    synchronized(SomeClass.class) {
        ...
    }
}

and

synchronized void foo() {
    ...
}

is the same as

void foo() {
    synchronized(this) {
        ...
    }
}

You can use any object as the lock. If you want to lock subsets of static methods, you can

class SomeClass {
    private static final Object LOCK_1 = new Object() {};
    private static final Object LOCK_2 = new Object() {};
    static void foo() {
        synchronized(LOCK_1) {...}
    }
    static void fee() {
        synchronized(LOCK_1) {...}
    }
    static void fie() {
        synchronized(LOCK_2) {...}
    }
    static void fo() {
        synchronized(LOCK_2) {...}
    }
}

(for non-static methods, you would want to make the locks be non-static fields)

What is the difference between char * const and const char *?

The const modifier is applied to the term immediately to its left. The only exception to this is when there is nothing to its left, then it applies to what is immediately on its right.

These are all equivalent ways of saying "constant pointer to a constant char":

  • const char * const
  • const char const *
  • char const * const
  • char const const *

Press enter in textbox to and execute button command

There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

Set textarea width to 100% in bootstrap modal

After testing those suggestions here, I draw the conclusion that we have to apply two things.

  1. Apply form-control class to your textarea element. This is among Bootstrap's built-in classes.

  2. Extend this class by adding the following property:

.form-control {
   max-width: 100%;
}

Hope this helps others who are looking for a solution to this issue.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

jQuery: value.attr is not a function

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object to use it.

    console.info("cat_id: ", $(value).attr('cat_id'));

or just use the DOM method directly

    console.info("cat_id: ", value.getAttribute('cat_id'));

How to remove the Flutter debug banner?

Here are 3 ways to do it

  • 1 : On your MaterialApp set debugShowCheckedModeBanner to false.

     MaterialApp(
       debugShowCheckedModeBanner: false
     )
    

    The slow banner will also automatically be removed on release build.

  • 2 : If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions. enter image description here

  • 3 : There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main. dart file. So I think these methods are effective:

    --> If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown.

enter image description here

For more info: How_to_remove_debug_banner_in_flutter_on_android_emulator

How to change CSS using jQuery?

You can do either:

$("h1").css("background-color", "yellow");

Or:

$("h1").css({backgroundColor: "yellow"});

Need to perform Wildcard (*,?, etc) search on a string using Regex

public class Wildcard
{
    private readonly string _pattern;

    public Wildcard(string pattern)
    {
        _pattern = pattern;
    }

    public static bool Match(string value, string pattern)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end);
    }

    public static bool Match(string value, string pattern, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end, toLowerTable);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end, char[] toLowerTable)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end);
    }

    public bool IsMatch(string str, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str, ref int start, ref int end)
    {
        if (_pattern.Length == 0) return false;
        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;
                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (str[si] == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && str[si] != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }

    public bool IsMatch(string str, ref int start, ref int end, char[] toLowerTable)
    {
        if (_pattern.Length == 0) return false;

        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;

                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    char c = toLowerTable[str[si]];
                    if (c == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && c != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    continue;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }
}

Use:

var ismatch2 = Wildcard.Match("xmlfsdfsd", "xml*");

WHERE vs HAVING

Why is it that you need to place columns you create yourself (for example "select 1 as number") after HAVING and not WHERE in MySQL?

WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates).

In general, you can reference aliases in neither of these clauses, but MySQL allows referencing SELECT level aliases in GROUP BY, ORDER BY and HAVING.

And are there any downsides instead of doing "WHERE 1" (writing the whole definition instead of a column name)

If your calculated expression does not contain any aggregates, putting it into the WHERE clause will most probably be more efficient.

How to use git merge --squash?

You want to merge with the squash option. That's if you want to do it one branch at a time.

git merge --squash feature1

If you want to merge all the branches at the same time as single commits, then first rebase interactively and squash each feature then octopus merge:

git checkout feature1
git rebase -i master

Squash into one commit then repeat for the other features.

git checkout master
git merge feature1 feature2 feature3 ...

That last merge is an "octopus merge" because it's merging a lot of branches at once.

Hope this helps

How to use jQuery with Angular?

Here is what worked for me - Angular 2 with webpack

I tried declaring $ as type any but whenever I tried to use any JQuery module I was getting (for example) $(..).datepicker() is not a function

Since I have Jquery included in my vendor.ts file I simply imported it into my component using

import * as $ from 'jquery';

I am able to use Jquery plugins (like bootstrap-datetimepicker) now

Execute the setInterval function without delay the first time

actually the quickest is to do

interval = setInterval(myFunction(),45000)

this will call myfunction, and then will do it agaian every 45 seconds which is different than doing

interval = setInterval(myfunction, 45000)

which won't call it, but schedule it only

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

How to print a dictionary line by line in Python?

# Declare and Initialize Map
map = {}

map ["New"] = 1
map ["to"] = 1
map ["Python"] = 5
map ["or"] = 2

# Print Statement
for i in map:
  print ("", i, ":", map[i])

#  New : 1
#  to : 1
#  Python : 5
#  or : 2

Cannot checkout, file is unmerged

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

git reset first_Name.txt
git checkout first_Name.txt

Why doesn't java.io.File have a close method?

A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

How to get a resource id with a known resource name?

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Is there a Google Voice API?

I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...

https://bitbucket.org/jitbit/sharpgooglevoice/wiki/Home

How to set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

FormsAuthentication.SignOut() does not log the user out

After lots of search finally this worked for me . I hope it helps.

public ActionResult LogOff()
{
    AuthenticationManager.SignOut();
    HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
    return RedirectToAction("Index", "Home");
}

<li class="page-scroll">@Html.ActionLink("Log off", "LogOff", "Account")</li>

Using Custom Domains With IIS Express

The up-voted answer is valid.. and this information helped me quite a bit. I know this topic has been discussed before but I wanted to add some additional input. People are saying that you must "manually edit" the application.config file in the Users IISExpress/Config directory. This was a big issue for me because I wanted to distribute the configuration via Source control to various developers.

What I found is that you can automate the updating of this file using the "C:\Program Files\IIS Express\appcmd.exe" program. It took a while to find out the control parameters but Ill share my findings here. Essentially you can make a .bat file that runs both the NETSH command and the APPCMD.EXE (and perhaps swap out a host file if you like) to make host header configuration easy with IIS Express.

Your install bat file would look something like this:

netsh http add urlacl url=http://yourcustomdomain.com:80/ user=everyone 

"C:\Program Files\IIS Express\appcmd.exe" set site "MyApp.Web" /+bindings.[protocol='http',bindingInformation='*:80:yourcustomdomain.com']

I also will make a "Uninstall" bat file that will clean up these bindings..(because often times Im just faking out DNS so that I can work on code that is host name sensitive)

netsh http delete urlacl url=http://yourcustomdomain.com:80/

"C:\Program Files\IIS Express\appcmd.exe" set site "MyApp.Web" /-bindings.[protocol='http',bindingInformation='*:80:yourcustomdomain.com']

I hope this information is helpful to someone.. It took me a bit to uncover.

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

How to convert characters to HTML entities using plain JavaScript

You can use:

function encodeHTML(str){
 var aStr = str.split(''),
     i = aStr.length,
     aRet = [];

   while (i--) {
    var iC = aStr[i].charCodeAt();
    if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
      aRet.push('&#'+iC+';');
    } else {
      aRet.push(aStr[i]);
    }
  }
 return aRet.reverse().join('');
}

This function HTMLEncodes everything that is not a-z/A-Z.

[Edit] A rather old answer. Let's add a simpler String extension to encode all extended characters:

String.prototype.encodeHTML = function () {
  return this.replace(/[\u0080-\u024F]/g, 
          function (v) {return '&#'+v.charCodeAt()+';';}
         );
}
// usage
log('Übergroße Äpfel mit Würmern'.encodeHTML());
//=> '&#220;bergro&#223;e &#196;pfel mit W&#252;rmern'

Rownum in postgresql

Postgresql > 8.4

SELECT 
    row_number() OVER (ORDER BY col1) AS i, 
    e.col1, 
    e.col2, 
    ... 
FROM ... 

sql query with multiple where statements

What is meta_key? Strip out all of the meta_value conditionals, reduce, and you end up with this:

SELECT
*
FROM
meta_data
WHERE
(
        (meta_key = 'lat')
)
AND
(
        (meta_key = 'long')
)
GROUP BY
item_id

Since meta_key can never simultaneously equal two different values, no results will be returned.


Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:

SELECT
*
FROM
meta_data
WHERE
(
    (meta_key = 'lat')
    AND
    (
        (meta_value >= '60.23457047672217')
        OR
        (meta_value <= '60.23457047672217')
    )
)
OR
(
    (meta_key = 'long')
    AND
    (
        (meta_value >= '24.879140853881836')
        OR
        (meta_value <= '24.879140853881836')
    )
)
GROUP BY
item_id

Note the OR between the top-level conditionals. This is because you want records which are lat or long, since no single record will ever be lat and long.

I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY clause, but that might be outside the context of this question entirely.

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

Disable future dates in jQuery UI Datepicker

$(function() { $("#datepicker").datepicker({  maxDate: '0'}); });

Java error - "invalid method declaration; return type required"

You forgot to declare double as a return type

public double diameter()
{
    double d = radius * 2;
    return d;
}

How do I wait until Task is finished in C#?

A clean example that answers the Title

string output = "Error";
Task task = Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(2000);
    output = "Complete";
});

task.Wait();
Console.WriteLine(output);

Regular expression for matching latitude/longitude coordinates?

I am using these ones (decimal format, with 6 decimal digits):

Latitude

^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$

Latitude Regular expression visualization

Longitude

^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$

Longitude Regular expression visualization


Here is a gist that tests both, reported here also, for ease of access. It's a Java TestNG test. You need Slf4j, Hamcrest and Lombok to run it:

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;

import java.math.RoundingMode;
import java.text.DecimalFormat;

import lombok.extern.slf4j.Slf4j;

import org.testng.annotations.Test;

@Slf4j
public class LatLongValidationTest {

    protected static final String LATITUDE_PATTERN="^(\\+|-)?(?:90(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\\.[0-9]{1,6})?))$";
    protected static final String LONGITUDE_PATTERN="^(\\+|-)?(?:180(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\\.[0-9]{1,6})?))$";

    @Test
    public void latitudeTest(){
        DecimalFormat df = new DecimalFormat("#.######");
        df.setRoundingMode(RoundingMode.UP);
        double step = 0.01;
        Double latitudeToTest = -90.0;

        while(latitudeToTest <= 90.0){
            boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
            log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
            assertThat(result, is(true));
            latitudeToTest += step;
        }

        latitudeToTest = -90.1;

        while(latitudeToTest >= -200.0){
            boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
            log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
            assertThat(result, is(false));
            latitudeToTest -= step;
        }

        latitudeToTest = 90.01;

        while(latitudeToTest <= 200.0){
            boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
        log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
            assertThat(result, is(false));
            latitudeToTest += step;
        }
    }

    @Test
    public void longitudeTest(){
        DecimalFormat df = new DecimalFormat("#.######");
        df.setRoundingMode(RoundingMode.UP);
        double step = 0.01;
        Double longitudeToTest = -180.0;

        while(longitudeToTest <= 180.0){
            boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
            log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
            assertThat(result, is(true));
            longitudeToTest += step;
        }

        longitudeToTest = -180.01;

        while(longitudeToTest >= -300.0){
            boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
            log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
            assertThat(result, is(false));
            longitudeToTest -= step;
        }

        longitudeToTest = 180.01;

        while(longitudeToTest <= 300.0){
            boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
            log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
            assertThat(result, is(false));
            longitudeToTest += step;
        }
    }
}

Use String.split() with multiple delimiters

I'd use Apache Commons:

import org.apache.commons.lang3.StringUtils;

private void getId(String pdfName){
    String[] tokens = StringUtils.split(pdfName, "-.");
}

It'll split on any of the specified separators, as opposed to StringUtils.splitByWholeSeparator(str, separator) which uses the complete string as a separator

How can I switch my signed in user in Visual Studio 2013?

I faced this issue Many time from different scenarios

one of them when I tryed Connecting to team foundation server for different Logged User

enter image description here

so the solution is easy Just Click Switch User

hope this help you

Preprocessing in scikit learn - single sample - Depreciation warning

I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.

array = []
array.append(temp[0])

Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.

What is tail recursion?

Using regular recursion, each recursive call pushes another entry onto the call stack. When the recursion is completed, the app then has to pop each entry off all the way back down.

With tail recursion, depending on language the compiler may be able to collapse the stack down to one entry, so you save stack space...A large recursive query can actually cause a stack overflow.

Basically Tail recursions are able to be optimized into iteration.

Can I pass an array as arguments to a method with variable arguments in Java?

Yes, a T... is only a syntactic sugar for a T[].

JLS 8.4.1 Format parameters

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.

Here's an example to illustrate:

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("\0", "[ %s ]");
    return String.format(format, args);
}
public static void main(String... args) {
    System.out.println(ezFormat("A", "B", "C"));
    // prints "[ A ][ B ][ C ]"
}

And yes, the above main method is valid, because again, String... is just String[]. Also, because arrays are covariant, a String[] is an Object[], so you can also call ezFormat(args) either way.

See also


Varargs gotchas #1: passing null

How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.

Consider this example:

static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!

Due to how varargs are resolved, the last statement invokes with objs = null, which of course would cause NullPointerException with objs.length. If you want to give one null argument to a varargs parameter, you can do either of the following:

count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"

Related questions

The following is a sample of some of the questions people have asked when dealing with varargs:


Vararg gotchas #2: adding extra arguments

As you've found out, the following doesn't "work":

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(myArgs, "Z"));
    // prints "[ [Ljava.lang.String;@13c5982 ][ Z ]"

Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[], the second being a String. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

Here are some useful helper methods:

static <T> T[] append(T[] arr, T lastElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    arr[N] = lastElement;
    return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    System.arraycopy(arr, 0, arr, 1, N);
    arr[0] = firstElement;
    return arr;
}

Now you can do the following:

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(append(myArgs, "Z")));
    // prints "[ A ][ B ][ C ][ Z ]"

    System.out.println(ezFormat(prepend(myArgs, "Z")));
    // prints "[ Z ][ A ][ B ][ C ]"

Varargs gotchas #3: passing an array of primitives

It doesn't "work":

    int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:

    Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

How to change css property using javascript

Just for the info, this can be done with CSS only with just minor HTML and CSS changes

HTML:

<div class="left">
    Hello
</div>
<div class="right">
    Hello2
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>

CSS:

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}
.right{
     float :right;
}
.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}
.left:hover ~ .center .left1 {
    display:block;
}

.right:hover ~ .center .right1 {
    display:block;
}

and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

How can I sharpen an image in OpenCV?

You can find a sample code about sharpening image using "unsharp mask" algorithm at OpenCV Documentation.

Changing values of sigma,threshold,amount will give different results.

// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowContrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);

How to wait for all threads to finish, using ExecutorService?

you should use executorService.shutdown() and executorService.awaitTermination method.

An example as follows :

public class ScheduledThreadPoolExample {

    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
        executorService.scheduleAtFixedRate(() -> System.out.println("process task."),
                0, 1, TimeUnit.SECONDS);

        TimeUnit.SECONDS.sleep(10);
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
    }

}

Singleton with Arguments in Java

"A singleton with parameters is not a singleton" statement is not completely correct. We need to analyze this from the application perspective rather than from the code perspective.

We build singleton class to create a single instance of an object in one application run. By having a constructor with parameter, you can build flexibility into your code to change some attributes of your singleton object every time you run you application. This is not a violation of Singleton pattern. It looks like a violation if you see this from code perspective.

Design Patterns are there to help us write flexible and extendable code, not to hinder us writing good code.

regex pattern to match the end of a string

Use following pattern:

/([^/]+)$

How can I pad an integer with zeros on the left?

int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.