Programs & Examples On #Datefield

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

django no such table:

You can try this!

python manage.py migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

How do I get the current date and current time only respectively in Django?

import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015

For the time

from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18

How do I filter query objects by date range in Django?

You can use django's filter with datetime.date objects:

import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
                                sampledate__lte=datetime.date(2011, 1, 31))

Age from birthdate in python

import datetime

def age(date_of_birth):
    if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
        return datetime.date.today().year - date_of_birth.year - 1
    else:
        return datetime.date.today().year - date_of_birth.year

In your case:

import datetime

# your model
def age(self):
    if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
        return datetime.date.today().year - self.birthdate.year - 1
    else:
        return datetime.date.today().year - self.birthdate.year

Django DateField default options

You could also use lambda. Useful if you're using django.utils.timezone.now

date = models.DateField(_("Date"), default=lambda: now().date())

How to convert / cast long to String?

Just do this:

String strLong = Long.toString(longNumber);

How to delete images from a private docker registry?

The current v2 registry now supports deleting via DELETE /v2/<name>/manifests/<reference>

See: https://github.com/docker/distribution/blob/master/docs/spec/api.md#deleting-an-image

Working usage: https://github.com/byrnedo/docker-reg-tool

Edit: The manifest <reference> above can be retrieved from requesting to

GET /v2/<name>/manifests/<tag>

and checking the Docker-Content-Digest header in the response.

Edit 2: You may have to run your registry with the following env set:

REGISTRY_STORAGE_DELETE_ENABLED="true"

Edit3: You may have to run garbage collection to free this disk space: https://docs.docker.com/registry/garbage-collection/

Display a decimal in scientific notation

def formatE_decimal(x, prec=2):
    """ Examples:
    >>> formatE_decimal('0.1613965',10)
    '1.6139650000E-01'
    >>> formatE_decimal('0.1613965',5)
    '1.61397E-01'
    >>> formatE_decimal('0.9995',2)
    '1.00E+00'
    """
    xx=decimal.Decimal(x) if type(x)==type("") else x 
    tup = xx.as_tuple()
    xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
    tup = xx.as_tuple()
    exp = xx.adjusted()
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in tup[1][1:prec+1])   
    if prec>0:
        return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
    elif prec==0:
        return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
    else:
        return None

Case Insensitive String comp in C

Simple solution:

int str_case_ins_cmp(const char* a, const char* b) {
  int rc;

  while (1) {
    rc = tolower((unsigned char)*a) - tolower((unsigned char)*b);
    if (rc || !*a) {
      break;
    }

    ++a;
    ++b;
  }

  return rc;
}

How to list all the files in a commit?

If you want to get list of changed files:

git diff-tree --no-commit-id --name-only -r <commit-ish>

If you want to get list of all files in a commit, you can use

git ls-tree --name-only -r <commit-ish>

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

Sending event when AngularJS finished loading

In the docs for angular.Module, there's an entry describing the run function:

Use this method to register work which should be performed when the injector is done loading all modules.

So if you have some module that is your app:

var app = angular.module('app', [/* module dependencies */]);

You can run stuff after the modules have loaded with:

app.run(function() {
  // Do post-load initialization stuff here
});

EDIT: Manual Initialization to the rescue

So it's been pointed out that the run doesn't get called when the DOM is ready and linked up. It gets called when the $injector for the module referenced by ng-app has loaded all its dependencies, which is separate from the DOM compilation step.

I took another look at manual initialization, and it seems that this should do the trick.

I've made a fiddle to illustrate.

The HTML is simple:

<html>
    <body>
        <test-directive>This is a test</test-directive>
    </body>
</html>

Note the lack of an ng-app. And I have a directive that will do some DOM manipulation, so we can make sure of the order and timing of things.

As usual, a module is created:

var app = angular.module('app', []);

And here's the directive:

app.directive('testDirective', function() {
    return {
        restrict: 'E',
        template: '<div class="test-directive"><h1><div ng-transclude></div></h1></div>',
        replace: true,
        transclude: true,
        compile: function() {
            console.log("Compiling test-directive");
            return {
                pre: function() { console.log("Prelink"); },
                post: function() { console.log("Postlink"); }
            };
        }
    };
});

We're going to replace the test-directive tag with a div of class test-directive, and wrap its contents in an h1.

I've added a compile function that returns both pre and post link functions so we can see when these things run.

Here's the rest of the code:

// The bootstrapping process

var body = document.getElementsByTagName('body')[0];

// Check that our directive hasn't been compiled

function howmany(classname) {
    return document.getElementsByClassName(classname).length;
}

Before we've done anything, there should be no elements with a class of test-directive in the DOM, and after we're done there should be 1.

console.log('before (should be 0):', howmany('test-directive'));

angular.element(document).ready(function() {
    // Bootstrap the body, which loades the specified modules
    // and compiled the DOM.
    angular.bootstrap(body, ['app']);

    // Our app is loaded and the DOM is compiled
    console.log('after (should be 1):', howmany('test-directive'));
});

It's pretty straightforward. When the document is ready, call angular.bootstrap with the root element of your app and an array of module names.

In fact, if you attach a run function to the app module, you'll see it gets run before any of the compiling takes place.

If you run the fiddle and watch the console, you'll see the following:

before (should be 0): 0 
Compiling test-directive 
Prelink
Postlink
after (should be 1): 1 <--- success!

get basic SQL Server table structure information

You could use these functions:

sp_help TableName
sp_helptext ProcedureName

How can I remove a button or make it invisible in Android?

To completely remove a button from its parent layout:

((ViewGroup)button.getParent()).removeView(button);

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

How to reset a select element with jQuery

In your case (and in most use cases I have seen), all you need is:

$("#baba").val("");

Demo.

Compare 2 arrays which returns difference

The short version can be like this:

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

result:

diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]

How do I add all new files to SVN

For reference, these are very similar questions.

These seem to work the best for me. They also work with spaces, and don't re-add ignored files. I didn't see them listed on any of the other answers I saw.

adding:

svn st | grep ^? | sed 's/?    //' | xargs svn add

removing:

svn st | grep ^! | sed 's/!    //' | xargs svn rm

Edit: It's important to NOT use "add *" if you want to keep your ignored files, otherwise everything that was ignored will be re-added.

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Resetting a multi-stage form with jQuery

Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:

function resetForm(formId){
        $('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
        $('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        $('.select2').select2();
    }

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

How to hide/show div tags using JavaScript?

Have you tried

document.getElementById('body').style.display = "none";

instead of

document.getElementById('body').style.display = "hidden";?

C# convert int to string with padding zeros?

public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);

How to convert a string to integer in C?

Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:

void splitInput(int arr[], int sizeArr, char num[])
{
    for(int i = 0; i < sizeArr; i++)
        // We are subtracting 48 because the numbers in ASCII starts at 48.
        arr[i] = (int)num[i] - 48;
}

AngularJS ng-if with multiple conditions

Sure you can. Something like:

HTML

<div ng-controller="fessCntrl">    
     <label ng-repeat="(key,val) in list">
       <input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
         <div ng-if="key == 'City' || key == 'County'">
             <pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
         </div>
         <div ng-if="key == 'Town'">
             <pre>Town!!! {{$parent.localityTypeRadio}}</pre>
         </div>        
      </label>
</div>

JS

var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.list = {
        City: [{name: "cityA"}, {name: "cityB"}],
        County: [{ name: "countyA"}, {name: "countyB"}],
        Town: [{ name: "townA"}, {name: "townB"}]
      };

    $scope.localityTypeRadio = 'City';
});

fessmodule.$inject = ['$scope'];

Demo Fiddle

Most efficient way to reverse a numpy array

np.fliplr() flips the array left to right.

Note that for 1d arrays, you need to trick it a bit:

arr1d = np.array(some_sequence)
reversed_arr = np.fliplr([arr1d])[0]

How to fix git error: RPC failed; curl 56 GnuTLS

I saw similar issues (particularly with depth) on some legacy projects when we were cloning that used to live on TFS. Enabling long paths resolved our issue and may be something else worth trying.

git config --system core.longpaths true

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

Single vs double quotes in JSON

Two issues with answers given so far, if , for instance, one streams such non-standard JSON. Because then one might have to interpret an incoming string (not a python dictionary).

Issue 1 - demjson: With Python 3.7.+ and using conda I wasn't able to install demjson since obviosly it does not support Python >3.5 currently. So I need a solution with simpler means, for instance astand/or json.dumps.

Issue 2 - ast & json.dumps: If a JSON is both single quoted and contains a string in at least one value, which in turn contains single quotes, the only simple yet practical solution I have found is applying both:

In the following example we assume line is the incoming JSON string object :

>>> line = str({'abc':'008565','name':'xyz','description':'can control TV\'s and more'})

Step 1: convert the incoming string into a dictionary using ast.literal_eval()
Step 2: apply json.dumps to it for the reliable conversion of keys and values, but without touching the contents of values:

>>> import ast
>>> import json
>>> print(json.dumps(ast.literal_eval(line)))
{"abc": "008565", "name": "xyz", "description": "can control TV's and more"}

