Programs & Examples On #Sorted

This tag refers to a collection of items that has already been arranged in some specific order.

Insert an item into sorted list in Python

I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:

def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.
    If x is already in a, insert it to the right of the rightmost x.
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]:
            hi = mid
        else:
            lo = mid+1
    a.insert(lo, x)

How to get indices of a sorted array in Python

If you do not want to use numpy,

sorted(range(len(seq)), key=seq.__getitem__)

is fastest, as demonstrated here.

Sorted array list in Java

It might be a bit too heavyweight for you, but GlazedLists has a SortedList that is perfect to use as the model of a table or JList

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

You can do like this:

SELECT convert(datetime, convert(date, '27-09-2013', 103), 103) 

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

ORA-28000: the account is locked error getting frequently

One of the reasons of your problem could be the password policy you are using.

And if there is no such policy of yours then check your settings for the password properties in the DEFAULT profile with the following query:

SELECT resource_name, limit
FROM dba_profiles 
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';

And If required, you just need to change the PASSWORD_LIFE_TIME to unlimited with the following query:

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

And this Link might be helpful for your problem.

Fill formula down till last row in column

For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.

Range("tablename[columnname]").Formula = "=G3&"",""&L3"

Making it a true one liner. Hope it helps someone!

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

How can I check that JButton is pressed? If the isEnable() is not work?

Just do System.out.println(e.getActionCommand()); inside actionPerformed(ActionEvent e) function. This will tell you which command is just performed.

or

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}

How should I throw a divide by zero exception in Java without actually dividing by zero?

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.

heroku - how to see all the logs

To see the detailed log you need to put two lines in the production.rb file:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::DEBUG

and then by running

heroku logs -t

you can see the detailed logs.

How do I calculate someone's age in Java?

public int getAge(Date dateOfBirth) 
{
    Calendar now = Calendar.getInstance();
    Calendar dob = Calendar.getInstance();

    dob.setTime(dateOfBirth);

    if (dob.after(now)) 
    {
        throw new IllegalArgumentException("Can't be born in the future");
    }

    int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

    if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) 
    {
        age--;
    }

    return age;
}

get current date with 'yyyy-MM-dd' format in Angular 4

You can use date:'yyyy-MM-dd' pipe

curDate=new Date();

<p>{{curDate | date:'yyyy-MM-dd'}}</p>

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

SQL join: selecting the last records in a one-to-many relationship

This is an example of the greatest-n-per-group problem that has appeared regularly on StackOverflow.

Here's how I usually recommend solving it:

SELECT c.*, p1.*
FROM customer c
JOIN purchase p1 ON (c.id = p1.customer_id)
LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
    (p1.date < p2.date OR (p1.date = p2.date AND p1.id < p2.id)))
WHERE p2.id IS NULL;

Explanation: given a row p1, there should be no row p2 with the same customer and a later date (or in the case of ties, a later id). When we find that to be true, then p1 is the most recent purchase for that customer.

Regarding indexes, I'd create a compound index in purchase over the columns (customer_id, date, id). That may allow the outer join to be done using a covering index. Be sure to test on your platform, because optimization is implementation-dependent. Use the features of your RDBMS to analyze the optimization plan. E.g. EXPLAIN on MySQL.


Some people use subqueries instead of the solution I show above, but I find my solution makes it easier to resolve ties.

How to check Elasticsearch cluster health?

If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:

Kibana => DevTools => Console:

GET /_cluster/health 

enter image description here enter image description here

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

I tried invalidating cache, it didnt work for me.

However, I tried removing the jdk from Platform Settings and added it back and it worked.

Here's how to do it.

Project Settings -> SDKs -> Select the SDK -> Remove (-) -> Add it back again (+)

How can I check if a single character appears in a string?

package com;
public class _index {

    public static void main(String[] args) {
        String s1="be proud to be an indian";
        char ch=s1.charAt(s1.indexOf('e'));
        int count = 0; 
        for(int i=0;i<s1.length();i++) {
            if(s1.charAt(i)=='e'){
                System.out.println("number of E:=="+ch);
                count++;
            }
        }
        System.out.println("Total count of E:=="+count);
    }
}

What is the best alternative IDE to Visual Studio

If you're into C# and VB.Net and don't mind open source then you could use SharpDevelop. It does a pretty good job!

Store text file content line by line into array

This should work because it uses List as you don't know how many lines will be there in the file and also they may change later.

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
    lines.add(str);
}
String[] linesArray = lines.toArray(new String[lines.size()]);

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How do I detect a page refresh using jquery?

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.


Example: http://jsfiddle.net/maniator/qpK7Y/

Code:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});

Efficient way to determine number of digits in an integer

// Meta-program to calculate number of digits in (unsigned) 'N'.    
template <unsigned long long N, unsigned base=10>
struct numberlength
{   // http://stackoverflow.com/questions/1489830/
    enum { value = ( 1<=N && N<base ? 1 : 1+numberlength<N/base, base>::value ) };
};

template <unsigned base>
struct numberlength<0, base>
{
    enum { value = 1 };
};

{
    assert( (1 == numberlength<0,10>::value) );
}
assert( (1 == numberlength<1,10>::value) );
assert( (1 == numberlength<5,10>::value) );
assert( (1 == numberlength<9,10>::value) );

assert( (4 == numberlength<1000,10>::value) );
assert( (4 == numberlength<5000,10>::value) );
assert( (4 == numberlength<9999,10>::value) );