json.dumps alone would not do the job because it does not interpret the JSON, but only see the string. Similar for ast.literal_eval(): although it interprets correctly the JSON (dictionary), it does not convert what we need.

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

Get user location by IP address

IPInfoDB has an API that you can call in order to find a location based on an IP address.

For "City Precision", you call it like this (you'll need to register to get a free API key):

 http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Here's an example in both VB and C# that shows how to call the API.

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

SQL Server Format Date DD.MM.YYYY HH:MM:SS

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

You can concatenate it:

SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

Breaking a list into multiple columns in Latex

Another option to avoid nesting two different environments (like multicols and enumerate).

The environment called tasks from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).

This code:

\documentclass{article}
\usepackage{tasks}

%\settasks{style=itemize}

\begin{document}
Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.

\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}    

Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.
\end{document}

produces this output

tasks

The package tasks was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.

jQuery - determine if input element is textbox or select list

alternatively you can retrieve DOM properties with .prop

here is sample code for select box

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

for textbox

  if( ctrl.prop('type') == 'text' ) { // for text box }

How to debug heap corruption errors?

To really slow things down and perform a lot of runtime checking, try adding the following at the top of your main() or equivalent in Microsoft Visual Studio C++

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF );

Print a variable in hexadecimal in Python

Use

print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))

like this:

>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>

On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

How do I get the Back Button to work with an AngularJS ui-router state machine?

browser's back/forward button solution
I encountered the same problem and I solved it using the popstate event from the $window object and ui-router's $state object. A popstate event is dispatched to the window every time the active history entry changes.
The $stateChangeSuccess and $locationChangeSuccess events are not triggered on browser's button click even though the address bar indicates the new location.
So, assuming you've navigated from states main to folder to main again, when you hit back on the browser, you should be back to the folder route. The path is updated but the view is not and still displays whatever you have on main. try this:

angular
.module 'app', ['ui.router']
.run($state, $window) {

     $window.onpopstate = function(event) {

        var stateName = $state.current.name,
            pathname = $window.location.pathname.split('/')[1],
            routeParams = {};  // i.e.- $state.params

        console.log($state.current.name, pathname); // 'main', 'folder'

        if ($state.current.name.indexOf(pathname) === -1) {
            // Optionally set option.notify to false if you don't want 
            // to retrigger another $stateChangeStart event
            $state.go(
              $state.current.name, 
              routeParams,
              {reload:true, notify: false}
            );
        }
    };
}

back/forward buttons should work smoothly after that.

note: check browser compatibility for window.onpopstate() to be sure

Making button go full-width?

Bootstrap v3 & v4

Use btn-block class on your button/element

Bootstrap v2

Use input-block-level class on your button/element

cannot load such file -- bundler/setup (LoadError)

Other possible situation: you have multiple users defined in your server environment. In that case, running

passenger-config --ruby-command

will give you the necessary command to specify your nginx/sites-enabled/relevant_application file with your use case, example:

passenger-config was invoked through the following Ruby interpreter:
Command: /home/other_user/.rbenv/versions/2.4.5/bin/ruby
Version: ruby 2.4.5p335 (2018-10-18 revision 65137) [x86_64-linux]
To use in Apache: PassengerRuby /home/other_user/.rbenv/versions/2.4.5/bin/ruby
To use in Nginx : passenger_ruby /home/other_user/.rbenv/versions/2.4.5/bin/ruby
To use with Standalone: /home/other_user/.rbenv/versions/2.4.5/bin/ruby /usr/bin/passenger start

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

invalidate cache in android studio will resolve this issue. Go to file-> click on invalidate cache/restart option.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I was able to solve this problem by executing this statement

sudo dpkg-reconfigure mysql-server-5.5

Which will change the root password.

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming you've got access to a standard Unix shell and/or cygwin environment:

tr -s ' ' '\n' < yourfile | sort | uniq -d -c
       ^--space char

Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

<?php
    $illstack=array(...............);
    $val=array('uk','bn','in');
    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>

How to iterate over rows in a DataFrame in Pandas

There is a way to iterate throw rows while getting a DataFrame in return, and not a Series. I don't see anyone mentioning that you can pass index as a list for the row to be returned as a DataFrame:

for i in range(len(df)):
    row = df.iloc[[i]]

Note the usage of double brackets. This returns a DataFrame with a single row.

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Are PDO prepared statements sufficient to prevent SQL injection?

Eaven if you are going to prevent sql injection front-end, using html or js checks, you'd have to consider that front-end checks are "bypassable".

You can disable js or edit a pattern with a front-end development tool (built in with firefox or chrome nowadays).

So, in order to prevent SQL injection, would be right to sanitize input date backend inside your controller.

I would like to suggest to you to use filter_input() native PHP function in order to sanitize GET and INPUT values.

If you want to go ahead with security, for sensible database queries, I'd like to suggest to you to use regular expression to validate data format. preg_match() will help you in this case! But take care! Regex engine is not so light. Use it only if necessary, otherwise your application performances will decrease.

Security has a costs, but do not waste your performance!

Easy example:

if you want to double check if a value, received from GET is a number, less then 99 if(!preg_match('/[0-9]{1,2}/')){...} is heavyer of

if (isset($value) && intval($value)) <99) {...}

So, the final answer is: "No! PDO Prepared Statements does not prevent all kind of sql injection"; It does not prevent unexpected values, just unexpected concatenation

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

I just run this command as a root from terminal and problem is solved,

sudo apt-get install -y postgis postgresql-9.3-postgis-2.1
pip install psycopg2

or

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

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

Using a RegEx to match IP addresses in Python

I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses. Found a better way for it:

Unfortunately it Works for python3 only

import ipaddress

def valid_ip(address):
    try: 
        print ipaddress.ip_address(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('2001:DB8::1')
print valid_ip('gibberish')

How to change progress bar's progress color in Android

Since method public void setColorFilter(@ColorInt int color, @NonNull PorterDuff.Mode mode) is deprecated, I use such form:

progressBar.indeterminateDrawable.colorFilter =
            PorterDuffColorFilter(ContextCompat.getColor(this, R.color.black), PorterDuff.Mode.SRC_IN)

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

What issues should be considered when overriding equals and hashCode in Java?

For equals, look into Secrets of Equals by Angelika Langer. I love it very much. She's also a great FAQ about Generics in Java. View her other articles here (scroll down to "Core Java"), where she also goes on with Part-2 and "mixed type comparison". Have fun reading them!

Is there a "null coalescing" operator in JavaScript?

If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

How to convert float to int with Java

Using Math.round() will round the float to the nearest integer.

What is simplest way to read a file into String?

Sadly, no.

I agree that such frequent operation should have easier implementation than copying of input line by line in loop, but you'll have to either write helper method or use external library.

Install specific branch from github using Npm

The Doc of the npm defines that only tag/version can be specified after repo_url.

Here is the Doc: https://docs.npmjs.com/cli/install

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

Abstract class in Java

An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly

abstract class Foo {
    abstract void someMethod();
}

or indirectly

interface IFoo {
    void someMethod();
}

abstract class Foo2 implements IFoo {
}

However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.

abstract class Foo3 {
}

class Bar extends Foo3 {

}

Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!

The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.

Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:

abstract class Processor {
    protected abstract int[] filterInput(int[] unfiltered);

    public int process(int[] values) {
        int[] filtered = filterInput(values);
        // do something with filtered input
    }
}

class EvenValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove odd numbers
    }
}

class OddValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove even numbers
    }
}

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

How to save a PNG image server-side, from a base64 data string

It's simple :

Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)

  1. Firstly you send a data attribute that contains a base64 encoded string.
  2. In the server side you have to decode it and save it in a local project folder.

Here how to do it using PHP

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

Sort a Custom Class List<T>

First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...

You can then make an IComparer:

public class TagComparer : IComparer<cTag>
{
    public int Compare(cTag first, cTag second)
    {
        if (first != null && second != null)
        {
            // We can compare both properties.
            return first.date.CompareTo(second.date);
        }

        if (first == null && second == null)
        {
            // We can't compare any properties, so they are essentially equal.
            return 0;
        }

        if (first != null)
        {
            // Only the first instance is not null, so prefer that.
            return -1;
        }

        // Only the second instance is not null, so prefer that.
        return 1;
    }
}

var list = new List<cTag>();
// populate list.

list.Sort(new TagComparer());

You can even do it as a delegate:

list.Sort((first, second) =>
          {
              if (first != null && second != null)
                  return first.date.CompareTo(second.date);

              if (first == null && second == null)
                  return 0;

              if (first != null)
                  return -1;

              return 1;
          });

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

How to redirect output of an already running process

Screen

If process is running in a screen session you can use screen's log command to log the output of that window to a file:

Switch to the script's window, C-a H to log.
Now you can :

$ tail -f screenlog.2 | grep whatever

From screen's man page:

log [on|off]

Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.

I'm sure tmux has something similar as well.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