Get free disk space

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);
            Console.WriteLine("  Drive type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes", 
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }
        }
    }
}
/* 
This code produces output similar to the following:

Drive A:\
  Drive type: Removable
Drive C:\
  Drive type: Fixed
  Volume label: 
  File system: FAT32
  Available space to current user:     4770430976 bytes
  Total available space:               4770430976 bytes
  Total size of drive:                10731683840 bytes 
Drive D:\
  Drive type: Fixed
  Volume label: 
  File system: NTFS
  Available space to current user:    15114977280 bytes
  Total available space:              15114977280 bytes
  Total size of drive:                25958948864 bytes 
Drive E:\
  Drive type: CDRom

The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/

Create a pointer to two-dimensional array

You could also add an offset if you want to use negative indexes:

uint8_t l_matrix[10][20];
uint8_t (*matrix_ptr)[20] = l_matrix+5;
matrix_ptr[-4][1]=7;

If your compiler gives an error or warning you could use:

uint8_t (*matrix_ptr)[20] = (uint8_t (*)[20]) l_matrix;

How to check the maximum number of allowed connections to an Oracle database?

Note: this only answers part of the question.

If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:

SQL> show parameter sessions

This gives you an output like:

    NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size           integer     0
java_soft_sessionspace_limit         integer     0
license_max_sessions                 integer     0
license_sessions_warning             integer     0
sessions                             integer     248
shared_server_sessions               integer

The sessions parameter is the one what you want.

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

How to change XAMPP apache server port?

if don't work above port id then change it.like 8082,8080 Restart xammp,Start apache server,Check it.It's now working.

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

How do I return multiple values from a function?

I vote for the dictionary.

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

How do I get today's date in C# in mm/dd/yyyy format?

Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-

using System.Globalization;
using System.Threading;

...

var currentCulture = Thread.CurrentThread.CurrentCulture;
try {
  Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us");
  string shortDateString = DateTime.Now.ToShortDateString();
  // Do something with shortDateString...
} finally {
  Thread.CurrentThread.CurrentCulture = currentCulture;
}

Though clearly the "m/dd/yyyy" approach is considerably neater!!

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

What is __gxx_personality_v0 for?

I had this error once and I found out the origin:

I was using a gcc compiler and my file was called CLIENT.C despite I was doing a C program and not a C++ program.

gcc recognizes the .C extension as C++ program and .c extension as C program (be careful to the small c and big C).

So I renamed my file CLIENT.c program and it worked.

ActivityCompat.requestPermissions not showing dialog box

I had this same issue.I updated to buildToolsVersion "23.0.3" It all of a sudden worked. Hope this helps anyone having this issue.

Change Circle color of radio button

I had this problem. If your app has a black background and you have a lot of RadioButtons that are invisible due to the background, it is complicated to edit the android: buttonTint of each one, the best solution is to change the parent theme in your styles.xml file

I changed

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">

So the RadioButtons' circles became a lighter shade of gray and now they are visible even with a black background.

This is my style.xml file:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

String to byte array in php

You could try this:

$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
    $hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);

Access item in a list of lists

You can use itertools.cycle:

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sum would return something like this:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use zip here:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

Listing available com ports with Python

Works only on Windows:

import winreg
import itertools

def serial_ports() -> list:
    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)

    ports = []
    for i in itertools.count():
        try:
            ports.append(winreg.EnumValue(key, i)[1])
        except EnvironmentError:
            break

    return ports

if __name__ == "__main__":
    ports = serial_ports()

Testing the type of a DOM element in JavaScript

I usually get it from the toString() return value. It works in differently accessed DOM elements:

var a = document.querySelector('a');

var img = document.createElement('img');

document.body.innerHTML += '<div id="newthing"></div>';
var div = document.getElementById('newthing');

Object.prototype.toString.call(a);    // "[object HTMLAnchorElement]"
Object.prototype.toString.call(img);  // "[object HTMLImageElement]"
Object.prototype.toString.call(div);  // "[object HTMLDivElement]"

Then the relevant piece:

Object.prototype.toString.call(...).split(' ')[1].slice(0, -1);

It works in Chrome, FF, Opera, Edge, IE9+ (in older IE it return "[object Object]").

FAIL - Application at context path /Hello could not be started

Your web.xml ends with <web-app>, but must end with </web-app>

Which by the way is almost literally what the exception tells you.

How to use ArrayAdapter<myClass>

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

Elegant way to check for missing packages and install them?

Dason K. and I have the pacman package that can do this nicely. The function p_load in the package does this. The first line is just to ensure that pacman is installed.

if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)

No appenders could be found for logger(log4j)?

I had this problem too. I just forgot to mark the resources directory in IntelliJ IDEA

  1. Rightclick on your directory
  2. Mark directory as
  3. Resources root

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

You must be installing the latest version of php mysql in my case I am install php7.1-mysql

Try this

sudo apt-get install php7.1-mysql

I am using the latest version of laravel

What does the "map" method do in Ruby?

Using ruby 2.4 you can do the same thing using transform_values, this feature extracted from rails to ruby.

h = {a: 1, b: 2, c: 3}

h.transform_values { |v| v * 10 }
 #=> {a: 10, b: 20, c: 30}

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Changing the space between each item in Bootstrap navbar

You can change this in your CSS with the property padding:

.navbar-nav > li{
  padding-left:30px;
  padding-right:30px;
}

Also you can set margin

.navbar-nav > li{
  margin-left:30px;
  margin-right:30px;
}

Convert a string to an enum in C#

You have to use Enum.Parse to get the object value from Enum, after that you have to change the object value to specific enum value. Casting to enum value can be do by using Convert.ChangeType. Please have a look on following code snippet

public T ConvertStringValueToEnum<T>(string valueToParse){
    return Convert.ChangeType(Enum.Parse(typeof(T), valueToParse, true), typeof(T));
}

Select element by exact match of its content

I found a way that works for me. It is not 100% exact but it eliminates all strings that contain more than just the word I am looking for because I check for the string not containing individual spaces too. By the way you don't need these " ". jQuery knows you are looking for a string. Make sure you only have one space in the :contains( ) part otherwise it won't work.

<p>hello</p>
<p>hello world</p>
$('p:contains(hello):not(:contains( ))').css('font-weight', 'bold');

And yes I know it won't work if you have stuff like <p>helloworld</p>

Git: "Corrupt loose object"

I had the same problem (don't know why).

This fix requires access to an uncorrupted remote copy of the repository, and will keep your locally working copy intact.

But it has some drawbacks:

  • You will lose the record of any commits that were not pushed, and will have to recommit them.
  • You will lose any stashes.

The fix

Execute these commands from the parent directory above your repo (replace 'foo' with the name of your project folder):

  1. Create a backup of the corrupt directory:
    cp -R foo foo-backup
  2. Make a new clone of the remote repository to a new directory:
    git clone [email protected]:foo foo-newclone
  3. Delete the corrupt .git subdirectory:
    rm -rf foo/.git
  4. Move the newly cloned .git subdirectory into foo:
    mv foo-newclone/.git foo
  5. Delete the rest of the temporary new clone:
    rm -rf foo-newclone

On Windows you will need to use:

  • copy instead of cp -R
  • rmdir /S instead of rm -rf
  • move instead of mv

Now foo has its original .git subdirectory back, but all the local changes are still there. git status, commit, pull, push, etc. work again as they should.

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Windows equivalent of OS X Keychain?

If you are on windows got to control pannel -> windows Credentials

Div not expanding even with content inside

Putting a <br clear="all" /> after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}

How to increase heap size for jBoss server

On wildfly 8 and later, go to /bin/standalone.conf and put your JAVA_OPTS there, with all you need.

What are the differences between 'call-template' and 'apply-templates' in XSL?

xsl:apply-templates is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.

xsl:call-template on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.

So I use xsl:apply-templates if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be

<xsl:template match="foo">
  <bar>
    <xsl:apply-templates/>
  </bar>
</xsl:template>

whereas with xsl:call-template I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.

Edit:

As an additional remark to your specific question text:

<xsl:call-template name="nodes"/> 

This calls a template which is named 'nodes':

    <xsl:template name="nodes">...</xsl:template>

This is a different semantic than:

<xsl:apply-templates select="nodes"/>

...which applies all templates to all children of your current XML node whose name is 'nodes'.

Git command to show which specific files are ignored by .gitignore

Notes:


Also interesting (mentioned in qwertymk's answer), you can also use the git check-ignore -v command, at least on Unix (doesn't work in a CMD Windows session)

git check-ignore *
git check-ignore -v *

The second one displays the actual rule of the .gitignore which makes a file to be ignored in your git repo.
On Unix, using "What expands to all files in current directory recursively?" and a bash4+:

git check-ignore **/*

(or a find -exec command)

Note: https://stackoverflow.com/users/351947/Rafi B. suggests in the comments to avoid the (risky) globstar:

git check-ignore -v $(find . -type f -print)

Make sure to exclude the files from the .git/ subfolder though.


Original answer 42009)

git ls-files -i

should work, except its source code indicates:

if (show_ignored && !exc_given) {
                fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
                        argv[0]);

exc_given ?

It turns out it need one more parameter after the -i to actually list anything:

Try:

git ls-files -i --exclude-from=[Path_To_Your_Global].gitignore

(but that would only list your cached (non-ignored) object, with a filter, so that is not quite what you want)


Example:

$ cat .git/ignore
# ignore objects and archives, anywhere in the tree.
*.[oa]
$ cat Documentation/.gitignore
# ignore generated html files,
*.html
# except foo.html which is maintained by hand
!foo.html
$ git ls-files --ignored \
    --exclude='Documentation/*.[0-9]' \
    --exclude-from=.git/ignore \
    --exclude-per-directory=.gitignore

Actually, in my 'gitignore' file (called 'exclude'), I find a command line that could help you:

F:\prog\git\test\.git\info>type exclude
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

So....

git ls-files --ignored --exclude-from=.git/info/exclude
git ls-files -i --exclude-from=.git/info/exclude

git ls-files --others --ignored --exclude-standard
git ls-files -o -i --exclude-standard

should do the trick.

(Thanks to honzajde pointing out in the comments that git ls-files -o -i --exclude-from... does not include cached files: only git ls-files -i --exclude-from... (without -o) does.)

As mentioned in the ls-files man page, --others is the important part, in order to show you non-cached, non-committed, normally-ignored files.

--exclude_standard is not just a shortcut, but a way to include all standard "ignored patterns" settings.

exclude-standard
Add the standard git exclusions: .git/info/exclude, .gitignore in each directory, and the user's global exclusion file.

Vim for Windows - What do I type to save and exit from a file?

Press ESC to make sure you are out of the edit mode and then type:

:wq

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

Echo newline in Bash prints literal \n

I just use echo no arguments

echo "Hello"
echo
echo "World"

CSS background-image-opacity?

Try this trick .. use css shadow with (inset) option and make the deep 200px for example

Code:

box-shadow: inset 0px 0px 277px 3px #4c3f37;

.

Also for all browsers:

-moz-box-shadow: inset 0px 0px 47px 3px #4c3f37;
-webkit-box-shadow: inset 0px 0px 47px 3px #4c3f37;
box-shadow: inset 0px 0px 277px 3px #4c3f37;

and increase number to make fill your box :)

Enjoy!

PostgreSQL: How to change PostgreSQL user password?

To Change Password

 sudo -u postgres psql

then

\password postgres

now enter New Password and Confirm

then \q to exit

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Most efficient way to remove special characters from string

public string RemoveSpecial(string evalstr)
{
StringBuilder finalstr = new StringBuilder();
            foreach(char c in evalstr){
            int charassci = Convert.ToInt16(c);
            if (!(charassci >= 33 && charassci <= 47))// special char ???
             finalstr.append(c);
            }
return finalstr.ToString();
}

How to return the output of stored procedure into a variable in sql server

That depends on the nature of the information you want to return.

If it is a single integer value, you can use the return statement

 create proc myproc
 as 
 begin
     return 1
 end
 go
 declare @i int
 exec @i = myproc

If you have a non integer value, or a number of scalar values, you can use output parameters

create proc myproc
  @a int output,
  @b varchar(50) output
as
begin
  select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output

If you want to return a dataset, you can use insert exec

create proc myproc
as 
begin
     select name from sysobjects
end
go

declare @t table (name varchar(100))
insert @t (name)
exec myproc

You can even return a cursor but that's just horrid so I shan't give an example :)

Trigger event when user scroll to specific element - with jQuery

If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.

It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites

How to get the file-path of the currently executing javascript code

Refining upon the answers found here I came up with the following:

getCurrentScript.js

var getCurrentScript = function () {
  if (document.currentScript) {
    return document.currentScript.src;
  } else {
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length-1].src;

  }
};

module.exports = getCurrentScript;

getCurrentScriptPath.js

var getCurrentScript = require('./getCurrentScript');

var getCurrentScriptPath = function () {
  var script = getCurrentScript();
  var path = script.substring(0, script.lastIndexOf('/'));
  return path;
};

module.exports = getCurrentScriptPath;

BTW: I'm using CommonJS module format and bundling with webpack.

Get user info via Google API

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

How to insert an item into an array at a specific index (JavaScript)?

For proper functional programming and chaining purposes an invention of Array.prototype.insert() is essential. Actually splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array. So here it goes

_x000D_
_x000D_
Array.prototype.insert = function(i,...rest){_x000D_
  this.splice(i,0,...rest)_x000D_
  return this_x000D_
}_x000D_
_x000D_
var a = [3,4,8,9];_x000D_
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");
_x000D_
_x000D_
_x000D_

Well ok the above with the Array.prototype.splice() one mutates the original array and some might complain like "you shouldn't modify what doesn't belong to you" and that might turn out to be right as well. So for the public welfare i would like to give another Array.prototype.insert() which doesn't mutate the original array. Here it goes;

_x000D_
_x000D_
Array.prototype.insert = function(i,...rest){_x000D_
  return this.slice(0,i).concat(rest,this.slice(i));_x000D_
}_x000D_
_x000D_
var a = [3,4,8,9],_x000D_
    b = a.insert(2,5,6,7);_x000D_
console.log(JSON.stringify(a));_x000D_
console.log(JSON.stringify(b));
_x000D_
_x000D_
_x000D_

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Can you change what a symlink points to after it is created?

Wouldn't unlinking it and creating the new one do the same thing in the end anyway?

Create directory if it does not exist

I wanted to be able to easily let users create a default profile for PowerShell to override some settings, and ended up with the following one-liner (multiple statements yes, but can be pasted into PowerShell and executed at once, which was the main goal):

cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };

For readability, here's how I would do it in a .ps1 file instead:

cls; # Clear console to better notice the results
[string]$filePath = $profile; # Declared as string, to allow the use of texts without plings and still not fail.
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
if(!(Test-Path $filePath)) {
  New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
  $fileContents | Set-Content $filePath; # Creates a new file with the input
  Write-Host 'File created!';
}
else {
  Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
};

Swift: Convert enum value to String?

For anyone reading the example in "A Swift Tour" chapter of "The Swift Programming Language" and looking for a way to simplify the simpleDescription() method, converting the enum itself to String by doing String(self) will do it:

enum Rank: Int
{
    case Ace = 1 //required otherwise Ace will be 0
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() -> String {
        switch self {
            case .Ace, .Jack, .Queen, .King:
                return String(self).lowercaseString
            default:
                return String(self.rawValue)
        }
     }
 }

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db.

There is no default config file, so you will either need to specify this when starting mongod with:

 mongod --config /etc/mongodb.conf

.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.

Note: to check the dbpath and command-line options for a running mongod, connect via the mongo shell and run:

db.serverCmdLineOpts()

In particular, if a custom dbpath is set it will be the value of:

db.serverCmdLineOpts().parsed.dbpath           // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath   // MongoDB 2.6+

How can I select the record with the 2nd highest salary in database Oracle?

RANK and DENSE_RANK have already been suggested - depending on your requirements, you might also consider ROW_NUMBER():

select * from (
  select e.*, row_number() over (order by sal desc) rn from emp e
)
where rn = 2;

The difference between RANK(), DENSE_RANK() and ROW_NUMBER() boils down to:

  • ROW_NUMBER() always generates a unique ranking; if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings (randomly)
  • RANK() and DENSE_RANK() will give the same ranking to rows that cannot be distinguished by the ORDER BY clause
  • DENSE_RANK() will always generate a contiguous sequence of ranks (1,2,3,...), whereas RANK() will leave gaps after two or more rows with the same rank (think "Olympic Games": if two athletes win the gold medal, there is no second place, only third)

So, if you only want one employee (even if there are several with the 2nd highest salary), I'd recommend ROW_NUMBER().

How to get the value from the GET parameters?

Here's a short and simple function for getting a single param:

function getUrlParam(paramName) {
    var match = window.location.search.match("[?&]" + paramName + "(?:&|$|=([^&]*))");
    return match ? (match[1] ? decodeURIComponent(match[1]) : "") : null;
}

The handling of these special cases are consistent with URLSearchParams:

  • If the parameter is missing, null is returned.

  • If the parameter is present but there is no "=" (e.g. "?param"), "" is returned.

Note! If there is a chance that the parameter name can contain special URL or regex characters (e.g. if it comes from user input) you need to escape it. This can easily be done like this:

function getUrlParamWithSpecialName(paramName) {
    return getUrlParam(encodeURIComponent(paramName).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
}

How can I overwrite file contents with new content in PHP?

$fname = "database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("192.168.1.198", "localhost", $content);

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

Add Foreign Key to existing table

To add a foreign key (grade_id) to an existing table (users), follow the following steps:

ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);

"The page you are requesting cannot be served because of the extension configuration." error message

I fixed my issue on Windows 2012 server by Installing ALL WCF Features.

A) Server Manager > Manage[link top left] > Add Roles and Features

B) In Features > .Net Framework 4.5 Features > WCF Services

C) Check (enable) the features. I checked all.

D) Install

Read a file one line at a time in node.js?

If you want to read a file line by line and writing this in another:

var fs = require('fs');
var readline = require('readline');
var Stream = require('stream');

function readFileLineByLine(inputFile, outputFile) {

   var instream = fs.createReadStream(inputFile);
   var outstream = new Stream();
   outstream.readable = true;
   outstream.writable = true;

   var rl = readline.createInterface({
      input: instream,
      output: outstream,
      terminal: false
   });

   rl.on('line', function (line) {
        fs.appendFileSync(outputFile, line + '\n');
   });
};

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

Simple way to measure cell execution time in ipython notebook

An easier way is to use ExecuteTime plugin in jupyter_contrib_nbextensions package.

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

Resolving a Git conflict with binary files

To resolve by keeping the version in your current branch (ignore the version from the branch you are merging in), just add and commit the file:

git commit -a

To resolve by overwriting the version in your current branch with the version from the branch you are merging in, you need to retrieve that version into your working directory first, and then add/commit it:

git checkout otherbranch theconflictedfile
git commit -a

Explained in more detail

Unable to find velocity template resources

I faced the similar problem with intellij IDEA. you can use this

 VelocityEngine ve = new VelocityEngine();
    Properties props = new Properties();
    props.put("file.resource.loader.path", "/Users/Projects/Comparator/src/main/resources/");
    ve.init(props);

    Template t = ve.getTemplate("helloworld.vm");
    VelocityContext context = new VelocityContext();

Capture characters from standard input without waiting for enter to be pressed

#include <conio.h>

if (kbhit() != 0) {
    cout << getch() << endl;
}

This uses kbhit() to check if the keyboard is being pressed and uses getch() to get the character that is being pressed.

How do I concatenate strings?

When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str:

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{}", owned_string);
}

Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String, as &String can be dereferenced as &str.

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{}", owned_string);
}

After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{}", new_owned_string);
}

Note that owned_string is no longer accessible after the call to +.

What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{}{}", borrowed_string, another_borrowed_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{borrowed_string}{another_borrowed_string}");

    println!("{}", together);
}

Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String, we can use the fact that String also can be formatted:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{}{}", owned_string, another_owned_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

You don't have to use format! though. You can clone one string and append the other string to the new string:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!

How can I delete an item from an array in VB.NET?

This may be a lazy man's solution, but can't you just delete the contents of the index you want removed by reassigning their values to 0 or "" and then ignore/skip these empty array elements instead of recreating and copying arrays on and off?

How to write a CSS hack for IE 11?

You can use the following code inside the style tag:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

Below is an example that worked for me:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Please note that since (#nav li) and (#nav a) are outside of the @media screen ..., they are general styles.

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

Get path to execution directory of Windows Forms application

In VB.NET

Dim directory as String = My.Application.Info.DirectoryPath

In C#

string directory = AppDomain.CurrentDomain.BaseDirectory;

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

How can I get the source directory of a Bash script from within the script itself?

Here is an easy-to-remember script:

DIR="$(dirname "${BASH_SOURCE[0]}")"  # Get the directory name
DIR="$(realpath "${DIR}")"    # Resolve its full path if need be

How can I check the system version of Android?

Check android.os.Build.VERSION.

  • CODENAME: The current development codename, or the string "REL" if this is a release build.
  • INCREMENTAL: The internal value used by the underlying source control to represent this build.
  • RELEASE: The user-visible version string.

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

Nesting queries in SQL

You need to join the two tables and then filter the result in where clause:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

How do you get a string from a MemoryStream?

In this case, if you really want to use ReadToEnd method in MemoryStream in an easy way, you can use this Extension Method to achieve this:

public static class SetExtensions
{
    public static string ReadToEnd(this MemoryStream BASE)
    {
        BASE.Position = 0;
        StreamReader R = new StreamReader(BASE);
        return R.ReadToEnd();
    }
}

And you can use this method in this way:

using (MemoryStream m = new MemoryStream())
{
    //for example i want to serialize an object into MemoryStream
    //I want to use XmlSeralizer
    XmlSerializer xs = new XmlSerializer(_yourVariable.GetType());
    xs.Serialize(m, _yourVariable);

    //the easy way to use ReadToEnd method in MemoryStream
    MessageBox.Show(m.ReadToEnd());
}

Android Drawing Separator/Divider Line in Layout?

Simple solution

just add this code in your layout and replace 'Id_of__view_present_above' to the id of the view, below which you need the divider.

<TextView
  android:layout_width="match_parent"
  android:layout_height="1dp"
  android:background="#c0c0c0"
  android:id="@+id/your_id"
  android:layout_marginTop="16dp" 
  android:layout_below="@+id/Id_of__view_present_above"
/>

How to load assemblies in PowerShell?

You can load the whole *.dll assembly with

$Assembly = [System.Reflection.Assembly]::LoadFrom("C:\folder\file.dll");

Convert String to Uri

If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

val uri = myUriString.toUri()

To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

How to turn on front flash light programmatically in Android?

In API 23 or Higher (Android M, 6.0)

Turn On code

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; 
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);   //Turn ON
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