You can also create a project repository. It's useful if more developers are working on the same project, and the library must be included in the project.

  • First, create a repository structure in your project's lib directory, and then copy the library into it. The library must have following name-format: <artifactId>-<version>.jar

    <your_project_dir>/lib/com/microsoft/sqlserver/<artifactId>/<version>/

  • Create pom file next to the library file, and put following information into it:

    <?xml version="1.0" encoding="UTF-8"?>
     <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <modelVersion>4.2.0</modelVersion>
         <groupId>com.microsoft.sqlserver</groupId>
         <artifactId>sqljdbc4</artifactId>
         <version>4.2</version>
     </project>
     
  • At this point, you should have this directory structure:

    <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.jar <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.pom

  • Go to your project's pom file and add new repository:

    <repositories>
         <repository>
             <id>Project repository</id>
             <url>file://${basedir}/lib</url>
         </repository>
     </repositories>
     
  • Finally, add a dependency on the library:

    <dependencies>
         <dependency>
             <groupId>com.microsoft.sqlserver</groupId>
             <artifactId>sqljdbc4</artifactId>
             <version>4.2</version>
         </dependency>
     </dependencies>
     

Update 2017-03-04

It seems like the library can be obtained from publicly available repository. @see nirmal's and Jacek Grzelaczyk's answers for more details.

Update 2020-11-04

Currently Maven has a convenient target install which allow you to deploy an existing package into a project / file repository without the need of creating POM files manually. It will generate those files for you.

mvn install:install-file \
    -Dfile=sqljdbc4.jar \
    -DgroupId=com.microsoft.sqlserver \
    -DartifactId=sqljdbc4 \
    -Dversion=4.2 \
    -Dpackaging=jar \
    -DlocalRepositoryPath=${your_project_dir}/lib

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

How to deep merge instead of shallow merge?

This is a cheap deep merge that uses as little code as I could think of. Each source overwrites the previous property when it exists.

const { keys } = Object;

const isObject = a => typeof a === "object" && !Array.isArray(a);
const merge = (a, b) =>
  isObject(a) && isObject(b)
    ? deepMerge(a, b)
    : isObject(a) && !isObject(b)
    ? a
    : b;

const coalesceByKey = source => (acc, key) =>
  (acc[key] && source[key]
    ? (acc[key] = merge(acc[key], source[key]))
    : (acc[key] = source[key])) && acc;

/**
 * Merge all sources into the target
 * overwriting primitive values in the the accumulated target as we go (if they already exist)
 * @param {*} target
 * @param  {...any} sources
 */
const deepMerge = (target, ...sources) =>
  sources.reduce(
    (acc, source) => keys(source).reduce(coalesceByKey(source), acc),
    target
  );

console.log(deepMerge({ a: 1 }, { a: 2 }));
console.log(deepMerge({ a: 1 }, { a: { b: 2 } }));
console.log(deepMerge({ a: { b: 2 } }, { a: 1 }));

What is the OR operator in an IF statement

The reason this is wrong:

if (title == "User greeting" || "User name") {do stuff};

is because what that's saying is

If title equals the string "User greeting"

or just "User name" (not if title equals the string "User name"). The part after your or would be like writing

if ("User name")

which c# doesn't know what to do with. It can't figure out how to get a boolean out of "User name"

How to set downloading file name in ASP.NET Web API

You need to add the content-disposition header to the response:

 response.StatusCode = HttpStatusCode.OK;
 response.Content = new StreamContent(result);
 response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
 return response;

Rename a column in MySQL

Syntax: ALTER TABLE table_name CHANGE old_column_name new_column_name datatype;

If table name is Student and column name is Name. Then, if you want to change Name to First_Name

ALTER TABLE Student CHANGE Name First_Name varchar(20);

Play sound file in a web-page in the background

Though this might be too late to comment but here's the working code for problems such as yours.

<div id="player">
    <audio autoplay hidden>
     <source src="link/to/file/file.mp3" type="audio/mpeg">
                If you're reading this, audio isn't supported. 
    </audio>
</div>

browser.msie error after update to jQuery 1.9.1

Using this:

if (navigator.userAgent.match("MSIE")) {}

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

import an array in python

Checkout the entry on the numpy example list. Here is the entry on .loadtxt()

>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt")                       # myfile.txt contains 4 columns of numbers
>>> t,z = data[:,0], data[:,3]                         # data is 2D numpy array
>>>
>>> t,x,y,z = loadtxt("myfile.txt", unpack=True)                  # to unpack all columns
>>> t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True)     # to select just a few columns
>>> data = loadtxt("myfile.txt", skiprows = 7)                    # to skip 7 rows from top of file
>>> data = loadtxt("myfile.txt", comments = '!')                  # use '!' as comment char instead of '#'
>>> data = loadtxt("myfile.txt", delimiter=';')                   # use ';' as column separator instead of whitespace
>>> data = loadtxt("myfile.txt", dtype = int)                     # file contains integers instead of floats

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

Best way to reset an Oracle sequence to the next value in an existing column?

If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):

DECLARE
  last_used  NUMBER;
  curr_seq   NUMBER;
BEGIN
  SELECT MAX(pk_val) INTO last_used FROM your_table;

  LOOP
    SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
    IF curr_seq >= last_used THEN EXIT;
    END IF;
  END LOOP;
END;

This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...

Developing C# on Linux

Mono Develop is what you want, if you have used visual studio you should find it simple enough to get started.

If I recall correctly you should be able to install with sudo apt-get install monodevelop

How to add an item to a drop down list in ASP.NET?

Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>

If you want to add it at a different index, maybe the last then try:

ListItem lst = new ListItem ( "Add New" , "0" );

DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);

Embedding Windows Media Player for all browsers

The following works for me in Firefox and Internet Explorer:

<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="true">
     <param name="ShowStatusBar" value="true">
     <param name="windowlessvideo" value="true">
     <embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>

In PHP with PDO, how to check the final SQL parametrized query?

What I did to print that actual query is a bit complicated but it works :)

In method that assigns variables to my statement I have another variable that looks a bit like this:

$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);

Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens

What it does is a simply replace tokens with values when the real PDO assignment happens.

I hope I did not confuse you and at least pointed you in right direction.

Toolbar Navigation Hamburger Icon missing

For that you just need write to some lines

   DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
   ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
   drawer.addDrawerListener(toggle);
   toggle.setDrawerIndicatorEnabled(true);
   toggle.syncState();

toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line

how to get the one entry from hashmap without iterating

Following your EDIT, here's my suggestion :

If you have only one entry, you might replace the Map by a dual object. Depending on the types, and your preferences:

  • an array (of 2 values, key and value)
  • a simple object with two properties

How can I have grep not print out 'No such file or directory' errors?

I redirect stderr to stdout and then use grep's invert-match (-v) to exclude the warning/error string that I want to hide:

grep -r <pattern> * 2>&1 | grep -v "No such file or directory"

How to display list items on console window in C#

Actually you can do it pretty simple, since the list have a ForEach method and since you can pass in Console.WriteLine as a method group. The compiler will then use an implicit conversion to convert the method group to, in this case, an Action<int> and pick the most specific method from the group, in this case Console.WriteLine(int):

  var list = new List<int>(Enumerable.Range(0, 50));

  list.ForEach(Console.WriteLine);

Works with strings too =)