Turn OFF code

camManager.setTorchMode(cameraId, false);

And Permissions

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

ADDITIONAL EDIT

People still upvoting my answer so I decided to post additional code This was my solution for the problem back in the day:

public class FlashlightProvider {

private static final String TAG = FlashlightProvider.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;

public FlashlightProvider(Context context) {
    this.context = context;
}

private void turnFlashlightOn() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            String cameraId = null; 
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0];
                camManager.setTorchMode(cameraId, true);
            }
        } catch (CameraAccessException e) {
            Log.e(TAG, e.toString());
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
}

private void turnFlashlightOff() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            String cameraId;
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
                camManager.setTorchMode(cameraId, false);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        mCamera.setParameters(parameters);
        mCamera.stopPreview();
    }
}
}

How to set a value for a selectize.js input?

just ran into the same problem and solved it with the following line of code:

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

Google Maps v3 - limit viewable area and zoom level

This can be used to re-center the map to a specific location. Which is what I needed.

    var MapBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(35.676263, 13.949096),
    new google.maps.LatLng(36.204391, 14.89038));

    google.maps.event.addListener(GoogleMap, 'dragend', function ()
    {
        if (MapBounds.contains(GoogleMap.getCenter()))
        {
            return;
        }
        else
        {
            GoogleMap.setCenter(new google.maps.LatLng(35.920242, 14.428825));
        }
    });

What are 'get' and 'set' in Swift?

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue
     }
}

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

Can you remove elements from a std::list while iterating through it?

Removal invalidates only the iterators that point to the elements that are removed.

So in this case after removing *i , i is invalidated and you cannot do increment on it.

What you can do is first save the iterator of element that is to be removed , then increment the iterator and then remove the saved one.

How to increase Bootstrap Modal Width?

The simplest way to do it is:

$(".modal-dialog").css("width", "80%");

where we can specify the width of the modal in terms of percentage of the screen.

Here is a working example to demonstrate the same:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>_x000D_
  <script type="text/javascript">_x000D_
  $(document).ready(function () {_x000D_
    $(".modal-dialog").css("width", "90%");_x000D_
  });_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.

See: HttpURLConnection implementation

java : convert float to String and String to float

To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
    // treat 0 separately, it will cause problems on the below algorithm
    if (d == 0) {
        return "0.000000000000";
    }
    // find the number of digits above the decimal point
    double testD = Math.abs(d);
    int digitsBeforePoint = 0;
    while (testD >= 1) {
        // doesn't matter that this loses precision on the lower end
        testD /= 10d;
        ++digitsBeforePoint;
    }

    // create the decimal digits
    StringBuilder repr = new StringBuilder();
    // 10^ exponent to determine divisor and current decimal place
    int digitIndex = digitsBeforePoint;
    double dabs = Math.abs(d);
    while (digitIndex > 0) {
        // Recieves digit at current power of ten (= place in decimal number)
        long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
        repr.append(digit);
        --digitIndex;
    }

    // insert decimal point
    if (digitIndex == 0) {
        repr.append(".");
    }

    // remove any parts above the decimal point, they create accuracy problems
    long digit = 0;
    dabs -= (long)Math.floor(dabs);
    // Because of inaccuracy, move to entirely new system of computing digits after decimal place.
    while (digitIndex > -12) {
        // Shift decimal point one step to the right
        dabs *= 10d;
        final var oldDigit = digit;
        digit = (long)Math.floor(dabs) % 10;
        repr.append(digit);

        // This may avoid float inaccuracy at the very last decimal places.
        // However, in practice, inaccuracy is still as high as even Java itself reports.
        // dabs -= oldDigit * 10l;
        --digitIndex;
    }

    return repr.insert(0, d < 0 ? "-" : "").toString(); 
}

Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.

WorksheetFunction.CountA - not working post upgrade to Office 2010

I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:

  1. It appears you are relying on VBA to determine variable types and modify accordingly. This can get confusing if you are not careful, because VBA may assign a variable type you did not intend. In your code, a type of Range should be assigned to myRange. Since a Range type is an object in VBA it needs to be Set, like this: Set myRange = Range("A:A")
  2. Your use of the worksheet function CountA() should be called with .WorksheetFunction

If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim statements, as I have done below.

The following code works for me in 2010. Hopefully it works for you too:

Dim myRange As Range
Dim NumRows As Integer

Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)

Good Luck.

Is there a "do ... while" loop in Ruby?

Like this:

people = []

begin
  info = gets.chomp
  people += [Person.new(info)] if not info.empty?
end while not info.empty?

Reference: Ruby's Hidden do {} while () Loop

Select Multiple Fields from List in Linq

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}

How to comment in Vim's config files: ".vimrc"?

A double quote to the left of the text you want to comment.

Example: " this is how a comment looks like in ~/.vimrc

How to find sum of multiple columns in a table in SQL Server 2005?

Hi You can use a simple query,

select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In case you need to insert a new row,

insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In order to update,

update emp set total = val1+val2+val3;

This will update for all comumns

What is the (function() { } )() construct in JavaScript?

Self-executing anonymous function. It's executed as soon as it is created.

One short and dummy example where this is useful is:

function prepareList(el){
  var list = (function(){
    var l = []; 
    for(var i = 0; i < 9; i++){
     l.push(i);
    }
    return l;
  })();

  return function (el){
    for(var i = 0, l = list.length; i < l; i++){
      if(list[i] == el) return list[i];
    }
    return null;
  }; 
} 

var search = prepareList();
search(2);
search(3);

So instead of creating a list each time, you create it only once (less overhead).

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

How to enable cURL in PHP / XAMPP

Actually I did it by uncommenting extension=php_curl.dll in the xampp\apache\bin\php.ini file.