To be utterly pedantic (and I'm not suggesting a change to your answer - just commenting for the sake of interest) Console.WriteLine is a method group. The compiler then uses an implicit conversion from the method group to Action<int>, picking the most specific method (Console.WriteLine(int) in this case).

How to properly upgrade node using nvm

if you have 4.2 and want to install 5.0.0 then

nvm install v5.0.0 --reinstall-packages-from=4.2

the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

source: sitepoint

HTML5 Form Input Pattern Currency Format

I like to give the users a bit of flexibility and trust, that they will get the format right, but I do want to enforce only digits and two decimals for currency

^[$\-\s]*[\d\,]*?([\.]\d{0,2})?\s*$

Takes care of:

$ 1.
-$ 1.00
$ -1.0
.1
.10
-$ 1,000,000.0

Of course it will also match:

$$--$1,92,9,29.1 => anyway after cleanup => -192,929.10

ReferenceError: describe is not defined NodeJs

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

Case insensitive comparison of strings in shell script

Here is my solution using tr:

var1=match
var2=MATCH
var1=`echo $var1 | tr '[A-Z]' '[a-z]'`
var2=`echo $var2 | tr '[A-Z]' '[a-z]'`
if [ "$var1" = "$var2" ] ; then
  echo "MATCH"
fi

Hiding elements in responsive layout?

Bootstrap 4 Beta Answer:

d-block d-md-none to hide on medium, large and extra large devices.

d-none d-md-block to hide on small and extra-small devices.

enter image description here

Note that you can also inline by replacing d-*-block with d-*-inline-block


Old answer: Bootstrap 4 Alpha

  • You can use the classes .hidden-*-up to hide on a given size and larger devices

    .hidden-md-up to hide on medium, large and extra large devices.

  • The same goes with .hidden-*-down to hide on a given size and smaller devices

    .hidden-md-down to hide on medium, small and extra-small devices

  • visible-* is no longer an option with bootstrap 4

  • To display only on medium devices, you can combine the two:

    hidden-sm-down and hidden-xl-up

The valid sizes are:

  • xs for phones in portrait mode (<34em)
  • sm for phones in landscape mode (=34em)
  • md for tablets (=48em)
  • lg for desktops (=62em)
  • xl for desktops (=75em)

This was as of Bootstrap 4, alpha 5 (January 2017). More details here: http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

On Bootstrap 4.3.x: https://getbootstrap.com/docs/4.3/utilities/display/

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

Angular : Manual redirect to route

You may have enough correct answers for your question but in case your IDE gives you the warning

Promise returned from navigate is ignored

you may either ignore that warning or use this.router.navigate(['/your-path']).then().

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Generating Unique Random Numbers in Java

Though it's an old thread, but adding another option might not harm. (JDK 1.8 lambda functions seem to make it easy);

The problem could be broken down into the following steps;

  • Get a minimum value for the provided list of integers (for which to generate unique random numbers)
  • Get a maximum value for the provided list of integers
  • Use ThreadLocalRandom class (from JDK 1.8) to generate random integer values against the previously found min and max integer values and then filter to ensure that the values are indeed contained by the originally provided list. Finally apply distinct to the intstream to ensure that generated numbers are unique.

Here is the function with some description:

/**
 * Provided an unsequenced / sequenced list of integers, the function returns unique random IDs as defined by the parameter
 * @param numberToGenerate
 * @param idList
 * @return List of unique random integer values from the provided list
 */
private List<Integer> getUniqueRandomInts(List<Integer> idList, Integer numberToGenerate) {

    List<Integer> generatedUniqueIds = new ArrayList<>();

    Integer minId = idList.stream().mapToInt (v->v).min().orElseThrow(NoSuchElementException::new);
    Integer maxId = idList.stream().mapToInt (v->v).max().orElseThrow(NoSuchElementException::new);

            ThreadLocalRandom.current().ints(minId,maxId)
            .filter(e->idList.contains(e))
            .distinct()
            .limit(numberToGenerate)
            .forEach(generatedUniqueIds:: add);

    return generatedUniqueIds;

}

So that, to get 11 unique random numbers for 'allIntegers' list object, we'll call the function like;

    List<Integer> ids = getUniqueRandomInts(allIntegers,11);

The function declares new arrayList 'generatedUniqueIds' and populates with each unique random integer up to the required number before returning.

P.S. ThreadLocalRandom class avoids common seed value in case of concurrent threads.

Import Excel to Datagridview

try the following program

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.DataSet DtSet;
        System.Data.OleDb.OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "Net-informations.com");
        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);
        dataGridView1.DataSource = DtSet.Tables[0];
        MyConnection.Close();
    }
}
} 

Android webview & localStorage

A solution that works on my Android 4.2.2, compiled with build target Android 4.4W:

WebSettings settings = webView.getSettings();
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    File databasePath = getDatabasePath("yourDbName");
    settings.setDatabasePath(databasePath.getPath());
}

Move UIView up when the keyboard appears in iOS

I found theDuncs answer very useful and below you can find my own (refactored) version:


Main Changes

  1. Now getting the keyboard size dynamically, rather than hard coding values
  2. Extracted the UIView Animation out into it's own method to prevent duplicate code
  3. Allowed duration to be passed into the method, rather than being hard coded

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    float newVerticalPosition = -keyboardSize.height;

    [self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    [self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
}


- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
    CGRect frame = self.view.frame;
    frame.origin.y = position;

    [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
    }];
}

How to sort a List of objects by their date (java collections, List<Object>)

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

Perform Button click event when user press Enter key in Textbox

In the aspx page load event, add an onkeypress to the box.

this.TextBox1.Attributes.Add(
    "onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");

Then add this javascript to evaluate the key press, and if it is "enter," click the right button.

<script>
    function button_click(objTextBox,objBtnID)
    {
        if(window.event.keyCode==13)
        {
            document.getElementById(objBtnID).focus();
            document.getElementById(objBtnID).click();
        }
    }
</script>

Python read next()

A small change to your algorithm:

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

while 1:
    lines = f.readlines()
    if not lines:
        break
    line_iter= iter(lines) # here
    for line in line_iter: # and here
        print line
        if (line[:5] == "anim "):
            print 'next() '
            ne = line_iter.next() # and here
            print ' ne ',ne,'\n'
            break

f.close()

However, using the pairwise function from itertools recipes:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

you can change your loop into:

for line, next_line in pairwise(f): # iterate over the file directly
    print line
    if line.startswith("anim "):
        print 'next() '
        print ' ne ', next_line, '\n'
        break

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality


The addwithvalue method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add method requires that you specify the Database type first. This helps to reduce such errors.

For more detail Please click here

Convert string with comma to integer

You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.

Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery - Follow the cursor with a DIV

You don't need jQuery for this. Here's a simple working example:

<!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;                    
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

I chose position: fixed; so scrolling wouldn't be an issue.

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

What's the difference between SortedList and SortedDictionary?

Check out the MSDN page for SortedList:

From Remarks section:

The SortedList<(Of <(TKey, TValue>)>) generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to the SortedDictionary<(Of <(TKey, TValue>)>) generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList<(Of <(TKey, TValue>)>) uses less memory than SortedDictionary<(Of <(TKey, TValue>)>).
  • SortedDictionary<(Of <(TKey, TValue>)>) has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) for SortedList<(Of <(TKey, TValue>)>).

  • If the list is populated all at once from sorted data, SortedList<(Of <(TKey, TValue>)>) is faster than SortedDictionary<(Of <(TKey, TValue>)>).

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

Auto height div with overflow and scroll when needed

Well, after long research, i found a workaround that does what i need: http://jsfiddle.net/CqB3d/25/

CSS:

body{
    margin: 0;
    padding: 0;
    border: 0;
    overflow: hidden;
    height: 100%; 
    max-height: 100%; 
}

#caixa{
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}
#framecontentTop, #framecontentBottom{
    position: absolute; 
    top: 0;   
    width: 800px; 
    height: 100px; /*Height of top frame div*/
    overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
    background-color: navy;
    color: white; 
}

#framecontentBottom{
    top: auto;
    bottom: 0; 
    height: 110px; /*Height of bottom frame div*/
    overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
    background-color: navy;
    color: white;
}

#maincontent{
    position: fixed; 
    top: 100px; /*Set top value to HeightOfTopFrameDiv*/
    margin-left:auto;
    margin-right: auto;
    bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/
    overflow: auto; 
    background: #fff;
    width: 800px;
}

.innertube{
    margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/
}

* html body{ /*IE6 hack*/
    padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/
}

* html #maincontent{ /*IE6 hack*/
    height: 100%; 
    width: 800px; 
}

HTML:

<div id="framecontentBottom">
    <div class="innertube">
        <h3>Sample text here</h3>
    </div>
</div>
<div id="maincontent">
    <div class="innertube">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text...
    </div>
</div>

might not work with the horizontal thingy yet, but, it's a work in progress!

I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.

Hope this might help whoever finds the question later!

EDIT: This is the final answer.

What is the fastest factorial function in JavaScript?

You can search for (1...100)! on Wolfram|Alpha to pre-calculate the factorial sequence.

The first 100 numbers are:

1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000, 51090942171709440000, 1124000727777607680000, 25852016738884976640000, 620448401733239439360000, 15511210043330985984000000, 403291461126605635584000000, 10888869450418352160768000000, 304888344611713860501504000000, 8841761993739701954543616000000, 265252859812191058636308480000000, 8222838654177922817725562880000000, 263130836933693530167218012160000000, 8683317618811886495518194401280000000, 295232799039604140847618609643520000000, 10333147966386144929666651337523200000000, 371993326789901217467999448150835200000000, 13763753091226345046315979581580902400000000, 523022617466601111760007224100074291200000000, 20397882081197443358640281739902897356800000000, 815915283247897734345611269596115894272000000000, 33452526613163807108170062053440751665152000000000, 1405006117752879898543142606244511569936384000000000, 60415263063373835637355132068513997507264512000000000, 2658271574788448768043625811014615890319638528000000000, 119622220865480194561963161495657715064383733760000000000, 5502622159812088949850305428800254892961651752960000000000, 258623241511168180642964355153611979969197632389120000000000, 12413915592536072670862289047373375038521486354677760000000000, 608281864034267560872252163321295376887552831379210240000000000, 30414093201713378043612608166064768844377641568960512000000000000, 1551118753287382280224243016469303211063259720016986112000000000000, 80658175170943878571660636856403766975289505440883277824000000000000, 4274883284060025564298013753389399649690343788366813724672000000000000, 230843697339241380472092742683027581083278564571807941132288000000000000, 12696403353658275925965100847566516959580321051449436762275840000000000000, 710998587804863451854045647463724949736497978881168458687447040000000000000, 40526919504877216755680601905432322134980384796226602145184481280000000000000, 2350561331282878571829474910515074683828862318181142924420699914240000000000000, 138683118545689835737939019720389406345902876772687432540821294940160000000000000, 8320987112741390144276341183223364380754172606361245952449277696409600000000000000, 507580213877224798800856812176625227226004528988036003099405939480985600000000000000, 31469973260387937525653122354950764088012280797258232192163168247821107200000000000000, 1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000, 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000, 8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000, 544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000, 36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000, 2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000, 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000, 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000, 850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000, 61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000, 4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000, 330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000, 24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000, 1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000, 145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000, 11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000, 894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000, 71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000, 5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000, 475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000, 39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000, 3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000, 281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000, 24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000, 2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000, 185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000, 16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000, 1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000, 135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000, 12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000, 1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000, 108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000, 10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000, 991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000, 96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000, 9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000, 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000, 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