How to handle onchange event on input type=file in jQuery?

 $('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});

You can use this one also

How to print a groupby object

In python 3

k = None
for name_of_the_group, group in dict(df_group):
    if(k != name_of_the_group):
        print ('\n', name_of_the_group)
        print('..........','\n')
    print (group)
    k = name_of_the_group

In more interactive way

What does a circled plus mean?

That's the XOR operator, not the PLUS operator

XOR works bit by bit, without carrying over like PLUS does

1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 0 = 0
0 XOR 1 = 1

How can I get the concatenation of two lists in Python without modifying either one?

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

php execute a background process

If you are looking to execute a background process via PHP, pipe the command's output to /dev/null and add & to the end of the command.

exec("bg_process > /dev/null &");

Note that you can not utilize the $output parameter of exec() or else PHP will hang (probably until the process completes).

How to install CocoaPods?

1.First open your terminal

2.Then update your gem file with command

sudo gem install -n /usr/local/bin cocoapods

3.Then give your project path

cd /your project path 

4.Touch the podifle

touch podfile

5.Open your podfile

open -e podfile

6.It will open a podfile like a text edit. Then set your target. For example if you want to set up Google maps then your podfile should be like

use_frameworks!
target 'yourProjectName' do
    pod 'GoogleMaps'
end

7.Then install the pod

pod install

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

Iterating over dictionaries using 'for' loops

When you iterate through dictionaries using the for .. in ..-syntax, it always iterates over the keys (the values are accessible using dictionary[key]).

To iterate over key-value pairs, in Python 2 use for k,v in s.iteritems(), and in Python 3 for k,v in s.items().

IIS 7, HttpHandler and HTTP Error 500.21

It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.

You can learn more about modules, handlers and IIS modes in the following blog post:

IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions

For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.

Add a pipe separator after items in an unordered list unless that item is the last on a line

This is possible with flex-box

The keys to this technique:

  • A container element set to overflow: hidden.
  • Set justify-content: space-between on the ul (which is a flex-box) to force its flex-items to stretch to the left and right edges.
  • Set margin-left: -1px on the ul to cause its left edge to overflow the container.
  • Set border-left: 1px on the li flex-items.

The container acts as a mask hiding the borders of any flex-items touching its left edge.

_x000D_
_x000D_
.flex-list {
    position: relative;
    margin: 1em;
    overflow: hidden;
}
.flex-list ul {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-left: -1px;
}
.flex-list li {
    flex-grow: 1;
    flex-basis: auto;
    margin: .25em 0;
    padding: 0 1em;
    text-align: center;
    border-left: 1px solid #ccc;
    background-color: #fff;
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
<div class="flex-list">
    <ul>
        <li>Dogs</li>
        <li>Cats</li>
        <li>Lions</li>
        <li>Tigers</li>
        <li>Zebras</li>
        <li>Giraffes</li>
        <li>Bears</li>
        <li>Hippopotamuses</li>
        <li>Antelopes</li>
        <li>Unicorns</li>
        <li>Seagulls</li>
    </ul>
</div>
_x000D_
_x000D_
_x000D_

How can I start an interactive console for Perl?

I think you're asking about a REPL (Read, Evaluate, Print, Loop) interface to perl. There are a few ways to do this:

  • Matt Trout has an article that describes how to write one
  • Adriano Ferreira has described some options
  • and finally, you can hop on IRC at irc.perl.org and try out one of the eval bots in many of the popular channels. They will evaluate chunks of perl that you pass to them.

Firefox 'Cross-Origin Request Blocked' despite headers

Just add

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

to the .htaccess file in the root of the website you are trying to connect with.

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

.bashrc at ssh login

.bashrc is not sourced when you log in using SSH. You need to source it in your .bash_profile like this:

if [ -f ~/.bashrc ]; then
  . ~/.bashrc
fi

Binding a Button's visibility to a bool value in ViewModel

In View:

<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>

In view Model:

public _advancedFormat = Visibility.visible (whatever you start with)

public Visibility AdvancedFormat
{
 get{return _advancedFormat;}
 set{
   _advancedFormat = value;
   //raise property changed here
}

You will need to have a property changed event

 protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
        PropertyChanged.Raise(this, e); 
    } 

    protected void OnPropertyChanged(string propertyName) 
    { 
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

This is how they use Model-view-viewmodel

But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.

Using the rJava package on Win7 64 bit with R

I need to have a 32 bit JRE available for my browser, but 64 bit JRE for R and rJava. The 32 bit JRE is installed in the default location. After some experimentation, I found that I only needed one of misterbee's suggestions to get rJava (version 0.9-6) working for me. All I did was add the path to my 64 bit java installation:

C:\apps\Java\jre\bin\server\jvm.dll

to the top of my path environment variable (your path will likely be different) and remove my JAVA_HOME as user2161065 suggested. I put this just ahead of the entry

C:\ProgramData\Oracle\Java\javapath

which the Oracle installer inserts at the top of the path and points to some symlinks to the 32 bit JRE. By adding the entry to 64 bit jvm.dll, looks like rJava could find what it needs.

Conda activate not working?

To use "conda activate" via Windows CMD, not the Anaconda Prompt:
(in response to okorng's question, although using the Anaconda Prompt is the preferred option)

First, we need to add the activate.bat script to your path:
Via CMD:

set PATH=%PATH%;<your_path_to_anaconda_installation>\Scripts

Or via Control Panel, open "User Accounts" and choose "Change my environment variables".

Then calling directly from Windows CMD:

activate <environment_name>

without using the prefix "conda".

(Tested on Windows 7 Enterprise with Anaconda3-5.2.0)

How to check if a URL exists or returns 404 with Java?

Based on the given answers and information in the question, this is the code you should use:

public static boolean doesURLExist(URL url) throws IOException
{
    // We want to check the current URL
    HttpURLConnection.setFollowRedirects(false);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    // We don't need to get data
    httpURLConnection.setRequestMethod("HEAD");

    // Some websites don't like programmatic access so pretend to be a browser
    httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    int responseCode = httpURLConnection.getResponseCode();

    // We only accept response code 200
    return responseCode == HttpURLConnection.HTTP_OK;
}

Of course tested and working.

How to run a maven created jar file using just the command line

Just use the exec-maven-plugin.

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>com.example.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Then you run you program:

mvn exec:java

Best way to detect when a user leaves a web page?

Mozilla Developer Network has a nice description and example of onbeforeunload.

If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

Conversion from 12 hours time to 24 hours time in java

Try this to calculate time difference between two times.

first it will convert 12 hours time into 24 hours then it will take diff between two times

String a = "09/06/18 01:55:33 AM";
            String b = "07/06/18 05:45:33 PM";
            String [] b2 = b.split(" ");
            String [] a2 = a.split(" ");
            SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
            SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
            String time1 = null ;
            String time2 = null ;
            if ( a.contains("PM") && b.contains("AM")) {
                 
                 Date date = parseFormat.parse(a2[1]+" PM");
                 time1 = displayFormat.format(date);
                 time2 = b2[1];
            }else if (b.contains("PM") && a.contains("AM")) {
                Date date = parseFormat.parse(a2[1]+" PM");
                time1 = a2[1];
                time2 = displayFormat.format(date);
            }else if (a.contains("PM") && b.contains("PM")){
                Date datea = parseFormat.parse(a2[1]+" PM");
                Date dateb = parseFormat.parse(b2[1]+" PM");
                time1 = displayFormat.format(datea);
                time2 = displayFormat.format(dateb);
            }   
            System.out.println(time1);
            System.out.println(time2);      
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
            Date date1 = format.parse(time1);
            Date date2 = format.parse(time2);
            long difference = date2.getTime() - date1.getTime(); 
            System.out.println(difference);
            System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));

For More Details Click Here

Django - after login, redirect user to his custom page --> mysite.com/username

You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in

This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.

Creating a constant Dictionary in C#

There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:

Use Enumerable.ToLookup() - the Lookup<,> class is immutable (but multi-valued on the rhs); you can do this from a Dictionary<,> quite easily:

    Dictionary<string, int> ids = new Dictionary<string, int> {
      {"abc",1}, {"def",2}, {"ghi",3}
    };
    ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
    int i = lookup["def"].Single();

Gaussian fit for Python

Actually, you do not need to do a first guess. Simply doing

import matplotlib.pyplot as plt  
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)

P.S.: use numpy.exp() better, says a warning of scipy

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

.m2 , settings.xml in Ubuntu

.m2 directory on linux box usually would be $HOME/.m2

you could get the $HOME :

echo $HOME

or simply:

cd <enter>

to go to your home directory.

other information from maven site: http://maven.apache.org/download.html#Installation

Does a finally block always get executed in Java?

Yes, it will. No matter what happens in your try or catch block unless otherwise System.exit() called or JVM crashed. if there is any return statement in the block(s),finally will be executed prior to that return statement.

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to use shared memory with Linux in C

There are two approaches: shmget and mmap. I'll talk about mmap, since it's more modern and flexible, but you can take a look at man shmget (or this tutorial) if you'd rather use the old-style tools.

The mmap() function can be used to allocate memory buffers with highly customizable parameters to control access and permissions, and to back them with file-system storage if necessary.

The following function creates an in-memory buffer that a process can share with its children:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

void* create_shared_memory(size_t size) {
  // Our memory buffer will be readable and writable:
  int protection = PROT_READ | PROT_WRITE;

  // The buffer will be shared (meaning other processes can access it), but
  // anonymous (meaning third-party processes cannot obtain an address for it),
  // so only this process and its children will be able to use it:
  int visibility = MAP_SHARED | MAP_ANONYMOUS;

  // The remaining parameters to `mmap()` are not important for this use case,
  // but the manpage for `mmap` explains their purpose.
  return mmap(NULL, size, protection, visibility, -1, 0);
}

The following is an example program that uses the function defined above to allocate a buffer. The parent process will write a message, fork, and then wait for its child to modify the buffer. Both processes can read and write the shared memory.

#include <string.h>
#include <unistd.h>

int main() {
  char parent_message[] = "hello";  // parent process will write this message
  char child_message[] = "goodbye"; // child process will then write this one

  void* shmem = create_shared_memory(128);

  memcpy(shmem, parent_message, sizeof(parent_message));

  int pid = fork();

  if (pid == 0) {
    printf("Child read: %s\n", shmem);
    memcpy(shmem, child_message, sizeof(child_message));
    printf("Child wrote: %s\n", shmem);

  } else {
    printf("Parent read: %s\n", shmem);
    sleep(1);
    printf("After 1s, parent read: %s\n", shmem);
  }
}

c++ custom compare function for std::sort()

Your comparison function is not even wrong.

Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

You need to model the less-than operator, not strcmp or memcmp style comparisons.

See StrictWeakOrdering which describes the properties the function must meet.

ImportError: No module named 'selenium'

Your IDE might be pointing to a different installation of Python than where Selenium is installed.

I'm using Eclipse and when I ran 'quick auto-configure' under:

Preferences > PyDev > Interpreters > Python Interpreter

it pointed to a different version of Python than where pip or easy_install actually installed it.

Selenium worked from the Terminal so I determined which version of python my Terminal was using by running this:

python -c "import sys; print(sys.path)"

then had Eclipse point to that same location, which for me on my 10.11 Mac was here:

/Library/Frameworks/Python.framework/Versions/Current/bin/python2.7/

You can run "Advanced Auto-Config" as well to see all of the installed versions of python and select the one you want to use. When I selected that same location using "Advanced Auto-Config" it finally showed me the Selenium folder as it went through the configuration steps.

Remove border radius from Select tag in bootstrap 3

I had the same issue and while user1732055's answer fixes the border, it removes the dropdown arrows. I solved this by removing the border from the select element and creating a wrapper span which has a border.

html:

<span class="select-wrapper">
    <select class="form-control no-radius">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
</span>

css:

select.no-radius{
    border:none;
}    
.select-wrapper{
    border: 1px solid black;
    border-radius: 0px;
}

https://jsfiddle.net/Lrqh0drd/6/

Compare two objects' properties to find differences?

Comparing two objects of the same type using LINQ and Reflection. NB! This is basically a rewrite of the solution from Jon Skeet, but with a more compact and modern syntax. It should also generate slightly more effecticve IL.

It goes something like this:

public bool ReflectiveEquals(LocalHdTicket serverTicket, LocalHdTicket localTicket)
  {
     if (serverTicket == null && localTicket == null) return true;
     if (serverTicket == null || localTicket == null) return false;

     var firstType = serverTicket.GetType();
     // Handle type mismatch anyway you please:
     if(localTicket.GetType() != firstType) throw new Exception("Trying to compare two different object types!");

     return !(from propertyInfo in firstType.GetProperties() 
              where propertyInfo.CanRead 
              let serverValue = propertyInfo.GetValue(serverTicket, null) 
              let localValue = propertyInfo.GetValue(localTicket, null) 
              where !Equals(serverValue, localValue) 
              select serverValue).Any();
  }

What is Func, how and when is it used

Aforementioned answers are great, just putting few points I see might be helpful:

  • Func is built-in delegate type

  • Func delegate type must return a value. Use Action delegate if no return type needed.

  • Func delegate type can have zero to 16 input parameters.

  • Func delegate does not allow ref and out parameters.

  • Func delegate type can be used with an anonymous method or lambda expression.

    Func<int, int, int> Sum = (x, y) => x + y;

How can I hide or encrypt JavaScript code?

JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.

The only way to partially hide it, at least from the less technical minds, is to obfuscate.

Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.

Java Ordered Map

LinkedHashMap maintains the order of the keys.

java.util.LinkedHashMap appears to work just like a normal HashMap otherwise.

Using jquery to get all checked checkboxes with a certain class name

A simple way to get the ids of the checked check boxes by class name:

$(".yourClassName:checkbox:checked").each(function() {
     console.log($(this).attr("id"));
});

GitHub: How to make a fork of public repository private?

The current answers are a bit out of date so, for clarity:

The short answer is:

  1. Do a bare clone of the public repo.
  2. Create a new private one.
  3. Do a mirror push to the new private one.

This is documented on GitHub: duplicating-a-repository

Getting "cannot find Symbol" in Java project in Intellij

I had the same problem, and turns out I had never completely compiled the fresh project. So right-clicking and selecting Compile'' (shift-cmd-F9 on mac) fixed it. It seems the compile on save does not 'see' non-compiled files.

Marking the src folder as source did not help in my case.

How can I represent an infinite number in Python?

Another, less convenient, way to do it is to use Decimal class:

from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')

How can I throw a general exception in Java?

It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");

Finding the layers and layer sizes for each Docker image

This will inspect the docker image and print the layers:

$ docker image inspect nginx -f '{{.RootFS.Layers}}'
[sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659 sha256:82b81d779f8352b20e52295afc6d0eab7e61c0ec7af96d85b8cda7800285d97d sha256:7ab428981537aa7d0c79bc1acbf208c71e57d9678f7deca4267cc03fba26b9c8]

Characters allowed in a URL

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding)