If you still want to calculate the values yourself, you can use memoization:

var f = [];
function factorial (n) {
  if (n == 0 || n == 1)
    return 1;
  if (f[n] > 0)
    return f[n];
  return f[n] = factorial(n-1) * n;
}

Edit: 21.08.2014

Solution 2

I thought it would be useful to add a working example of lazy iterative factorial function that uses big numbers to get exact result with memoization and cache as comparison

var f = [new BigNumber("1"), new BigNumber("1")];
var i = 2;
function factorial(n)
{
  if (typeof f[n] != 'undefined')
    return f[n];
  var result = f[i-1];
  for (; i <= n; i++)
      f[i] = result = result.multiply(i.toString());
  return result;
}
var cache = 100;
// Due to memoization, following line will cache first 100 elements.
factorial(cache);

I assume you would use some kind of closure to limit variable name visibility.

Ref: BigNumber Sandbox: JsFiddle

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Format ints into string of hex

Just for completeness, using the modern .format() syntax:

>>> numbers = [1, 15, 255]
>>> ''.join('{:02X}'.format(a) for a in numbers)
'010FFF'

Checkout another branch when there are uncommitted changes on the current branch

Preliminary notes

This answer is an attempt to explain why Git behaves the way it does. It is not a recommendation to engage in any particular workflows. (My own preference is to just commit anyway, avoiding git stash and not trying to be too tricky, but others like other methods.)

The observation here is that, after you start working in branch1 (forgetting or not realizing that it would be good to switch to a different branch branch2 first), you run:

git checkout branch2

Sometimes Git says "OK, you're on branch2 now!" Sometimes, Git says "I can't do that, I'd lose some of your changes."

If Git won't let you do it, you have to commit your changes, to save them somewhere permanent. You may want to use git stash to save them; this is one of the things it's designed for. Note that git stash save or git stash push actually means "Commit all the changes, but on no branch at all, then remove them from where I am now." That makes it possible to switch: you now have no in-progress changes. You can then git stash apply them after switching.

Sidebar: git stash save is the old syntax; git stash push was introduced in Git version 2.13, to fix up some problems with the arguments to git stash and allow for new options. Both do the same thing, when used in the basic ways.

You can stop reading here, if you like!

If Git won't let you switch, you already have a remedy: use git stash or git commit; or, if your changes are trivial to re-create, use git checkout -f to force it. This answer is all about when Git will let you git checkout branch2 even though you started making some changes. Why does it work sometimes, and not other times?

The rule here is simple in one way, and complicated/hard-to-explain in another:

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.

That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git adds, git rms and such—suppose you are on branch1. A git checkout branch2 would have to do this:

  • For every file that is in branch1 and not in branch2,1 remove that file.
  • For every file that is in branch2 and not in branch1, create that file (with appropriate contents).
  • For every file that is in both branches, if the version in branch2 is different, update the working tree version.

Each of these steps could clobber something in your work-tree:

  • Removing a file is "safe" if the version in the work-tree is the same as the committed version in branch1; it's "unsafe" if you've made changes.
  • Creating a file the way it appears in branch2 is "safe" if it does not exist now.2 It's "unsafe" if it does exist now but has the "wrong" contents.
  • And of course, replacing the work-tree version of a file with a different version is "safe" if the work-tree version is already committed to branch1.

Creating a new branch (git checkout -b newbranch) is always considered "safe": no files will be added, removed, or altered in the work-tree as part of this process, and the index/staging-area is also untouched. (Caveat: it's safe when creating a new branch without changing the new branch's starting-point; but if you add another argument, e.g., git checkout -b newbranch different-start-point, this might have to change things, to move to different-start-point. Git will then apply the checkout safety rules as usual.)


1This requires that we define what it means for a file to be in a branch, which in turn requires defining the word branch properly. (See also What exactly do we mean by "branch"?) Here, what I really mean is the commit to which the branch-name resolves: a file whose path is P is in branch1 if git rev-parse branch1:P produces a hash. That file is not in branch1 if you get an error message instead. The existence of path P in your index or work-tree is not relevant when answering this particular question. Thus, the secret here is to examine the result of git rev-parse on each branch-name:path. This either fails because the file is "in" at most one branch, or gives us two hash IDs. If the two hash IDs are the same, the file is the same in both branches. No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches.

The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen. We are, at least initially, looking only at the mismatches between two frozen commits. Unfortunately, we—or Git—also have to deal with files that aren't in the commit you're going to switch away from and are in the commit you're going to switch to. This leads to the remaining complications, since files can also exist in the index and/or in the work-tree, without having to exist these two particular frozen commits we're working with.

2It might be considered "sort-of-safe" if it already exists with the "right contents", so that Git does not have to create it after all. I recall at least some versions of Git allowing this, but testing just now shows it to be considered "unsafe" in Git 1.8.5.4. The same argument would apply to a modified file that happens to be modified to match the to-be-switch-to branch. Again, 1.8.5.4 just says "would be overwritten", though. See the end of the technical notes as well: my memory may be faulty as I don't think the read-tree rules have changed since I first started using Git at version 1.5.something.


Does it matter whether the changes are staged or unstaged?

Yes, in some ways. In particular, you can stage a change, then "de-modify" the work tree file. Here's a file in two branches, that's different in branch1 and branch2:

$ git show branch1:inboth
this file is in both branches
$ git show branch2:inboth
this file is in both branches
but it has more stuff in branch2 now
$ git checkout branch1
Switched to branch 'branch1'
$ echo 'but it has more stuff in branch2 now' >> inboth

At this point, the working tree file inboth matches the one in branch2, even though we're on branch1. This change is not staged for commit, which is what git status --short shows here:

$ git status --short
 M inboth

The space-then-M means "modified but not staged" (or more precisely, working-tree copy differs from staged/index copy).

$ git checkout branch2
error: Your local changes ...

OK, now let's stage the working-tree copy, which we already know also matches the copy in branch2.

$ git add inboth
$ git status --short
M  inboth
$ git checkout branch2
Switched to branch 'branch2'

Here the staged-and-working copies both matched what was in branch2, so the checkout was allowed.

Let's try another step:

$ git checkout branch1
Switched to branch 'branch1'
$ cat inboth
this file is in both branches

The change I made is lost from the staging area now (because checkout writes through the staging area). This is a bit of a corner case. The change is not gone, but the fact that I had staged it, is gone.

Let's stage a third variant of the file, different from either branch-copy, then set the working copy to match the current branch version:

$ echo 'staged version different from all' > inboth
$ git add inboth
$ git show branch1:inboth > inboth
$ git status --short
MM inboth

The two Ms here mean: staged file differs from HEAD file, and, working-tree file differs from staged file. The working-tree version does match the branch1 (aka HEAD) version:

$ git diff HEAD
$

But git checkout won't allow the checkout:

$ git checkout branch2
error: Your local changes ...

Let's set the branch2 version as the working version:

$ git show branch2:inboth > inboth
$ git status --short
MM inboth
$ git diff HEAD
diff --git a/inboth b/inboth
index ecb07f7..aee20fb 100644
--- a/inboth
+++ b/inboth
@@ -1 +1,2 @@
 this file is in both branches
+but it has more stuff in branch2 now
$ git diff branch2 -- inboth
$ git checkout branch2
error: Your local changes ...

Even though the current working copy matches the one in branch2, the staged file does not, so a git checkout would lose that copy, and the git checkout is rejected.

Technical notes—only for the insanely curious :-)

The underlying implementation mechanism for all of this is Git's index. The index, also called the "staging area", is where you build the next commit: it starts out matching the current commit, i.e., whatever you have checked-out now, and then each time you git add a file, you replace the index version with whatever you have in your work-tree.

Remember, the work-tree is where you work on your files. Here, they have their normal form, rather than some special only-useful-to-Git form like they do in commits and in the index. So you extract a file from a commit, through the index, and then on into the work-tree. After changing it, you git add it to the index. So there are in fact three places for each file: the current commit, the index, and the work-tree.

When you run git checkout branch2, what Git does underneath the covers is to compare the tip commit of branch2 to whatever is in both the current commit and the index now. Any file that matches what's there now, Git can leave alone. It's all untouched. Any file that's the same in both commits, Git can also leave alone—and these are the ones that let you switch branches.

Much of Git, including commit-switching, is relatively fast because of this index. What's actually in the index is not each file itself, but rather each file's hash. The copy of the file itself is stored as what Git calls a blob object, in the repository. This is similar to how the files are stored in commits as well: commits don't actually contain the files, they just lead Git to the hash ID of each file. So Git can compare hash IDs—currently 160-bit-long strings—to decide if commits X and Y have the same file or not. It can then compare those hash IDs to the hash ID in the index, too.