http://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters

says these are RFC 3986 unreserved characters (sec. 2.3) as well as reserved characters (sec 2.2) if they need to retain their special meaning. And also a percent character as part of a percent-encoding.

How to parse unix timestamp to time.Time

I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:

func dateFormat(layout string, d float64) string{
    intTime := int64(d)
    t := time.Unix(intTime, 0)
    if layout == "" {
        layout = "2006-01-02 15:04:05"
    }
    return t.Format(layout)
}

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

Trust Store vs Key Store - creating with keytool

There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore. But in theory it's fine to use one and the same file for trust- and keystores.

Sorting arrays in NumPy by column

Here is another solution considering all columns (more compact way of J.J's answer);

ar=np.array([[0, 0, 0, 1],
             [1, 0, 1, 0],
             [0, 1, 0, 0],
             [1, 0, 0, 1],
             [0, 0, 1, 0],
             [1, 1, 0, 0]])

Sort with lexsort,

ar[np.lexsort(([ar[:, i] for i in range(ar.shape[1]-1, -1, -1)]))]

Output:

array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 1, 0, 0],
       [1, 0, 0, 1],
       [1, 0, 1, 0],
       [1, 1, 0, 0]])

How can I create a Java method that accepts a variable number of arguments?

You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

Where should I put the CSS and Javascript code in an HTML webpage?

And if you have more than one .css or .js file to call, just include them one after another, or:

<head>

<link href="css/grid.css" rel="stylesheet" />

<link href="css/style.css" rel="stylesheet" />

<script src="js/jquery-1.4.4.min.js"></script>

<script src="js/jquery.animate-colors-min.js"></script>

</head>

Can't install Scipy through pip

This is an alternative to pip. I also had the same error when installing scipy with pip.

Then I downloaded and installed MiniConda. And then I used the below command to install pytables.

conda install -c conda-forge scipy

Please refer the below screenshot.

enter image description here

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

Role/Purpose of ContextLoaderListener in Spring?

Basically you can isolate your root application context and web application context using ContextLoaderListner.

The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.

In any web application we may have multiple dispatcher servlets, so multiple web application contexts.

But in any web application we may have only one root application context that is shared with all web application contexts.

We should define our common services, entities, aspects etc in root application context. And controllers, interceptors etc are in relevant web application context.

A sample web.xml is

<!-- language: xml -->
<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>example.config.AppConfig</param-value>
    </context-param>
    <servlet>
        <servlet-name>restEntryPoint</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>example.config.RestConfig</param-value>
        </init-param>       
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>restEntryPoint</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>webEntryPoint</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>example.config.WebConfig</param-value>
        </init-param>       
        <load-on-startup>1</load-on-startup>
    </servlet>  
    <servlet-mapping>
        <servlet-name>webEntryPoint</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app> 

Here config class example.config.AppConfig can be used to configure services, entities, aspects etc in root application context that will be shared with all other web application contexts (for example here we have two web application context config classes RestConfig and WebConfig)

PS: Here ContextLoaderListener is completely optional. If we will not mention ContextLoaderListener in web.xml here, AppConfig will not work. In that case we need to configure all our services and entities in WebConfig and Rest Config.

System.Data.OracleClient requires Oracle client software version 8.1.7

Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.

Spring @Transactional read-only propagation

First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.

If you specify readOnly as true, the flush mode will be set as FlushMode.NEVER in the current Hibernate Session preventing the session from committing the transaction.

Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER, but it's stronger since you cannot even flush manually.

Now let's see how transaction propagation works.

If you don't explicitly set readOnly to true, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.

OK, we're almost there. Let's see what brings readOnly into this scenario.

If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.

Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.

In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Try placing the desired java directory in PATH before not needed java directories in your PATH.

Delete many rows from a table using id in Mysql

if you need to keep only a few rows, consider

DELETE FROM tablename WHERE id NOT IN (5,124,221);

This will keep only some records and discard others.

CSS @font-face not working with Firefox, but working with Chrome and IE

I had a similar problem. The fontsquirel demo page was working in FF but not my own page even though all files were coming from the same domain!

It turned out that I was linking my stylesheet with an absolute URL (http://example.com/style.css) so FF thought it was coming from a different domain. Changing my stylesheet link href to /style.css instead fixed things for me.

How can I read input from the console using the Scanner class in Java?

A simple example:

import java.util.Scanner;

public class Example
{
    public static void main(String[] args)
    {
        int number1, number2, sum;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter First multiple");
        number1 = input.nextInt();

        System.out.println("Enter second multiple");
        number2 = input.nextInt();

        sum = number1 * number2;

        System.out.printf("The product of both number is %d", sum);
    }
}

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

In iTerm -> Preferences -> Profiles Tab -> General section set Command to: /bin/zsh --login

/bin/zsh --login

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I was having the same problem, the fact is that the input of lat and long should be String. Only then did I manage.

for example:

Controller.

 ViewBag.Lat = object.Lat.ToString().Replace(",", ".");

 ViewBag.Lng = object.Lng.ToString().Replace(",", ".");

View - function javascript

<script>
    function initMap() {
        var myLatLng = { lat: @ViewBag.Lat, lng: @ViewBag.Lng};

        // Create a map object and specify the DOM element for display.
        var map = new window.google.maps.Map(document.getElementById('map'),
        {
            center: myLatLng,
            scrollwheel: false,
            zoom: 16
        });

        // Create a marker and set its position.
        var marker = new window.google.maps.Marker({
            map: map,
            position: myLatLng
            //title: "Blue"
        });
    }
</script>

I convert the double value to string and do a Replace in the ',' to '.' And so everything works normally.

Changing image size in Markdown

You could use this one as well with kramdown:

markdown
![drawing](drawing.jpg)   
{:.some-css-class style="width: 200px"}

or

markdown
![drawing](drawing.jpg)   
{:.some-css-class width="200"}

This way you can directly add arbitrary attributes to the last html element. To add classes there is a shortcut .class.secondclass.

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

Instead you will receive callback on onRequestPermissionsResult() as PERMISSION_DENIED when you request permission again while falling in false condition of shouldShowRequestPermissionRationale()

From Android doc:

When the system asks the user to grant a permission, the user has the option of telling the system not to ask for that permission again. In that case, any time an app uses requestPermissions() to ask for that permission again, the system immediately denies the request. The system calls your onRequestPermissionsResult() callback method and passes PERMISSION_DENIED, the same way it would if the user had explicitly rejected your request again. This means that when you call requestPermissions(), you cannot assume that any direct interaction with the user has taken place.

Error using eclipse for Android - No resource found that matches the given name

Project ---> Clean does the trick in most of the cases. It did in mine.

Python convert decimal to hex

It is good to write your own functions for conversions between numeral systems to learn something. For "real" code I would recommend to use build in conversion function from Python like bin(x), hex(x), int(x). Some examples can be found here.

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Read entire file in Scala?

print every line, like use Java BufferedReader read ervery line, and print it:

scala.io.Source.fromFile("test.txt" ).foreach{  print  }

equivalent:

scala.io.Source.fromFile("test.txt" ).foreach( x => print(x))