This is what leads to all the oddball corner cases above. We have commits X and Y that both have file path/to/name.txt, and we have an index entry for path/to/name.txt. Maybe all three hashes match. Maybe two of them match and one doesn't. Maybe all three are different. And, we might also have another/file.txt that's only in X or only in Y and is or is not in the index now. Each of these various cases requires its own separate consideration: does Git need to copy the file out from commit to index, or remove it from index, to switch from X to Y? If so, it also has to copy the file to the work-tree, or remove it from the work-tree. And if that's the case, the index and work-tree versions had better match at least one of the committed versions; otherwise Git will be clobbering some data.

(The complete rules for all of this are described in, not the git checkout documentation as you might expect, but rather the git read-tree documentation, under the section titled "Two Tree Merge".)

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

Why dict.get(key) instead of dict[key]?

For what purpose is this function useful?

One particular usage is counting with a dictionary. Let's assume you want to count the number of occurrences of each element in a given list. The common way to do so is to make a dictionary where keys are elements and values are the number of occurrences.

fruits = ['apple', 'banana', 'peach', 'apple', 'pear']
d = {}
for fruit in fruits:
    if fruit not in d:
        d[fruit] = 0
    d[fruit] += 1

Using the .get() method, you can make this code more compact and clear:

for fruit in fruits:
    d[fruit] = d.get(fruit, 0) + 1

Getting index value on razor foreach

You could also use deconstruction and tuples and try something like this:

@foreach (var (index, member) in @Model.Members.Select((member, i) => (i, member)))
{
  <div>@index - @member.anyProperty</div>

  if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
      @: <div class="clear"></div>
  }
}

For more info you can have a look at this link

How can I make a DateTimePicker display an empty string?

Listen , Make Following changes in your code if you want to show empty datetimepicker and get null when no date is selected by user, else save date.

  1. Set datetimepicker FORMAT property to custom.
  2. set CUSTOM FORMAT property to empty string " ".
  3. set its TAG to 0 by default.
  4. Register Event for datetimepicker VALUECHANGED.

Now real work starts

if user will interact with datetimepicker its VALUECHANGED event will be called and there set its TAG property to 1.

Final Step

Now when saving, check if its TAG is zero, then save NULL date else if TAG is 1 then pick and save Datetime picker value.

It Works like a charm.

Now if you want its value be changed back to empty by user interaction, then add checkbox and show text "Clear" with this checkbox. if user wants to clear date, simply again set its CUSTOM FORMAT property to empty string " ", and set its TAG back to 0. Thats it..

Equivalent to AssemblyInfo in dotnet core/csproj

I do the following for my .NET Standard 2.0 projects.

Create a Directory.Build.props file (e.g. in the root of your repo) and move the properties to be shared from the .csproj file to this file.

MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs.

They also get applied to the nuget package when building one with dotnet pack or via the UI in Visual Studio 2017.

See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build

Example:

<Project>
    <PropertyGroup>
        <Company>Some company</Company>
        <Copyright>Copyright © 2020</Copyright>
        <AssemblyVersion>1.0.0.1</AssemblyVersion>
        <FileVersion>1.0.0.1</FileVersion>
        <Version>1.0.0.1</Version>
        <!-- ... -->
    </PropertyGroup>
</Project>

Override back button to act like home button

try to override void onBackPressed() defined in android.app.Activity class.

The network path was not found

In my case, I had generated DbContext from an existing database. I had my connection string set in appSettings.json file; however, when I generated the class files by scaffolding the DbContext class it had incorrect connection string.

So make sure your connection string is proper in appSettings.json file as well as in DbContext file. This will solve your issue.

how to get docker-compose to use the latest image from repository

I spent half a day with this problem. The reason was that be sure to check where the volume was recorded.

volumes: - api-data:/src/patterns

But the fact is that in this place was the code that we changed. But when updating the docker, the code did not change.

Therefore, if you are checking someone else's code and for some reason you are not updating, check this.

And so in general this approach works:

docker-compose down

docker-compose build

docker-compose up -d

JWT (JSON Web Token) library for Java

IETF has suggested jose libs on it's wiki: http://trac.tools.ietf.org/wg/jose/trac/wiki

I would highly recommend using them for signing. I am not a Java guy, but seems like jose4j seems like a good option. Has nice examples as well: https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples

Update: jwt.io provides a neat comparison of several jwt related libraries, and their features. A must check!

I would love to hear about what other java devs prefer.

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

Downgrade npm to an older version

Even I run npm install -g npm@4, it is not ok for me.

Finally, I download and install the old node.js version.

https://nodejs.org/download/release/v7.10.1/

It is npm version 4.

You can choose any version here https://nodejs.org/download/release/

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

This solution merges smoothly and does not lose history:

  1. Move /working-copy/offender to a temporary location.
  2. Do an svn checkout of svn+ssh://svn.example.com/repo/offender to /working-copy/offender.
  3. Manually move your files from the temporary location into the new checkout.
  4. Delete the temporary location.

How to find if an array contains a specific string in JavaScript/jQuery?

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_


Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern Javascript is Array.prototype.includes:

var found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_

show all tables in DB2 using the LIST command

To get a list of tables for the current database in DB2 -->

Connect to the database:

db2 connect to DATABASENAME user USER using PASSWORD

Run this query:

db2 LIST TABLES

This is the equivalent of SHOW TABLES in MySQL.

You may need to execute 'set schema myschema' to the correct schema before you run the list tables command. By default upon login your schema is the same as your username - which often won't contain any tables. You can use 'values current schema' to check what schema you're currently set to.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Incorrect integer value: '' for column 'id' at row 1

Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".

vi /etc/mysql/my.cnf

sql_mode = ""

save and quit...

service mysql restart

How to convert byte array to string and vice versa?

This works fine for me:

String cd="Holding some value";

Converting from string to byte[]:

byte[] cookie = new sun.misc.BASE64Decoder().decodeBuffer(cd);

Converting from byte[] to string:

cd = new sun.misc.BASE64Encoder().encode(cookie);

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

Can you test google analytics on a localhost address?

After spending about two hours trying to come up with a solution I realized that I had adblockers blocking the call to GA. Once I turned them off I was good to go.

CodeIgniter Active Record not equal

$this->db->where('emailsToCampaigns.campaignId !=' , $campaignId);

This should work (which you have tried)

To debug you might place this code just after you execute your query to see what exact SQL it is producing, this might give you clues, you might add that to the question to allow for further help.

$this->db->get();              // your query executing

echo '<pre>';                  // to preserve formatting
die($this->db->last_query());  // halt execution and print last ran query.

Regex date validation for yyyy-mm-dd

You can use this regex to get the yyyy-MM-dd format:

((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])

You can find example for date validation: How to validate date with regular expression.

Android Studio - How to increase Allocated Heap Size

I looked at my Environment Variables and had a System Variable called _JAVA_OPTIONS with the value -Xms256m -Xmx512m, after changing this to -Xms256m -Xmx1024m the max heap size increased accordingly.

Generating random whole numbers in JavaScript in a specific range?

function getRandomInt(lower, upper)
{
    //to create an even sample distribution
    return Math.floor(lower + (Math.random() * (upper - lower + 1)));

    //to produce an uneven sample distribution
    //return Math.round(lower + (Math.random() * (upper - lower)));

    //to exclude the max value from the possible values
    //return Math.floor(lower + (Math.random() * (upper - lower)));
}

To test this function, and variations of this function, save the below HTML/JavaScript to a file and open with a browser. The code will produce a graph showing the distribution of one million function calls. The code will also record the edge cases, so if the the function produces a value greater than the max, or less than the min, you.will.know.about.it.

<html>
    <head>
        <script type="text/javascript">
        function getRandomInt(lower, upper)
        {
            //to create an even sample distribution
            return Math.floor(lower + (Math.random() * (upper - lower + 1)));

            //to produce an uneven sample distribution
            //return Math.round(lower + (Math.random() * (upper - lower)));

            //to exclude the max value from the possible values
            //return Math.floor(lower + (Math.random() * (upper - lower)));
        }

        var min = -5;
        var max = 5;

        var array = new Array();

        for(var i = 0; i <= (max - min) + 2; i++) {
          array.push(0);
        }

        for(var i = 0; i < 1000000; i++) {
            var random = getRandomInt(min, max);
            array[random - min + 1]++;
        }

        var maxSample = 0;
        for(var i = 0; i < max - min; i++) {
            maxSample = Math.max(maxSample, array[i]);
        }

        //create a bar graph to show the sample distribution
        var maxHeight = 500;
        for(var i = 0; i <= (max - min) + 2; i++) {
            var sampleHeight = (array[i]/maxSample) * maxHeight;

            document.write('<span style="display:inline-block;color:'+(sampleHeight == 0 ? 'black' : 'white')+';background-color:black;height:'+sampleHeight+'px">&nbsp;[' + (i + min - 1) + ']:&nbsp;'+array[i]+'</span>&nbsp;&nbsp;');
        }
        document.write('<hr/>');
        </script>
    </head>
    <body>

    </body>
</html>

Run a single test method with maven

Run a single test method from a test class.

mvn test -Dtest=Test1#methodname


Other related use-cases

  • mvn test // Run all the unit test classes

  • mvn test -Dtest=Test1 // Run a single test class

  • mvn test -Dtest=Test1,Test2 // Run multiple test classes

  • mvn test -Dtest=Test1#testFoo* // Run all test methods that match pattern 'testFoo*' from a test class.

  • mvn test -Dtest=Test1#testFoo*+testBar* // Run all test methods match pattern 'testFoo*' and 'testBar*' from a test class.

How to set cursor position in EditText?

If you want to place the cursor in a certain position on an EditText, you can use:

yourEditText.setSelection(position);

Additionally, there is the possibility to set the initial and final position, so that you programmatically select some text, this way:

yourEditText.setSelection(startPosition, endPosition);

Please note that setting the selection might be tricky since you can place the cursor before or after a character, the image below explains how to index works in this case:

enter image description here

So, if you want the cursor at the end of the text, just set it to yourEditText.length().

Fake "click" to activate an onclick method

You can also try getting the element's onclick attribute and then passing into eval. This should work despite the big taboo over eval. I put a sample below

eval(document.getElementById('elementId').getAttribute('onclick'));

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

Replace new line/return with space using regex

Your regex is good altough I would replace it with the empty string

String resultString = subjectString.replaceAll("[\t\n\r]", "");

You expect a space between "text." and "And" right?

I get that space when I try the regex by copying your sample

"This is my text. "

So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.

point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>

more details in this answer: https://stackoverflow.com/a/37465080/473040

"Invalid form control" only in Google Chrome

I was getting this error, and determined it was actually on a field that was not hidden.

In this case, it was a type="number" field, that is required. When no value has ever been entered into this field, the error message is shown in the console, and the form is not submitted. Entering a value, and then removing it means that the validation error is shown as expected.

I believe this is a bug in Chrome: my workaround for now was to come up with an initial/default value.

How to get box-shadow on left & right sides only

I wasn't satisfied with the rounded top and bottom to the shadow present in Deefour's solution so created my own.

inset box-shadow creates a nice uniform shadow with the top and bottom cut off.

To use this effect on the sides of your element, create two pseudo elements :before and :after positioned absolutely on the sides of the original element.

_x000D_
_x000D_
div:before, div:after {
  content: " ";
  height: 100%;
  position: absolute;
  top: 0;
  width: 15px;
}
div:before {
  box-shadow: -15px 0 15px -15px inset;
  left: -15px;
}
div:after {
  box-shadow: 15px 0 15px -15px inset;
  right: -15px;
}

div {
  background: #EEEEEE;
  height: 100px;
  margin: 0 50px;
  width: 100px;
  position: relative;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


Edit

Depending on your design, you may be able to use clip-path, as shown in @Luke's answer. However, note that in many cases this still results in the shadow tapering off at the top and bottom as you can see in this example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  background: #EEE;
  box-shadow: 0 0 15px 0px #000;
  clip-path: inset(0px -15px 0px -15px);
  position: relative;
  margin: 0 50px;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How can I enable cURL for an installed Ubuntu LAMP stack?

First thing to do: Check for the PHP version your machine is running.

Command Line: php -version

This will show something like this (in my case):

PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS ) Copyright (c) 1997-2016 The PHP Group

If you are using PHP 5.x.x => run command: sudo apt-get install php5-curl

If PHP 7.x.x => run command (in my case): sudo apt-get install php7.0-curl

Enable this extension by running:

sudo gedit /etc/php/7.0/cli/php.ini

And in the file "php.ini" search for keyword "curl" to find this line below and change it from

;extension=php_curl.dll

To:

extension=php_curl.dll

Next, save your file "php.ini".

Finally, in your command line, restart your server by running: sudo service apache2 restart.

Using GPU from a docker container?

We just released an experimental GitHub repository which should ease the process of using NVIDIA GPUs inside Docker containers.

Curl error: Operation timed out

Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.

If you are running the script through browser, then set the set_time_limit to zero for infinite seconds.

set_time_limit(0);

Increase the curl's operation time limit using this option CURLOPT_TIMEOUT

curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds

It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

How can I get client information such as OS and browser

You can use browscap-java to get browser's information.

For Example:

UserAgentParser parser = new UserAgentService().loadParser(Arrays.asList(BrowsCapField.BROWSER));
    Capabilities capabilities = parser.parse(user_agent);

    String browser = capabilities.getBrowser();

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

Adding a css class to select using @Html.DropDownList()

Try this:

@Html.DropDownList(
    "country", 
    new[] {
        new SelectListItem() { Value = "IN", Text = "India" },
        new SelectListItem() { Value = "US", Text = "United States" }
    }, 
    "Country",
    new { @class = "form-control",@selected = Model.Country}
)

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');
    }

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    /* Process $content here */

    // Close curl handle
    curl_close($ch);
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);

}

* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

How to capitalize the first letter of text in a TextView in an Android Application

The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.

private String capitizeString(String name){
    String captilizedString="";
    if(!name.trim().equals("")){
       captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
    }
    return captilizedString;
}

Connecting to Postgresql in a docker container from outside

I know this is late, if you used docker-compose like @Martin

These are the snippets that helped me connect to psql inside the container

docker-compose run db bash

root@de96f9358b70:/# psql -h db -U root -d postgres_db

I cannot comment because I don't have 50 reputation. So hope this helps.

upstream sent too big header while reading response header from upstream

I am not sure that the issue is related to what header php is sending. Make sure that the buffering is enabled. The simple way is to create a proxy.conf file:

proxy_redirect          off;
proxy_set_header        Host            $host;
proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    100m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffering         on;
proxy_buffer_size       128k;
proxy_buffers           4 256k;
proxy_busy_buffers_size 256k;

And a fascgi.conf file:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;
fastcgi_buffers 128 4096k;
fastcgi_buffer_size 4096k;
fastcgi_index  index.php;
fastcgi_param  REDIRECT_STATUS    200;

Next you need to call them in your default config server this way:

http {
  include    /etc/nginx/mime.types;
  include    /etc/nginx/proxy.conf;
  include    /etc/nginx/fastcgi.conf;
  index    index.html index.htm index.php;
  log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log   /logs/access.log  main;
  sendfile     on;
  tcp_nopush   on;
 # ........
}

How to use refs in React with Typescript

If you wont to forward your ref, in Props interface you need to use RefObject<CmpType> type from import React, { RefObject } from 'react';

Compiling dynamic HTML strings from database

Found in a google discussion group. Works for me.

var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
  $compile(element)($rootScope);
});

HTML.ActionLink method

This type use:

@Html.ActionLink("MainPage","Index","Home")

MainPage : Name of the text Index : Action View Home : HomeController

Base Use ActionLink

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
    <meta name="viewport" content="width=device-width" />_x000D_
    <title>_Layout</title>_x000D_
    <link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />_x000D_
</head>_x000D_
<body>_x000D_
    <div class="container">_x000D_
        <div class="col-md-12">_x000D_
            <button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>_x000D_
            <button class="btn btn-default" type="submit">@Html.ActionLink("Hakkimizda", "Hakkimizda", "Home")</button>_x000D_
            <button class="btn btn-default" type="submit">@Html.ActionLink("Iletisim", "Iletisim", "Home")</button>_x000D_
        </div> _x000D_
        @RenderBody()_x000D_
        <div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Byte Array and Int conversion in Java

I took a long look at many questions like this, and found this post... I didn't like the fact that the conversion code is duplicated for each type, so I've made a generic method to perform the task:

public static byte[] toByteArray(long value, int n)
{
    byte[] ret = new byte[n];
    ret[n-1] = (byte) ((value >> (0*8) & 0xFF);   
    ret[n-2] = (byte) ((value >> (1*8) & 0xFF);   
    ...
    ret[1] = (byte) ((value >> ((n-2)*8) & 0xFF);   
    ret[0] = (byte) ((value >> ((n-1)*8) & 0xFF);   
    return ret;
}

See full post.

Is it a bad practice to use break in a for loop?

I don't see any reason why it would be a bad practice PROVIDED that you want to complete STOP processing at that point.

Deserialize a json string to an object in python

pydantic is an increasingly popular library for python 3.6+ projects. It mainly does data validation and settings management using type hints.

A basic example using different types:

from pydantic import BaseModel

class ClassicBar(BaseModel):
    count_drinks: int
    is_open: bool
 
data = {'count_drinks': '226', 'is_open': 'False'}
cb = ClassicBar(**data)
>>> cb
ClassicBar(count_drinks=226, is_open=False)

What I love about the lib is that you get a lot of goodies for free, like

>>> cb.json()
'{"count_drinks": 226, "is_open": false}'
>>> cb.dict()
{'count_drinks': 226, 'is_open': False}

Angular2 - Radio Button Binding

I was looking for the right method to handle those radio buttons here is an example for a solution I found here:

<tr *ngFor="let entry of entries">
    <td>{{ entry.description }}</td>
    <td>
        <input type="radio" name="radiogroup" 
            [value]="entry.id" 
            (change)="onSelectionChange(entry)">
    </td>
</tr>

Notice the onSelectionChange that passes the current element to the method.

Scroll Element into View with Selenium

The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.

Here is my solution for Java:

public List<String> getBoundedRectangleOfElement(WebElement we)
{
    JavascriptExecutor je = (JavascriptExecutor) driver;
    List<String> bounds = (ArrayList<String>) je.executeScript(
            "var rect = arguments[0].getBoundingClientRect();" +
                    "return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
    System.out.println("top: " + bounds.get(1));
    return bounds;
}

And then, to scroll, you call it like this:

public void scrollToElementAndCenterVertically(WebElement we)
{
    List<String> bounds = getBoundedRectangleOfElement(we);
    Long totalInnerPageHeight = getViewPortHeight(driver);
    JavascriptExecutor je = (JavascriptExecutor) driver;
    je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
    je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}

Xcode 4: create IPA file instead of .xcarchive

For Xcode 4.6 (and Xcode 5) archives

  • In Organizer, right-click an archive, select Show in Finder
  • In Finder, right-click an archive, select Show Package Contents
  • Open the folder Products > Applications
  • The application is there
  • Drag the application into iTunes Apps folder

    enter image description here

  • Right-click on the application in iTunes Apps, select Show in Finder

  • The .ipa is there!

How to import a Python class that is in a directory above?

from ..subpkg2 import mod

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

PostgreSQL: How to change PostgreSQL user password?

use this:

\password

enter the new password you want for that user and then confirm it. If you don't remember the password and you want to change it, you can log in as postgres and then use this:

ALTER USER 'the username' WITH PASSWORD 'the new password';

How to add leading zeros for for-loop in shell?

why not printf '%02d' $num? See help printf for this internal bash command.

How to use a variable inside a regular expression?

if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):

This will insert what is in TEXTO into the regex as a string.

Argument Exception "Item with Same Key has already been added"

If you want "insert or replace" semantics, use this syntax:

A[key] = value;     // <-- insert or replace semantics

It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".

So in your case:

rct3Features[items[0]] = items[1];

How to pass values arguments to modal.show() function in Bootstrap

I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.

Here is my modal code:

<div class="modal fade" id="editGroupNameModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div id="editGroupName" class="modal-header">Enter new name for group </div>
        <div class="modal-body">
          <%= form_tag( { action: 'update_group', port: portnum } ) do %>
          <%= text_field_tag( :gid, "", { type: "hidden" })  %>
          <div class="input-group input-group-md">
          <span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
          <%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}})  %>
        </div>
        <div class="modal-footer">
          <%= submit_tag("Submit") %>
        </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

And here is the simple javascript to change the gid, and gname input values:

function editGroupName(id, name) {
    $('input#gid').val(id);
    $('input#gname.form-control').val(name);
  }

I just used the onclick event in a link:

//                                                                              &#39; is single quote
//                                                                                   ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName(&#39;1&#39;, &#39;admin&#39;); return false;" href="#">edit</a>

The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.

I hope this helps someone someday. Cheers.

iOS 7 status bar back to iOS 6 default style in iPhone app?

This may be a overwhelming problem if you use Auto layout because you can not directly manipulate frames anymore. There is a simple solution without too much work.

I ended up writing an utility method in an Utility Class and called it from all the view controllers's viewDidLayoutSubviews Method.

+ (void)addStatusBarIfiOS7:(UIViewController *)vc
    {
        if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
            CGRect viewFrame = vc.view.frame;
            if(viewFrame.origin.y == 20) {
                //If the view's y origin is already 20 then don't move it down.
                return;
            }
            viewFrame.origin.y+=20.0;
            viewFrame.size.height-= 20.0;
            vc.view.frame = viewFrame;
            [vc.view layoutIfNeeded];
        }
    }

Override your viewDidLayoutSubviews method in the view controller, where you want status bar. It will get you through the burden of Autolayout.

- (void)viewDidLayoutSubviews
{
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    [super viewDidLayoutSubviews];
    [MyUtilityClass addStatusBarIfiOS7:self];
}

How to get label of select option with jQuery?

Try this:

$('select option:selected').prop('label');

This will pull out the displayed text for both styles of <option> elements:

  • <option label="foo"><option> -> "foo"
  • <option>bar<option> -> "bar"

If it has both a label attribute and text inside the element, it'll use the label attribute, which is the same behavior as the browser.

For posterity, this was tested under jQuery 3.1.1

How to have stored properties in Swift, the same way I had on Objective-C?

As in Objective-C, you can't add stored property to existing classes. If you're extending an Objective-C class (UIView is definitely one), you can still use Associated Objects to emulate stored properties:

for Swift 1

import ObjectiveC

private var xoAssociationKey: UInt8 = 0

extension UIView {
    var xo: PFObject! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
        }
    }
}

The association key is a pointer that should be the unique for each association. For that, we create a private global variable and use it's memory address as the key with the & operator. See the Using Swift with Cocoa and Objective-C on more details how pointers are handled in Swift.

UPDATED for Swift 2 and 3

import ObjectiveC

private var xoAssociationKey: UInt8 = 0

extension UIView {
    var xo: PFObject! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

UPDATED for Swift 4

In Swift 4, it's much more simple. The Holder struct will contain the private value that our computed property will expose to the world, giving the illusion of a stored property behaviour instead.

Source

extension UIViewController {
    struct Holder {
        static var _myComputedProperty:Bool = false
    }
    var myComputedProperty:Bool {
        get {
            return Holder._myComputedProperty
        }
        set(newValue) {
            Holder._myComputedProperty = newValue
        }
    }
}

How to check if multiple array keys exists

<?php

function check_keys_exists($keys_str = "", $arr = array()){
    $return = false;
    if($keys_str != "" and !empty($arr)){
        $keys = explode(',', $keys_str);
        if(!empty($keys)){
            foreach($keys as $key){
                $return = array_key_exists($key, $arr);
                if($return == false){
                    break;
                }
            }
        }
    }
    return $return;
}

//run demo

$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');

var_dump( check_keys_exists($key, $array));

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

Get DOM content of cross-domain iframe

There's a workaround to achieve it.

  1. First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.

  2. In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.

How do I run a docker instance from a DockerFile?

Straightforward and easy solution is:

docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67

3000 - can be any port

a3e628814c68 - hash result given by success build command

NOTE: you should be within directory that contains Dockerfile.

Split string with delimiters in C

String tokenizer this code should put you in the right direction.

int main(void) {
  char st[] ="Where there is will, there is a way.";
  char *ch;
  ch = strtok(st, " ");
  while (ch != NULL) {
  printf("%s\n", ch);
  ch = strtok(NULL, " ,");
  }
  getch();
  return 0;
}

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

android ellipsize multiline textview

The top answer here from Micah Hainline works great, but even better is the library that was built from it by user aleb as he posted in the comments under Micahs answer:

I created an Android library with this component and changed it to be able to show as many lines of text as possible and ellipsize the last one; see github.com/triposo/barone

There are some more features to it, if you only need the TextView, it is here.

Maybe this will help others find it faster than I did :-)

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.

Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).

What is the string length of a GUID?

I believe GUIDs are constrained to 16-byte lengths (or 32 bytes for an ASCII hex equivalent).

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem because I had a typo in my template near [(ngModel)]]. Extra bracket. Example:

<input id="descr" name="descr" type="text" required class="form-control width-half"
      [ngClass]="{'is-invalid': descr.dirty && !descr.valid}" maxlength="16" [(ngModel)]]="category.descr"
      [disabled]="isDescrReadOnly" #descr="ngModel">

ERROR 1064 (42000): You have an error in your SQL syntax;

It is varchar and not var_char

CREATE DATABASE IF NOT EXISTS courses;

USE courses;

CREATE TABLE IF NOT EXISTS teachers(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    addr VARCHAR(255) NOT NULL,
    phone INT NOT NULL
);

You should use a SQL tool to visualize possbile errors like MySQL Workbench.

OwinStartup not firing

For me it was because they are not in the same namespace. After I remove my AppStart from "project.Startup.AppStart" and let they both Startup.cs and Startup.Auth.cs with "project.Startup" namespace, everything was back to work perfectly.

I hope it help!

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

How to get the device's IMEI/ESN programmatically in android?

For those looking for a Kotlin version, you can use something like this;

private fun telephonyService() {
    val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
    val imei = if (android.os.Build.VERSION.SDK_INT >= 26) {
        Timber.i("Phone >= 26 IMEI")
        telephonyManager.imei
    } else {
        Timber.i("Phone IMEI < 26")
        telephonyManager.deviceId
    }

    Timber.i("Phone IMEI $imei")
}

NOTE: You must wrap telephonyService() above with a permission check using checkSelfPermission or whatever method you use.

Also add this permission in the manifest file;

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

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

USB Debugging option greyed out

This worked for me:

  1. Changing USB connection to File Transfer
  2. Turn off developer options
  3. Turn it back on
  4. USB Debugging option came back to life

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases