Langford sequence implementation Haskell or C

Question: In combinatorial mathematics, a Langford pairing, also called a Langford sequence, is a permutation of the sequence of 2n numbers 1, 1, 2, 2, ..., n,n in which the two ones are one unit apart, the two twos are two units apart, and more generally the two copies of each number k are k units apart.
For example:
Langford pairing for n = 3 is given by the sequence 2,3,1,2,1,3.

What is a good method to solve this in haskell or C
Can you suggest an algorithm to solve it (Do not want to use brute force)?

--------------------------EDIT----------------------
How could we define the mathematical rules to put @Rafe's code in haskell
Comment: When trying to solve this problem, I wrote this [correctness checker](http://www.codecatalog.net/241/).  Hard problem.
Comment: The algorithm should be relatively independent of the language in use. (And besides, if this is more than an educational exercise, you're propably better off just using readily-calculated solutions)
Comment: Here's a Perl program that you might want to study: http://legacy.lclark.edu/~miller/langford/ROD.pl
Comment: According to wikipedia, this is an exact cover problem, which are NP complete in general.  I am not sure if that result applies to this particular problem.
Comment: Integer programming might be useful here.
Comment: How could I use Integer Programming, could ypu describe it a little more?
Comment: @luqui use an SMT solver DSL?
Comment: http://www.amsterdamoptimization.com/pdf/langford.pdf
Comment: I have found this paper http://home.comcast.net/~mrtwhs/vita/langford.pdf
Answer: You want to find an assignment to the variables {p1, p2, ..., pn} (where pi is the position of the first occurrence of 'i') with the following constraints holding for each pi:

pi in 1..(1+n-i)
if pi = k then forall pj where j != i
pj != k
pj != k + i
pj != k - j
pj != k + i - j

You need a sensible search strategy here.  A good choice is to at each choice point choose the pi with the smallest remaining set of possible values.
Cheers!
[EDIT: second addendum.]
This is a "mostly functional" version of the imperative version I first wrote (see first addendum below).  It's mostly functional in the sense that the state associated with each vertex in the search tree is independent of all other state, hence there's no need for a trail or machinery of that kind.  However, I have used imperative code to implement the construction of each new domain set from a copy of the parent domain set.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MostlyFunctionalLangford
{
    class Program
    {
        // An (effectively functional) program to compute Langford sequences.
        static void Main(string[] args)
        {
            var n = 7;
            var DInit = InitLangford(n);
            var DSoln = Search(DInit);
            if (DSoln != null)
            {
                Console.WriteLine();
                Console.WriteLine("Solution for n = {0}:", n);
                WriteSolution(DSoln);
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("No solution for n = {0}.", n);
            }
            Console.Read();
        }

        // The largest integer in the Langford sequence we are looking for.
        // [I could infer N from the size of the domain array, but this is neater.]
        static int N;

        // ---- Integer domain manipulation. ----

        // Find the least bit in a domain; return 0 if the domain is empty.
        private static long LeastBitInDomain(long d)
        {
            return d & ~(d - 1);
        }

        // Remove a bit from a domain.
        private static long RemoveBitFromDomain(long d, long b)
        {
            return d & ~b;
        }

        private static bool DomainIsEmpty(long d)
        {
            return d == 0;
        }

        private static bool DomainIsSingleton(long d)
        {
            return (d == LeastBitInDomain(d));
        }

        // Return the size of a domain.
        private static int DomainSize(long d)
        {
            var size = 0;
            while (!DomainIsEmpty(d))
            {
                d = RemoveBitFromDomain(d, LeastBitInDomain(d));
                size++;
            }
            return size;
        }

        // Find the k with the smallest non-singleton domain D[k].
        // Returns zero if none exists.
        private static int SmallestUndecidedDomainIndex(long[] D)
        {
            var bestK = 0;
            var bestKSize = int.MaxValue;
            for (var k = 1; k <= N && 2 < bestKSize; k++)
            {
                var kSize = DomainSize(D[k]);
                if (2 <= kSize && kSize < bestKSize)
                {
                    bestK = k;
                    bestKSize = kSize;
                }
            }
            return bestK;
        }

        // Obtain a copy of a domain.
        private static long[] CopyOfDomain(long[] D)
        {
            var DCopy = new long[N + 1];
            for (var i = 1; i <= N; i++) DCopy[i] = D[i];
            return DCopy;
        }

        // Destructively prune a domain by setting D[k] = {b}.
        // Returns false iff this exhausts some domain.
        private static bool Prune(long[] D, int k, long b)
        {
            for (var j = 1; j <= N; j++)
            {
                if (j == k)
                {
                    D[j] = b;
                }
                else
                {
                    var dj = D[j];
                    dj = RemoveBitFromDomain(dj, b);
                    dj = RemoveBitFromDomain(dj, b << (k + 1));
                    dj = RemoveBitFromDomain(dj, b >> (j + 1));
                    dj = RemoveBitFromDomain(dj, (b << (k + 1)) >> (j + 1));
                    if (DomainIsEmpty(dj)) return false;
                    if (dj != D[j] && DomainIsSingleton(dj) && !Prune(D, j, dj)) return false;
                }
            }
            return true;
        }

        // Search for a solution from a given set of domains.
        // Returns the solution domain on success.
        // Returns null on failure.
        private static long[] Search(long[] D)
        {
            var k = SmallestUndecidedDomainIndex(D);
            if (k == 0) return D;

            // Branch on k, trying each possible assignment.
            var dk = D[k];
            while (!DomainIsEmpty(dk))
            {
                var b = LeastBitInDomain(dk);
                dk = RemoveBitFromDomain(dk, b);
                var DKeqB = CopyOfDomain(D);
                if (Prune(DKeqB, k, b))
                {
                    var DSoln = Search(DKeqB);
                    if (DSoln != null) return DSoln;
                }
            }

            // Search failed.
            return null;
        }

        // Set up the problem.
        private static long[] InitLangford(int n)
        {
            N = n;
            var D = new long[N + 1];
            var bs = (1L << (N + N - 1)) - 1;
            for (var k = 1; k <= N; k++)
            {
                D[k] = bs & ~1;
                bs >>= 1;
            }
            return D;
        }

        // Print out a solution.
        private static void WriteSolution(long[] D)
        {
            var l = new int[N + N + 1];
            for (var k = 1; k <= N; k++)
            {
                for (var i = 1; i <= N + N; i++)
                {
                    if (D[k] == 1L << i)
                    {
                        l[i] = k;
                        l[i + k + 1] = k;
                    }
                }
            }
            for (var i = 1; i < l.Length; i++)
            {
                Console.Write("{0} ", l[i]);
            }
            Console.WriteLine();
        }
    }
}

[EDIT: first addendum.]
I decided to write a C# program to solve Langford problems.  It runs very quickly up to n = 16, but thereafter you need to change it to use longs since it represents domains as bit patterns.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Langford
{
    // Compute Langford sequences.  A Langford sequence L(n) is a permutation of [1, 1, 2, 2, ..., n, n] such
    // that the pair of 1s is separated by 1 place, the pair of 2s is separated by 2 places, and so forth.
    //
    class Program
    {
        static void Main(string[] args)
        {
            var n = 16;
            InitLangford(n);
            WriteDomains();
            if (FindSolution())
            {
                Console.WriteLine();
                Console.WriteLine("Solution for n = {0}:", n);
                WriteDomains();
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("No solution for n = {0}.", n);
            }
            Console.Read();
        }

        // The n in L(n).
        private static int N;

        // D[k] is the set of unexcluded possible positions in the solution of the first k for each pair of ks.
        // Each domain is represented as a bit pattern, where bit i is set iff i is in D[k].
        private static int[] D;

        // The trail records domain changes to undo on backtracking.  T[2k] gives the element in D to undo;
        // T[2k+1] gives the value to which it must be restored.
        private static List<int> T = new List<int> { };

        // This is the index of the next unused entry in the trail.
        private static int TTop;

        // Extend the trail to restore D[k] on backtracking.
        private static void TrailDomainValue(int k)
        {
            if (TTop == T.Count)
            {
                T.Add(0);
                T.Add(0);
            }
            T[TTop++] = k;
            T[TTop++] = D[k];
        }

        // Undo the trail to some earlier point.
        private static void UntrailTo(int checkPoint)
        {
            //Console.WriteLine("Backtracking...");

            while (TTop != checkPoint)
            {
                var d = T[--TTop];
                var k = T[--TTop];
                D[k] = d;
            }
        }

        // Find the least bit in a domain; return 0 if the domain is empty.
        private static int LeastBitInDomain(int d)
        {
            return d & ~(d - 1);
        }

        // Remove a bit from a domain.
        private static int RemoveBitFromDomain(int d, int b)
        {
            return d & ~b;
        }

        private static bool DomainIsEmpty(int d)
        {
            return d == 0;
        }

        private static bool DomainIsSingleton(int d)
        {
            return (d == LeastBitInDomain(d));
        }

        // Return the size of a domain.
        private static int DomainSize(int d)
        {
            var size = 0;
            while (!DomainIsEmpty(d))
            {
                d = RemoveBitFromDomain(d, LeastBitInDomain(d));
                size++;
            }
            return size;
        }

        // Find the k with the smallest non-singleton domain D[k].
        // Returns zero if none exists.
        private static int SmallestUndecidedDomainIndex()
        {
            var bestK = 0;
            var bestKSize = int.MaxValue;
            for (var k = 1; k <= N && 2 < bestKSize; k++)
            {
                var kSize = DomainSize(D[k]);
                if (2 <= kSize && kSize < bestKSize)
                {
                    bestK = k;
                    bestKSize = kSize;
                }
            }
            return bestK;
        }

        // Prune the other domains when domain k is reduced to a singleton.
        // Return false iff this exhausts some domain.
        private static bool Prune(int k)
        {
            var newSingletons = new Queue<int>();
            newSingletons.Enqueue(k);

            while (newSingletons.Count != 0)
            {
                k = newSingletons.Dequeue();

                //Console.WriteLine("Pruning from domain {0}.", k);

                var b = D[k];
                for (var j = 1; j <= N; j++)
                {
                    if (j == k) continue;
                    var dOrig = D[j];
                    var d = dOrig;
                    d = RemoveBitFromDomain(d, b);
                    d = RemoveBitFromDomain(d, b << (k + 1));
                    d = RemoveBitFromDomain(d, b >> (j + 1));
                    d = RemoveBitFromDomain(d, (b << (k + 1)) >> (j + 1));
                    if (DomainIsEmpty(d)) return false;
                    if (d != dOrig)
                    {
                        TrailDomainValue(j);
                        D[j] = d;
                        if (DomainIsSingleton(d)) newSingletons.Enqueue(j);
                    }
                }

                //WriteDomains();
            }
            return true;
        }

        // Search for a solution.  Return false iff one is not found.
        private static bool FindSolution() {
            var k = SmallestUndecidedDomainIndex();
            if (k == 0) return true;

            // Branch on k, trying each possible assignment.
            var dOrig = D[k];
            var d = dOrig;
            var checkPoint = TTop;
            while (!DomainIsEmpty(d))
            {
                var b = LeastBitInDomain(d);
                d = RemoveBitFromDomain(d, b);
                D[k] = b;

                //Console.WriteLine();
                //Console.WriteLine("Branching on domain {0}.", k);

                if (Prune(k) && FindSolution()) return true;
                UntrailTo(checkPoint);
            }
            D[k] = dOrig;
            return false;
        }

        // Print out a representation of the domains.
        private static void WriteDomains()
        {
            for (var k = 1; k <= N; k++)
            {
                Console.Write("D[{0,3}] = {{", k);
                for (var i = 1; i <= N + N; i++)
                {
                    Console.Write("{0, 3}", ( (1 << i) & D[k]) != 0 ? i.ToString()
                                            : DomainIsSingleton(D[k]) && (1 << i) == (D[k] << (k + 1)) ? "x"
                                            : "");
                }
                Console.WriteLine(" }");
            }
        }

        // Set up the problem.
        private static void InitLangford(int n)
        {
            N = n;
            D = new int[N + 1];
            var bs = (1 << (N + N - 1)) - 1;
            for (var k = 1; k <= N; k++)
            {
                D[k] = bs & ~1;
                bs >>= 1;
            }
        }
    }
}

Comment: could you give a hint in how would be a haskell solution?, I am reading your code, is really cool.
Comment: @darkcminor, sure.  In Haskell, the solution is even easier.  You write your code to generate the search tree explicitly; you don't need a trail since you never backtrack - each branch of the tree keeps its own assignment.  Laziness means you only manifest the part of the tree you are currently examining.  Let me know if you need more help on this one.  Cheers!
Comment: @darkcminor, check out the new C# version.  That should be trivial to recode in Haskell!
Answer: I couldn't resist. Here's my port of Rafe's code to Haskell:
module Langford where

import Control.Applicative
import Control.Monad
import Data.Array
import Data.List
import Data.Ord
import Data.Tuple
import qualified Data.IntSet as S

langford :: Int -> [[Int]]
langford n
  | mod n 4 `elem` [0, 3] = map (pairingToList n) . search $ initial n
  | otherwise             = []

type Variable = (Int, S.IntSet)
type Assignment = (Int, Int)
type Pairing = [Assignment]

initial :: Int -> [Variable]
initial n = [(i, S.fromList [1..(2*n-i-1)]) | i <- [1..n]]

search :: [Variable] -> [Pairing]
search [] = return []
search vs = do
    let (v, vs') = choose vs
    a <- assignments v
    case prune a vs' of
        Just vs'' -> (a :) <$> search vs''
        Nothing   -> mzero

choose :: [Variable] -> (Variable, [Variable])
choose vs = (v, filter (\(j, _) -> i /= j) vs)
  where v@(i, _) = minimumBy (comparing (S.size . snd)) vs

assignments :: Variable -> [Assignment]
assignments (i, d) = [(i, k) | k <- S.toList d]

prune :: Assignment -> [Variable] -> Maybe [Variable]
prune a = mapM (prune' a)

prune' :: Assignment -> Variable -> Maybe Variable
prune' (i, k) (j, d)
  | S.null d' = Nothing
  | otherwise = Just (j, d')
  where d' = S.filter (`notElem` [k, k+i+1, k-j-1, k+i-j]) d

pairingToList :: Int -> Pairing -> [Int]
pairingToList n = elems . array (1, 2*n) . concatMap positions
  where positions (i, k) = [(k, i), (k+i+1, i)]

It seems to work quite well. Here are some timings from GHCi:
Prelude Langford> :set +s
Prelude Langford> head $ langford 4
[4,1,3,1,2,4,3,2]
(0.03 secs, 6857080 bytes)
Prelude Langford> head $ langford 32
[32,28,31,23,26,29,22,24,27,15,17,11,25,10,30,5,20,2,21,19,2,5,18,11,10, ...]
(0.05 secs, 15795632 bytes)
Prelude Langford> head $ langford 100
[100,96,99,91,94,97,90,92,95,83,85,82,93,78,76,73,88,70,89,87,69,64,86, ...]
(0.57 secs, 626084984 bytes)

Comment: Seconded - I really miss declarative languages!  Still, have to pay the mortgage these days.
Answer: Since the Langford sequences are usually generated for a small integer n, I use bogosort for this program and include a check everytime it is bogosorted. When the check completes, I'm done.
For example, with n=3:

Create an array for 2n numbers.  The array would be something like this: 1 2 3 1 2 3
Employ a simple loop for bogosort and include a check every time which is quite easy.
If the check is successful, the array would give you the Langford sequence.

This will work fast for small integers only since the number of permutaions possible is n!, here: 3*2*1=6.


Python: make a derived class into a singleton

Question: I want to turn my derived class into a singleton in python. I would like to implement the singleton via metaclass, but I always come across the following error:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

My Code:
# singleton.py
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

# base.py
from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def run(self, value):
        pass

# foo.py
from base import Base
from singleton import Singleton

class Foo(Base, metaclass=Singleton):
    def run(self, value):
        print(value)

# main.py
from foo import Foo

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(24)

Answer: Through various other stackoverflow questions I have now come up with a solution myself.

MetaClass Conflict: Base Class and Derived class have different metaclass
Implementing Singleton as metaclass, but for abstract classes

As the error text already says, the metaclass of Foo must be a metaclass that is compatible with the base class metaclass (=ABCMeta).
This means that Singleton must also inherit from ABCMeta.
New Code:
# singleton.py

from abc import ABCMeta

class Singleton(ABCMeta):
    # ...

# bar.py
from base import Base

class Bar(Base):
    def run(self, value):
        print(value)

# main.py
from foo import Foo
from bar import Bar

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(34)

b1 = Bar()
print(b1)
b1.run(12)
b2 = Bar()
print(b2)
b2.run(21)

Output:
<foo.Foo object at 0x000001D4D512BE48>
42
<foo.Foo object at 0x000001D4D512BE48>
34
<bar.Bar object at 0x000001D4D512B0B8>
12
<bar.Bar object at 0x000001D4D512BEF0>
21

So Foo is a singleton and Bar isn't.
Bonus question:
Why doesn't Singleton(ABC) work?
Comment: ABC is just a base class.. and not metaclass.. You can derive  a metaclass from another metaclass, and not from just another Class..
Comment: `Base` is derived from `ABC`. This gives `Base` the metaclass `ABCMeta`. Why doesn't this also work for the (meta)class `Singleton`?
Comment: So, it seems that you just replaced "class Singleton(type):" to "class Singleton(ABCMeta):"? What was the 'type' used for? Was it not important?


How to do InputBindings for a DataBound ListBox?

Question: I have a ListBox with ItemsSource bound. If anyone selects a ListBoxItem and presses Enter key, a  command should be executed. How could I do this? I have ItemContainerStyle for ListBox and I cannot find a way to set InputBindings through Style.
Any ideas?
Answer: You could create an attached helper property which sets the bindings, here would be an example, you then can set that property in the style.


How can I test that a method is private using PHPUnit

Question: Using PHPUnit, I would like to test that a Class CANNOT be instantiated using the __construct [ new Class(); ] method as well as cannot be cloned, woken up etc.
Basically it is a Singleton class, and the __construct, __clone and __wakeup methods set to private to make sure it remains a Singleton.
But how can I test for that?
Answer: You can do this by catching the exception thrown by trying to instantiate a new object from the singleton.
Try the following (PHP 7):
class Single
{
    private function __construct() {}
}

class SingleTest extends \PHPUnit_Framework_TestCase
{
    function testCannotCallConstructor()
    {
        try {
            $single = new Single();
            $this->fail('Should never be called!');
        } catch (\Throwable $e) {
            $this->assertNotEmpty($e->getMessage());
        }

        //alternative:
        $this->expectException(\Error::class);
        $single = new Single();
    }
}

Answer: By design, unit test usually checks a behavior, not an interface (method signature is a part of the interface).
But if you really need that you can use the Reflection API. Check the class hasMethod() and this method isPrivate().
In the PHP7 enviroment you can use try/catch solution proposed by John Joseph, but i recommend to intercept only Error exceptions (Throwable covers all possible erros, not only visibility violation). Also PHPUnit has a @expectedException annotation, it's better than manual try/catch.
Answer: All of these are working perfectly.
function testCannotCallConstructor()
{
    try {
        $log = new Log();
        $this->fail('Should never be called!');
    } catch (\Throwable $e) {
        $this->assertNotEmpty($e->getMessage());
    }

    //alternative:
    $this->expectException(\Error::class);
    $log = new Log();
}

public function testConstructPrivate(){
    $method = new \ReflectionMethod('\\Core\\Log', '__construct');
    $result = $method->isPrivate();
    $this->assertTrue( $result, "Log __construct is not private. Singleton not guaranteed.");
}

Thank you very much. I think the one I prefer is the expectException method.


Android notification shown only icon on status bar

Question: In my application i wrote simple notification function, the method shows icon only on status bar and i want to show notification layout too, but not shown automatically and i have pull down android status bar down to see that,
public static void createNotification(Context context, Class activity, String title, String subject, int count_unread_message) {

    Intent intent = new Intent(context, activity);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notify = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(subject)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setNumber(count_unread_message)
            .setPriority(0)

            .setLights(Color.BLUE, 500, 500)
            .setContentIntent(pendingIntent)
            .build();

    notify.flags |= Notification.FLAG_AUTO_CANCEL;

    NOTIFICATIONMANAGER = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    NOTIFICATIONMANAGER.notify(159753456, notify);
}

It seems this problem is for android 6 and above
Answer: For me this was solved by calling setDefaults(Notification.DEFAULT_ALL) on the builder.  Hope that helps,
Paul
Comment: in my case it was needed both deprecated methods #setDefaults() and #setPriority()
Answer: I believe your problem is that the notification banner is not being displayed, right? So the user must lower the status bar in order to see the notification.
For me what solved it was to set a higher priority to the notification. In your case you should set it to high or max (since it is already on 0 - default):
            .setPriority(1)//1 is high, 2 is max

Reference: NotificationCompat.Builder documentation
Comment: in my case it was needed both deprecated methods #setDefaults() and #setPriority()
Answer: Add setDefaults(Notification.DEFAULT_ALL) on the Builder of Notification works for me.
Answer: Add .setLargeIcon(R.mipmap.ic_launcher) in your code
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.yourIcon);

 Notification notify = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(subject)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)//can set only bitmap images convert your drawable to bitmap
            .setNumber(count_unread_message)
            .setPriority(0)

            .setLights(Color.BLUE, 500, 500)
            .setContentIntent(pendingIntent)
            .build();

https://developer.android.com/reference/android/app/Notification.html#largeIcon
Comment: are you sure problem is setting large icon? i get this error:  `Error:(224, 39) error: incompatible types: int cannot be converted to Bitmap`
Comment: dont resolve problem, i dont see notification and only can show small notification icon on status bar, i tested on android 6.0.1, is it cause of this problem? or any permission must be set?
Comment: .setLargeIcon(icon) is deprecated in sdk v23, may be it won't work in android 6.0.1 please check the documentation link above
Comment: on notification layout `setLargeIcon` work fine but I'm not sure problem is `setLargeIcon`
Comment: Hi i see my edited post by you thanks , you dont understand my mean sir, i edited that again. please read again sir :) problem is shown only icon on status bar, i want to show layout too
Comment: I've had setDefaults and setPriority, but notification was still appearing only in Status Bar. Setting Large Icon helped me.


Recommended Ubuntu partition size

Question: I have a 128GB SSD with Windows 10 installed on it and I also have a 1TB HDD on my computer. I want to dual boot Ubuntu along side with windows 10 but I don't know how much space I need to give to Ubuntu and if I should even install it on the same drive as windows, because I roughly have 60GB's on my SSD left but I thought it would be better to keep them like that since windows always has updates and that sort of stuff.
I mainly use windows for gaming and pretty much everything, Ubuntu is for college programming purposes.
Sorry if I misnamed any term but I'm still a beginner to all this sort of stuff.
Comment: You may also use the partition and data allocation between SSD and HDD from the answer to this question: [Do I need Intel Smart Response when installing Ubuntu?](https://askubuntu.com/questions/282831/do-i-need-intel-smart-response-when-installing-ubuntu/282903?s=4|26.7736#282903)
Answer: Although this question has many possibilities, according to the needs of each one.
I would install in particular:
An ext4 partition, of 1 gigabytes, for /boot in the SDD.
An ext4 partition of 30 gigabytes for /on the HDD.
A partition exchange system, of 4 gigas to swap on the HDD.
An ext4 partition, of 40 gigabytes, for /home on the HDD.
Comment: Most desktops do not need /boot partition. And swap is not a partition exchange system, but more for use if RAM if full of active programs. Ubuntu with 17.04 or later  does not create a swap partition, but uses a swap file, but will use an existing swap if found. How much for /home or /mnt/data whether NTFS or ext4 depends greatly on how much data you want or will have.
Comment: I would prefer to do not have separate swap partition and to setup a [swap file](https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-16-04) instead that. Separate boot partition is required when you are using LVM, etc.

Recommended Ubuntu partition size


Regular Expressions in .NET 2.0

Question: Can somebody help to modify following regular expression to ignore commas if they are included in double quotes
Current regular expression -
<code>,(?!(?<=(?:^|,)\s*""(?:[^""]|""|\\"")*,)(?:[^""]|""|\\"")*""\s*(?:,|$))
</code>
The only issue with this is that it splits string at each comma. Commas within columns surrounded by double quotes should be treated as one column
As an example, splitting this string "a","b,c" should result in two columns, not three.
Thanks!
Comment: Could it be that you would be better off with a [TextFieldParser](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser%28v=vs.80%29.aspx)?
Comment: Does VB.net not have a CSV parsing library?
Answer: The following Regex is probably what you are looking for...

\".*?\"
Comment: @user2835552 The TextFieldParser was new in .NET 2.0. It would probably have been used in the .NET 1.1 version of the program if it was available then.
Comment: It's a legacy application that was running on .net 1.1 just fine, but regular expression doesn't work as it used on 1.0. I am trying not to make too many changes.
Comment: I updated the regex to handle more characters. Let me know if that works.
Comment: sorry, \".*?\" results in same output
Comment: what is the output you get?

Regular Expressions in .NET 2.0


What constitutes being off-topic with regards to puzzles/problems/theoretical constructions?

Question: I noticed this topic was just put on hold as being off-topic. However, several other recent questions about extremely similar topics, for example this, this, or this, have all been deemed acceptable.
Considering the similarity of the questions and the opposite handling with regards to whether or not they are off-topic, there appears to be some discrepancy. What exactly constitutes being off-topic when it comes to these types of questions?
Comment: I quite appreciate these types of questions myself. The pure chess value may be debateable, but they are interesting thought exercises and have been covered by major chess publications. Of course, the community as a whole may come to the agreement that this is not the place for these questions, but there needs to be some kind of consistency in the way they are handled.
Comment: Does anyone even read this? It's been about a week since I posted this and not a single reply or comment of any kind. What's the point of the chess meta if no one even sees it?
Comment: To me, all those questions are not relevant and I would close them all. Still, I refrained myself from voting because someone might find them useful ( as you have commented someone may find them artistic... ). I believe that the rules for puzzles are very loose and ill defined. Something we should definitely attend to. Since the question seems equally irrelevant to me as the ones you linked to, I have voted for reopening it.
Answer: I'm sorry for not checking the site for a while. I reopened the question under scrutiny, and in my opinion, the others you cited should remain open as well.
As long as they are not open-ended (i.e. there is a definitive answer or study to be given, not opinion), such questions are suited for the Stack Exchange venue; therefore, the only objection that may remain is one regarding our site's scope. This is determined by the moderators. After the core topic is established (the game of chess), we have leeway in including/excluding related topics. So basically, it could change over time.
At this point, I call chess puzzles on-topic for chess.SE. But a few things could alter that consideration. The other moderators may disagree, or the chess.SE community may present a case for removing the topic, or some effect of that decision may prove to negatively impact the productivity of this site. But I don't see any of this happening, and chess puzzles have to do with chess, and I like chess puzzles.
Comment: Thanks for reopening. I hope you get a chance to read my own response, where I argue that chess compositions (like OTB strategy and tactical puzzles) are at the core of "the game of chess"
Answer: There are several ways to enjoy chess. The most popular way is probably to play the game. Folk who do this often enjoy tactical puzzles which sample typical critical moments that might occur in a game.
However, just as both speed skating and figure skating are sports that involve moving around on ice, let's not forget chess problem composition. This has a venerable history, and titles (from GM downwards) are awarded for showing extreme technical mastery and artistic flair. Similarly, there are titles awarded for solving chess compositions, and while an OTB (Over The Board) player can achieve GM status in their early teens, it would be rare for a composer GM to achieve that before 40.
Compositions are deliberately not intended to be a "typical position from a game", and indeed it is very much frowned upon to add extra material to make the position more "realistic" - that's not the point. The word "puzzle" is deliberately avoided - there's nothing wrong with tactical puzzles, but that's not what compositions are about.
It may be that some kinds of composition may help in over the board play, but it's irrelevant and cringing to make that kind of argument. Does high-diving skill make someone better able to swim 100m freestyle? Almost certainly not, but high-diving is still a beautiful Olympic sport.
It's curious that even today, many competitive-minded chessplayers are snortingly ignorant that someone might want to engage with chess in a purely artistic way. In Magic the Gathering, at least a "Spike" (a.k.a. a competitive player) is generally aware that this is their designation, and that another designation exists: "Johnny" the player who wants to make cool decks that lead to interesting situations.
So there are Spikes in chess.stackexchange for whom the penny hasn't dropped, and still think "speed skating" is the only game in town. If they stumble across a composition post here in chess.stackexchange they may erroneously classify it as "off-topic".
I hope that (properly edited) my answer may be added to the terms of reference of this community, because it would be good to nail this misunderstanding once and for all.
Thank you


Not able to view a website in ubuntu?

Question: I am not able to view a particular website in ubuntu where as the same is getting viewed in windows. Can anyone suggest or provide me a fix to solve this issue??
Website which is not getting viewed in Ubuntu:

http://www.grandsarovar.com/360/resturant.html

Getting viewed in windows:

View in Ubuntu:
Answer: This website consists basically of an embedded .mov (Apple Quicktime) movie. It may be Quicktime VR; I can't tell for sure as, even with the right set of plugins for quicktime playback, I'm unable to really see what was meant to be shown.
You can install the gstreamer0.10-ffmpeg plugin to get some .mov playback going, or you can google around for how to install some non-free codecs to get better .mov playback.
Personally I think this website's design is horrible as it's just an embedded video, and I'd strongly try to encourage the designer to make it more accessible and useful by coding with reasonable web standards and content, but that may not be a possibility here.
Comment: I can confirm it's Quicktime VR. Tested on Windows machine, and planning to send an email to the developer.

Not able to view a website in ubuntu?


Stuck in login screen after 15.04 upgrade

Question: I have upgraded from 14.10 to 15.04 and when I boot I get to the usual login screen but it is displayed in low resolution. When I login it briefly displays a console message then returns to the login screen. This is the case for all users and for each of the Ubuntu versions except console mode which opens a 'terminal'.
I have tried a few things found on the help boards but without joy.
The display manager is lightdm.
I have tried mount - of remount, rw / sequence without joy.
Getting a bit desperate! Have a feeling it isn't mounting all the partitions (just a hunch after running blkid).
Any suggestions welcome! (having to do this on my phone).
Cheers Nevil
Answer: You can login via the command line from the login screen by hitting Ctrl+Alt+F1
You can get back to the GUI with Ctrl+Alt+F7
This might make it easier to troubleshoot the problem.
The last time I had this issue I moved all of the hidden files out of my user account into a temp folder and it fixed the problem. Then I started copying them back in until I found which one was causing the problem. I think it was something in ~/.gconf
Comment: Thanks. How did you move all the hidden files to a temporary folder?
Comment: use `mkdir temporary` to make a directory called temporary. Then use `ls -a` to list all files/directories, including the hidden ones (starting with a dot, e.g. `.profile`), then use `mv -i -v file temporary` to move file to temporary (do not forget the dot). the `-i` will prompt you in case you are trying to overwrite an existing file of the same name, and `-v` will simply give you a feedback of the moving ( e.g. `'file' -> 'temporary/file'`). For moving all dotted files, use `mv .[A-z0-9]* temporary`


Set up a Stomp client in android with Spring framework in server side

Question: I am developing an android application that exchanges data with a jetty server configured in Spring. To obtain a more dynamic android application, i am trying to use WebSocket protocol with Stomp messages.
In order to realize this stuff, i config a web socket message broker in spring :
@Configuration
//@EnableScheduling
@ComponentScan(
        basePackages="project.web",
        excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class)
)
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/message");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/client");
    }
}

and a SimpMessageSendingOperations in Spring controller to send message from server to client :
@Controller
public class MessageAddController {
    private final Log log = LogFactory.getLog(MessageAddController.class);

    private SimpMessageSendingOperations messagingTemplate;

    private UserManager userManager;

    private MessageManager messageManager;

    @Autowired
    public MessageAddController(SimpMessageSendingOperations messagingTemplate,
            UserManager userManager, MessageManager messageManager){
        this.messagingTemplate = messagingTemplate;
        this.userManager = userManager;
        this.messageManager = messageManager;
    }

    @RequestMapping("/Message/Add")
    @ResponseBody
    public SimpleMessage addFriendship(
            @RequestParam String content,
            @RequestParam Long otherUser_id
    ){
        if(log.isInfoEnabled())
            log.info("Execute MessageAdd action");
        SimpleMessage simpleMessage;

        try{
            User curentUser = userManager.getCurrentUser();
            User otherUser = userManager.findUser(otherUser_id);

            Message message = new Message();
            message.setContent(content);
            message.setUserSender(curentUser);
            message.setUserReceiver(otherUser);

            messageManager.createMessage(message);
            Message newMessage = messageManager.findLastMessageCreated();

            messagingTemplate.convertAndSend(
                    "/message/add", newMessage);//send message through websocket

            simpleMessage = new SimpleMessage(null, newMessage);
        } catch (Exception e) {
            if(log.isErrorEnabled())
                log.error("A problem of type : " + e.getClass()
                        + " has occured, with message : " + e.getMessage());
            simpleMessage = new SimpleMessage(
                            new SimpleException(e.getClass(), e.getMessage()), null);
        }
        return simpleMessage;
    }
}

When i test this configuration in a web browser with stomp.js, I haven't any problem : messages are perfectly exchanged between web browser and Jetty server. The JavaScript code using for web browser test :
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        document.getElementById('response').innerHTML = '';
    }

    function connect() {
        stompClient = Stomp.client("ws://YOUR_IP/client");
        stompClient.connect({}, function(frame) {
            setConnected(true);
            stompClient.subscribe('/message/add', function(message){
                showMessage(JSON.parse(message.body).content);
            });
        });
    }

    function disconnect() {
        stompClient.disconnect();
        setConnected(false);
        console.log("Disconnected");
    }

    function showMessage(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }

Problems occur when i try to use stomp in Android with libraries like gozirra, activemq-stomp or others : most of time, connection with server doesn't work. My app stop to run and, after a few minutes, i have the following message in logcat : java.net.UnknownHostException: Unable to resolve host "ws://192.168.1.39/client": No address associated with hostname, and i don't understand why. Code using Gozzira library which manages the stomp appeal in my android activity :
private void stomp_test() {
    String ip = "ws://126.96.36.199/client";
    int port = 8080;

    String channel = "/message/add";
    Client c;

    try {
        c = new Client( ip, port, "", "" );
        Log.i("Stomp", "Connection established");
        c.subscribe( channel, new Listener() {
            public void message( Map header, String message ) {
                Log.i("Stomp", "Message received!!!");
              }
        });

    } catch (IOException ex) {
        Log.e("Stomp", ex.getMessage());
        ex.printStackTrace();

    } catch (LoginException ex) {
        Log.e("Stomp", ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        Log.e("Stomp", ex.getMessage());
        ex.printStackTrace();
    }

}

After some research, i found that most persons who want to use stomp over websocket with Java Client use ActiveMQ server, like in this site. But spring tools are very simple to use and it will be cool if i could keep my server layer as is it now. Someone would know how to use stomp java (Android) in client side with Spring configuration in server side?
Comment: you didn't talk about how you are managing threads.
Answer: My implementation of STOMP protocol for android (or plain java) with RxJava https://github.com/NaikSoftware/StompProtocolAndroid. Tested on STOMP server with SpringBoot.
Simple example (with retrolambda):
private StompClient mStompClient;

 // ...

 mStompClient = Stomp.over(WebSocket.class, "ws://localhost:8080/app/hello/websocket");
 mStompClient.connect();

 mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
     Log.d(TAG, topicMessage.getPayload());
 });

 mStompClient.send("/app/hello", "My first STOMP message!");

 // ...

 mStompClient.disconnect();

Add the following classpath in project :
  classpath 'me.tatarka:gradle-retrolambda:3.2.0'

Add the following thing in your app build.gradle :
apply plugin: 'me.tatarka.retrolambda'

android {
       .............
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

  dependencies {
      ............................
    compile 'org.java-websocket:Java-WebSocket:1.3.0'
    compile 'com.github.NaikSoftware:StompProtocolAndroid:1.1.5'
}

All working asynchronously! You can call connect() after subscribe() and send(), messages will be pushed to queue.
Additional features:

extra HTTP headers for handshake query (for passing auth token or other)
you can implement own transport for library, just implement interface ConnectionProvider
subscribe connection lifecycle events (connected, closed, error)

For Example :
public class MainActivity extends AppCompatActivity {
    private StompClient mStompClient;
    public static  final String TAG="StompClient";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button view = (Button) findViewById(R.id.button);
        view.setOnClickListener(e->  new LongOperation().execute(""));

    }

        private class LongOperation extends AsyncTask<String, Void, String> {
        private StompClient mStompClient;
        String TAG="LongOperation";
        @Override
        protected String doInBackground(String... params) {

            mStompClient = Stomp.over(WebSocket.class, "ws://localhost:8080/app/hello/websocket");
            mStompClient.connect();

            mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
                Log.d(TAG, topicMessage.getPayload());
            });

            mStompClient.send("/app/hello", "My first STOMP message!").subscribe();

            mStompClient.lifecycle().subscribe(lifecycleEvent -> {
                switch (lifecycleEvent.getType()) {

                    case OPENED:
                        Log.d(TAG, "Stomp connection opened");
                        break;

                    case ERROR:
                        Log.e(TAG, "Error", lifecycleEvent.getException());
                        break;

                    case CLOSED:
                        Log.d(TAG, "Stomp connection closed");
                        break;
                }
            });
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

        }

    }
}

Add Internet permission in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Comment: can't use it. everytime StompClient receive message, it always disconnected.
Comment: @Raizal call connect() method after subscibe
Comment: How do you reconnect with your library? Thanks.
Comment: where are you put this line? `  classpath 'me.tatarka:gradle-retrolambda:3.2.0'`? build.gradle?
Comment: In project-level gradle `buildscript>dependencies`
Comment: @NickolaySavchenko its not working forme, but i dont know why, i can connect to `ws://localhost:61614` but not `ws://localhost:8080` and i see from https://github.com/NaikSoftware/StompProtocolAndroid, its setup the endpoint to `/hello`, but from that code, he was connect to `Stomp.over(WebSocket.class, "ws://localhost:8080/app/hello/websocket");`
can you help me? i don't know why, i cannot connect to `ws://localhost:8080`
Comment: @NickolaySavchenko hi,, will you join this chat room please ? http://chat.stackoverflow.com/rooms/136809/stomp-with-spring-web-socket
Comment: if server send, it display :-
"D/WebSocketsConnectionProvider: Emit STOMP message:                                                                                destination:/topic/online/
message-id:ID:Laptop-Jiban-63222-1512979632616-18:1:1:1:1                                                                                timestamp:1512981478081
Enter some text here for the message body"

 Not executing Log.d(TAG, topicMessage.getPayload()); block
Comment: Hi.. I am getting error ie. Failed to resolve: compile 'com.github.NaikSoftware:StompProtocolAndroid:1.1.5'
Answer: I achieve to use stomp over web socket with Android and spring server.
To do such a thing, i used a web socket library : werbench (follow this link to download it). To install, I used the maven command mvn install and i got back the jar in my local repository. Then, I need to add a stomp layer on the basic web socket one, but i couldn't find any stomp library in java which could manage stomp over web socket (I had to give up gozzira). So I create my own one (with stomp.js like model). Don't hesitate to ask me if you want take a look at it, but i realized it very quickly so it can not manage as much as stomp.js. Then, i need to realize an authentication with my spring server. To achieve it, i followed the indication of this site. when i get back the JSESSIONID cookie, I had just need to declare an header with this cookie in the instantiation of a werbench  web socket in my stomp "library".
EDIT :
this is the main class in this library, the one which manage the stomp over web socket connection :
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.util.Log;
import de.roderick.weberknecht.WebSocket;
import de.roderick.weberknecht.WebSocketEventHandler;
import de.roderick.weberknecht.WebSocketMessage;

public class Stomp {

    private static final String TAG = Stomp.class.getSimpleName();

    public static final int CONNECTED = 1;//Connection completely established
    public static final int NOT_AGAIN_CONNECTED = 2;//Connection process is ongoing
    public static final int DECONNECTED_FROM_OTHER = 3;//Error, no more internet connection, etc.
    public static final int DECONNECTED_FROM_APP = 4;//application explicitely ask for shut down the connection

    private static final String PREFIX_ID_SUBSCIPTION = "sub-";
    private static final String ACCEPT_VERSION_NAME = "accept-version";
    private static final String ACCEPT_VERSION = "1.1,1.0";
    private static final String COMMAND_CONNECT = "CONNECT";
    private static final String COMMAND_CONNECTED = "CONNECTED";
    private static final String COMMAND_MESSAGE = "MESSAGE";
    private static final String COMMAND_RECEIPT = "RECEIPT";
    private static final String COMMAND_ERROR = "ERROR";
    private static final String COMMAND_DISCONNECT = "DISCONNECT";
    private static final String COMMAND_SEND = "SEND";
    private static final String COMMAND_SUBSCRIBE = "SUBSCRIBE";
    private static final String COMMAND_UNSUBSCRIBE = "UNSUBSCRIBE";
    private static final String SUBSCRIPTION_ID = "id";
    private static final String SUBSCRIPTION_DESTINATION = "destination";
    private static final String SUBSCRIPTION_SUBSCRIPTION = "subscription";

    private static final Set<String> VERSIONS = new HashSet<String>();
    static {
        VERSIONS.add("V1.0");
        VERSIONS.add("V1.1");
        VERSIONS.add("V1.2");
    }

    private WebSocket websocket;

    private int counter;

    private int connection;

    private Map<String, String> headers;

    private int maxWebSocketFrameSize;

    private Map<String, Subscription> subscriptions;

    private ListenerWSNetwork networkListener;

    /**
     * Constructor of a stomp object. Only url used to set up a connection with a server can be instantiate
     *
     * @param url
     *      the url of the server to connect with
     */
    public Stomp(String url, Map<String,String> headersSetup, ListenerWSNetwork stompStates){
        try {
            this.websocket = new WebSocket(new URI(url), null, headersSetup);
            this.counter = 0;

            this.headers = new HashMap<String, String>();
            this.maxWebSocketFrameSize = 16 * 1024;
            this.connection = NOT_AGAIN_CONNECTED;
            this.networkListener = stompStates;
            this.networkListener.onState(NOT_AGAIN_CONNECTED);
            this.subscriptions = new HashMap<String, Subscription>();

            this.websocket.setEventHandler(new WebSocketEventHandler() {
                @Override
                public void onOpen(){
                    if(Stomp.this.headers != null){
                        Stomp.this.headers.put(ACCEPT_VERSION_NAME, ACCEPT_VERSION);

                        transmit(COMMAND_CONNECT, Stomp.this.headers, null);

                        Log.d(TAG, "...Web Socket Openned");
                    }
                }

                @Override
                public void onMessage(WebSocketMessage message) {
                    Log.d(TAG, "<<< " + message.getText());
                    Frame frame = Frame.fromString(message.getText());
                    boolean isMessageConnected = false;

                    if(frame.getCommand().equals(COMMAND_CONNECTED)){
                        Stomp.this.connection = CONNECTED;
                        Stomp.this.networkListener.onState(CONNECTED);

                        Log.d(TAG, "connected to server : " + frame.getHeaders().get("server"));
                        isMessageConnected = true;

                    } else if(frame.getCommand().equals(COMMAND_MESSAGE)){
                        String subscription = frame.getHeaders().get(SUBSCRIPTION_SUBSCRIPTION);
                        ListenerSubscription onReceive = Stomp.this.subscriptions.get(subscription).getCallback();

                        if(onReceive != null){
                            onReceive.onMessage(frame.getHeaders(), frame.getBody());
                        } else{
                            Log.e(TAG, "Error : Subscription with id = " + subscription + " had not been subscribed");
                            //ACTION TO DETERMINE TO MANAGE SUBCRIPTION ERROR
                        }

                    } else if(frame.getCommand().equals(COMMAND_RECEIPT)){
                        //I DON'T KNOW WHAT A RECEIPT STOMP MESSAGE IS

                    } else if(frame.getCommand().equals(COMMAND_ERROR)){
                        Log.e(TAG, "Error : Headers = " + frame.getHeaders() + ", Body = " + frame.getBody());
                        //ACTION TO DETERMINE TO MANAGE ERROR MESSAGE

                    } else {

                    }

                    if(isMessageConnected)
                        Stomp.this.subscribe();
                }

                @Override
                public void onClose(){
                    if(connection == DECONNECTED_FROM_APP){
                        Log.d(TAG, "Web Socket disconnected");
                        disconnectFromApp();
                    } else{
                        Log.w(TAG, "Problem : Web Socket disconnected whereas Stomp disconnect method has never "
                                + "been called.");
                        disconnectFromServer();
                    }
                }

                @Override
                public void onPing() {

                }

                @Override
                public void onPong() {

                }

                @Override
                public void onError(IOException e) {
                    Log.e(TAG, "Error : " + e.getMessage());
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * Send a message to server thanks to websocket
     *
     * @param command
     *      one of a frame property, see {@link Frame} for more details
     * @param headers
     *      one of a frame property, see {@link Frame} for more details
     * @param body
     *      one of a frame property, see {@link Frame} for more details
     */
    private void transmit(String command, Map<String, String> headers, String body){
        String out = Frame.marshall(command, headers, body);
        Log.d(TAG, ">>> " + out);
        while (true) {
            if (out.length() > this.maxWebSocketFrameSize) {
                this.websocket.send(out.substring(0, this.maxWebSocketFrameSize));
                out = out.substring(this.maxWebSocketFrameSize);
            } else {
                this.websocket.send(out);
                break;
            }
        }
    }

    /**
     * Set up a web socket connection with a server
     */
    public void connect(){
        if(this.connection != CONNECTED){
            Log.d(TAG, "Opening Web Socket...");
            try{
                this.websocket.connect();
            } catch (Exception e){
                Log.w(TAG, "Impossible to establish a connection : " + e.getClass() + ":" + e.getMessage());
            }
        }
    }

    /**
     * disconnection come from the server, without any intervention of client side. Operations order is very important
     */
    private void disconnectFromServer(){
        if(this.connection == CONNECTED){
            this.connection = DECONNECTED_FROM_OTHER;
            this.websocket.close();
            this.networkListener.onState(this.connection);
        }
    }

    /**
     * disconnection come from the app, because the public method disconnect was called
     */
    private void disconnectFromApp(){
        if(this.connection == DECONNECTED_FROM_APP){
            this.websocket.close();
            this.networkListener.onState(this.connection);
        }
    }

    /**
     * Close the web socket connection with the server. Operations order is very important
     */
    public void disconnect(){
        if(this.connection == CONNECTED){
            this.connection = DECONNECTED_FROM_APP;
            transmit(COMMAND_DISCONNECT, null, null);
        }
    }

    /**
     * Send a simple message to the server thanks to the body parameter
     *
     *
     * @param destination
     *      The destination through a Stomp message will be send to the server
     * @param headers
     *      headers of the message
     * @param body
     *      body of a message
     */
    public void send(String destination, Map<String,String> headers, String body){
        if(this.connection == CONNECTED){
            if(headers == null)
                headers = new HashMap<String, String>();

            if(body == null)
                body = "";

            headers.put(SUBSCRIPTION_DESTINATION, destination);

            transmit(COMMAND_SEND, headers, body);
        }
    }

    /**
     * Allow a client to send a subscription message to the server independently of the initialization of the web socket.
     * If connection have not been already done, just save the subscription
     *
     * @param subscription
     *      a subscription object
     */
    public void subscribe(Subscription subscription){
        subscription.setId(PREFIX_ID_SUBSCIPTION + this.counter++);
        this.subscriptions.put(subscription.getId(), subscription);

        if(this.connection == CONNECTED){
            Map<String, String> headers = new HashMap<String, String>();
            headers.put(SUBSCRIPTION_ID, subscription.getId());
            headers.put(SUBSCRIPTION_DESTINATION, subscription.getDestination());

            subscribe(headers);
        }
    }

    /**
     * Subscribe to a Stomp channel, through messages will be send and received. A message send from a determine channel
     * can not be receive in an another.
     *
     */
    private void subscribe(){
        if(this.connection == CONNECTED){
            for(Subscription subscription : this.subscriptions.values()){
                Map<String, String> headers = new HashMap<String, String>();
                headers.put(SUBSCRIPTION_ID, subscription.getId());
                headers.put(SUBSCRIPTION_DESTINATION, subscription.getDestination());

                subscribe(headers);
            }
        }
    }

    /**
     * Send the subscribe to the server with an header
     * @param headers
     *      header of a subscribe STOMP message
     */
    private void subscribe(Map<String, String> headers){
        transmit(COMMAND_SUBSCRIBE, headers, null);
    }

    /**
     * Destroy a subscription with its id
     *
     * @param id
     *      the id of the subscription. This id is automatically setting up in the subscribe method
     */
    public void unsubscribe(String id){
        if(this.connection == CONNECTED){
            Map<String, String> headers = new HashMap<String, String>();
            headers.put(SUBSCRIPTION_ID, id);

            this.subscriptions.remove(id);
            this.transmit(COMMAND_UNSUBSCRIBE, headers, null);
        }
    }
}

This one is the Frame of a Stomp message :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Frame {
//  private final static String CONTENT_LENGTH = "content-length";

    private String command;
    private Map<String, String> headers;
    private String body;

    /**
     * Constructor of a Frame object. All parameters of a frame can be instantiate
     *
     * @param command
     * @param headers
     * @param body
     */
    public Frame(String command, Map<String, String> headers, String body){
        this.command = command;
        this.headers = headers != null ? headers : new HashMap<String, String>();
        this.body = body != null ? body : "";
    }

    public String getCommand(){
        return command;
    }

    public Map<String, String> getHeaders(){
        return headers;
    }

    public String getBody(){
        return body;
    }

    /**
     * Transform a frame object into a String. This method is copied on the objective C one, in the MMPReactiveStompClient
     * library
     * @return a frame object convert in a String
     */
    private String toStringg(){
        String strLines = this.command;
        strLines += Byte.LF;
        for(String key : this.headers.keySet()){
            strLines += key + ":" + this.headers.get(key);
            strLines += Byte.LF;
        }
        strLines += Byte.LF;
        strLines += this.body;
        strLines += Byte.NULL;

        return strLines;
    }

    /**
     * Create a frame from a received message. This method is copied on the objective C one, in the MMPReactiveStompClient
     * library
     *
     * @param data
     *  a part of the message received from network, which represented a frame
     * @return
     *  An object frame
     */
    public static Frame fromString(String data){
        List<String> contents = new ArrayList<String>(Arrays.asList(data.split(Byte.LF)));

        while(contents.size() > 0 && contents.get(0).equals("")){
            contents.remove(0);
        }

        String command = contents.get(0);
        Map<String, String> headers = new HashMap<String, String>();
        String body = "";

        contents.remove(0);
        boolean hasHeaders = false;
        for(String line : contents){
            if(hasHeaders){
                for(int i=0; i < line.length(); i++){
                    Character c = line.charAt(i);
                    if(!c.equals('\0'))
                        body += c;
                }
            } else{
                if(line.equals("")){
                    hasHeaders = true;
                } else {
                    String[] header = line.split(":");
                    headers.put(header[0], header[1]);
                }
            }
        }
        return new Frame(command, headers, body);
    }

//    No need this method, a single frame will be always be send because body of the message will never be excessive
//    /**
//     * Transform a message received from server in a Set of objects, named frame, manageable by java
//     *
//     * @param datas
//     *        message received from network
//     * @return
//     *        a Set of Frame
//     */
//    public static Set<Frame> unmarshall(String datas){
//      String data;
//      String[] ref = datas.split(Byte.NULL + Byte.LF + "*");//NEED TO VERIFY THIS PARAMETER
//      Set<Frame> results = new HashSet<Frame>();
//
//      for (int i = 0, len = ref.length; i < len; i++) {
//            data = ref[i];
//
//            if ((data != null ? data.length() : 0) > 0){
//              results.add(unmarshallSingle(data));//"unmarshallSingle" is the old name method for "fromString"
//            }
//        }
//      return results;
//    }

    /**
     * Create a frame with based fame component and convert them into a string
     *
     * @param command
     * @param headers
     * @param body
     * @return  a frame object convert in a String, thanks to toStringg() method
     */
    public static String marshall(String command, Map<String, String> headers, String body){
        Frame frame = new Frame(command, headers, body);
        return frame.toStringg();
    }

    private class Byte {
        public static final String LF = "\n";
        public static final String NULL = "\0";
    }
}

This one is an object used to establish a subscription via the stomp protocol :
public class Subscription {

    private String id;

    private String destination;

    private ListenerSubscription callback;

    public Subscription(String destination, ListenerSubscription callback){
        this.destination = destination;
        this.callback = callback;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getDestination() {
        return destination;
    }

    public ListenerSubscription getCallback() {
        return callback;
    }
}

At least, there are two interfaces used as the "Run" java class, to listen web socket network and a given subscription canal
public interface ListenerWSNetwork {
    public void onState(int state);
}

import java.util.Map;
public interface ListenerSubscription {
    public void onMessage(Map<String, String> headers, String body);
}

For more information, don't hesitate to ask me.
Comment: You should always post your solution.
Comment: Could you please provide an example about how to subscribe to ws service?
Comment: Hi, How do you manage to run Spring over Cross domain (mobile devices). I am implementing a solution using Spring with Sockjs and JWT tokens but Sockjs fallback into iframe because (I think) the client is running in a different domain.
Comment: @Eperrin95 `i followed the indication of this site. when i get back the JSESSIONID cookie,` the link is dead
Comment: Can you provide link to the client please?
Answer: Perfect solution Eperrin thank you. I would like fill the complete solution e.g. in your Activity/Service phase you call connection method of course doesn't in MainThread.
private void connection() {
        Map<String,String> headersSetup = new HashMap<String,String>();
        Stomp stomp = new Stomp(hostUrl, headersSetup, new ListenerWSNetwork() {
            @Override
            public void onState(int state) {
            }
        });
        stomp.connect();
        stomp.subscribe(new Subscription(testUrl, new ListenerSubscription() {
            @Override
            public void onMessage(Map<String, String> headers, String body) {
            }
        }));
    }

And be careful in websocket weberknecht library is bug in WebSocketHandshake class in method verifyServerHandshakeHeaders is on the line 124 is check only if(!headers.get("Connection").equals("Upgrade"))  and when server send upgrade instead of Upgrade you get error connection failed: missing header field in server handshake: Connection you have to turn off ignore cases if(!headers.get("Connection").equalsIgnoreCase("Upgrade"))
Comment: My server also have path to SEND messages (chat broker). So how can I send something to it with that solution?
Comment: I will try explain solution for AsyncTask the same you can do it in Services. First you have to create Activity/Fragment, after you call AsyncTask and in phase doInBackground you call my method connection (in previous answered). And you have to import weberknecht library in your project because you call object Stomp which exist in this library thos is everything.  But be careful your server must support STOMP version websocket
Comment: Okay, I got It. Reading code a little bit carefully makes me understand. Thanks!
Comment: Don't forget send PING server, default implementation doesn't send PING and you can get EOF after few doesn't send PING ...it depends implementation on server.
Answer: With weberknecht library I had an exception from Spring "A fragmented control frame was received but control frames may not be fragmented".
Fixed it by clearing extra spaces:
WebSocketHandshake.java
handshake += "";

instead of:
handshake += "\r\n";


how to select distinct values from a table when i need to select values having y if it has both y,n values and n values only if there is no y value

Question: i have a table with data like
promo    flag

ab21     y
ab21     N
bc22     N
bc22     N
CD23     Y
CD23     Y
ef24     N
ef24     y

i want distinct  promo ,flag from the table
 but when a single promo has both Y,N flags i want only Y FLAG PROMO
i.e
expected output
ab21 y
bc22 n
cd23 y
ef24 y

need help in building a simple query
like
select distinct promo,flag from table where ( your solution subquery)

Answer: Try, it is simpler way(from your test data):
select promo, max(lower(flag)) from table
group by promo

Comment: @RustamPulatov . . . I don't know if this is faster, but it is definitely simpler.  It might be faster -- Oracle has a good optimizer and has good implementations for aggregation.
Comment: @Gordon Linoff, Thank you. I think only "explain plan" says faster or not)
Answer: You can use analytical function like this:
Select promo, flag
 from (Select promo, flag,
       row_number()
       over (partition by promo order by upper(flag) desc nulls last) as rn
 From your_table)
Where rn=1;

You can also use group by but it will restrict you to select any other columns from table in the result.
select promo, max(upper(flag)) from table
group by promo

Also, in group by query, it will be case insensitive so , I would recommend to use analytical function.
Cheers!!


Dropdown in Bootstrap won't work

Question: I've looked at previous questions and moved stuff around but it doesn't seem to work. I'm thinking that there something wrong with me referencing the bootstrap scripts and links. I've taken stuff out in iterations but it hasn't solved the problem yet. Thanks for the help.
<! DOCTYPE html>

<title>Austin Band Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href = "bootstrap.min.css" rel = "stylesheet">
    <link href = "css/styles.css" rel = "stylesheet">
    <link href="css/bootstrap.min.css/navbar-static-top.css" rel="stylesheet">

    <link href="BootStrap.css" rel="stylesheet" />
    <link href="css/bootstrap.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          Austin Band Map

About

Contact

List View

Login

                Austin Venues

Antone's

Austin 360

Austin Music Hall

The Backyard

Bass Concert Hall

Emo's

Festivals

Frank Erwin Center

Hole In The Wall

Lambert's

Mohawk

Parish

Red 7

Stubb's

Comment: why are you including jQuery twice?
Answer: Try this out

Comment: Instead of the previous scripts I have the bottom?

Dropdown in Bootstrap won't work


Is it bad practice to use gksu when writing code in development?

Question: I am writing a C++ application that needs to access the serial port and use the mount command, both needing root to be performed.
In the end the application will be run as root on a device, but I am wondering if it is bad practice to start the IDE with gksu while in development mode? I am afraid that a mistake in the code could damage the machine and also it adds extra steps when cross-compiling the app, since I first need to chown it.
I found this article that explains how to use the serial port without root, and this that explains how to use mount without root, but I am wondering if I should follow these recommandation or if there is another way.
Comment: If you can do something without having root, then why use root?
Comment: Because on every machine that I work, I will have to add myself to the group that owns the serial ports and for the mount part I will have to change the code.
Comment: Well, what's your priority here? Security or ease of use?
Comment: I would say both, leaning on security. I know how to achieve either of them, but was wondering if there is a way to get both.
Comment: OK... How about just scripting the mount and group changing parts? Then you can use `sudo` for exactly what it is needed for, and a setup script shouldn't be that difficult or cumbersome.
Comment: Yes, probably this is the way to go, but I am not sure what you mean by scripting the mount part?
Comment: You said something about mounting and having to change the code for that. I wonder why that has to be done within the code.
Comment: The mount should be done in the code. For the device I am writing the code, when a removable media is inserted it is not automatically mounted, so I have to mount it from the code. What I meant by changing the code is to use `pmount` or something similar, as stated in the linked question.
Answer: If at all possible, you should probably develop this from a live DVD/USB so that you don't have to worry about making a mistake. Push your work to a remote server just in case and then do all of your development on the live device so if something goes wrong, you can just wipe it and reinstall it without losing any personal data.


how to validate an accesstoken and facebook id?

Question: I'm building an ios app which uses Django as server. Users login my server use their facebook account. ios app get facebook id and access token first, then I want to send facebook id and access token to my server to validate it. If the facebook id and access token is correct, server will create a user.
My question is :
how to validate facebook id and access token?
e.g. a user whose facebook id is 123 get an accessToken: abc in app, then the app send the info to my server,  how can server validate that the accessToken abc is assigned for 123, not for other facebook id?
Answer: To identify an access_token, make a call to the https://graph.facebook.com/me endpoint with it. Then use the retrieved data to validate the user's id.


iOS. I can´t play an mp3 calling a NSObject class, However it works directly from the UIViewController

Question: I can play an mp3 file with AVAudioPlayer framework directly in the ViewController as an action from a button, but if I want to play the same mp3 calling a selector in a NSObject Class, failed. Thanks for your advice.
Playing an mp3 from the ViewController (audioPlayerDemo.xcodeproj) and it works:
AVFoundation.framework included in the frameworks folder
APDViewController.h
    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVFoundation.h>

    @interface APDViewController : UIViewController <AVAudioPlayerDelegate>
    {
    }
    @property (strong,nonatomic) AVAudioPlayer *audioPlay;

    - (IBAction)play:(id)sender;

APDViewController.m
    @implementation APDViewController

    @synthesize audioPlay;

    - (IBAction)play:(id)sender
    {
        NSError *error = nil;
        NSData *dataAudio = [[NSData alloc] initWithContentsOfFile:
           @"/Users/User/Documents/AudioPlayerDemo/AudioPlayerDemo/hello world.mp3"options:0 error:&error];
        if(error){
            NSLog(@" error loading data: %@ ", [error localizedDescription]);
        }
        else{
            audioPlay = [[AVAudioPlayer alloc] initWithData:dataAudio error:&error];
            if(error){
                NSLog(@" error loading audio: %@ ", [error localizedDescription]);
            }
            else{
                audioPlay.delegate = self;
                [audioPlay prepareToPlay];
                [audioPlay play];
            }
        }
    }

    -(void)audioPlayerDidFinishPlaying:
    (AVAudioPlayer *)player successfully:(BOOL)flag
    {
        if (player == audioPlay){
            audioPlay = nil;
            NSLog(@"audioplay = nil");
        }
    }

But, if I want to play the same .mp3 calling a NSObject class (AudioPlayClass.xcodeproj), there is no error, neither any sound. Here the code that doesn`t work:
AVFoundation.framework included in the frameworks folder
APCplayObject.h
    #import <Foundation/Foundation.h>
    #import <AVFoundation/AVFoundation.h>

    @interface APCplayObject : NSObject <AVAudioPlayerDelegate>
    {
    }
    @property (strong,nonatomic) AVAudioPlayer *audioPlay;

    - (void)playAudio;

    @end

APCplayObject.m
    #import "APCplayObject.h"
    @implementation APCplayObject

    @synthesize audioPlay;

    -(void)playAudio{

        NSError *error = nil;
        NSData *dataAudio = [[NSData alloc] initWithContentsOfFile:
           @"/Users/User/Documents/AudioPlayerClass/AudioPlayerClass/hello world.mp3"options:0 error:&error];
        if(error){
            NSLog(@" error loading data: %@ ", [error localizedDescription]);
        }
        else{
            audioPlay = [[AVAudioPlayer alloc] initWithData:dataAudio error:&error];
            if(error){
                NSLog(@" error loading audio: %@ ", [error localizedDescription]);
            }
            else{
                audioPlay.delegate = self;
                [audioPlay prepareToPlay];
                [audioPlay play];
            }
        }
    }

    -(void)audioPlayerDidFinishPlaying:
    (AVAudioPlayer *)player successfully:(BOOL)flag
    {
        if (player == audioPlay){
            audioPlay = nil;
            NSLog(@"audioplay = nil");
        }
    }

APCviewController.m, the caller as an action from a button:
    - (IBAction)callPlay:(id)sender {
        APCplayObject *a = [[APCplayObject alloc] init];
        [a playAudio];

    }

Thanks in advance.
Answer: The problem is that after you start the audio playing, the variable a goes out of scope and is therefore destroyed.
You need to create a declared property to hold your APCplayObject when the method exits.
So, in APCviewController.h you can do something like this:
@property (strong,nonatomic) APCplayObject *playObject;

And then change callPlay to:
- (IBAction)callPlay:(id)sender {
    if (!self.playObject)  // Use this line if you only want to create one playObject, take it out to create a new one every time.
        self.playObject = [[APCplayObject alloc] init];
    [self.playObject playAudio];

}

Comment: He's using ARC. If he weren't, he wouldn't have noticed his bug as the audio player wouldn't be destroyed on going out of scope as things stand and the "is therefore" wouldn't apply. It used to be you could clumsily autorelease the audio player and pray it lived long enough!
Comment: Exactly. The OP is using ARC, if he weren't he wouldn't have noticed this issue. It's because he's using ARC that your "is therefore" applies.
Comment: In other words, this post should be noted "Assuming you are using ARC, ..." so that boneheads don't take this answer and run with it without using ARC (that's becoming more and more rare these days, but I am still surprised at the amount of times I spot it)
Comment: Well, I never even considered that this might be non-ARC since one of the first lines of his code is `@property (strong,...`.  Thanks for pointing it out for those that it might not be so obvious for though.
Comment: The assumption is correct, I´m using ARC. Thanks for the comments SK9 and borrrden
Comment: Great, welcome to SO!  Since this answers your question, please select the checkmark at the top left of the question to make it as a correct answer.  Glad I could help!
Comment: Yes, thank you, I was just wondering why it's not playing as well and this is exactly the reason!


Remote notification of Sharepoint 2010 update?

Question: I have a business requirement from a client to generate push notifications to Apple devices based on changes to Sharepoint 2010 server. I need to support these notifications in nearly real-time and access a server that is behind a VPN.
I am stumped.
Answer: You need to implement two things, an item event receiver that will detect the changes you are interested in and a APNS notification "service" to send the notification.
The standard way to react to changes in SharePoint is through event receivers. An event receiver implements a specific interface that provides callback functions for specific events.
There are multiple types of events all the way from the site collection level down to the item level.  I assume that you are more interested in item level event receivers.
There are two broad types of events:

Before events (Adding,Changing,Deleting) are synchronous which means that the operation blocks until the event receiver finishes processing.
After events (Added, Changed, etc) are asynchronous and do not block the operation.

You should create an after event receiver that will create an APNS notification and send it.
To send the notification you can use a library like APNS-Sharp. The simplest solution would be to call the library directly from the event receiver. This may be OK if you are not concerned with notifications getting lost due to problems (e.g. connectivity).
A more robust and testable solution would be to put the notifications in a queue and create a separate project (eg. windows service, sharepoint service or even a simple scheduled task) that will read the queue and send the notifications.


make a select object field in salsforce

Question: First, I'm just a beginner in salesforce and started to learn visualforce page using apex,
basically I have the default object "people", and many records in it
now is to write a "payment" visual page to allow people to select the people record
they are master-details relationship, what apex tag should I use in both page side and apex class? similar like time selector one below:
page code:
<apex:inputField value="{!proxyObject.closeDate}"/>

class:
opportunity o = new Opportunity();

public Opportunity getProxyObject() { return o; }

Can any body help me with it? Any kind of suggestions are welcomed!!!
Answer: If you have lookup field from opportunity to people just write on page something like this  <apex:inputField value="{!proxyObject.people__c}"/>
Comment: that's cool! but now I have a B with master detail A, I want to get the value 'balance' in A via B, how should I do? I tried A__c temp = B__c.A__c, but it turns out wrong, can you give me some hints?

make a select object field in salsforce


Programming projects website

Question: Does anybody know of a website where they have a listing of interesting projects that one can do to gradually ramp up your skills, and stuff that is actually interesting. This could be language agnostic or language specific in which case I am looking for C#. A great example of this diveintopython
Answer: Project Euler.
Answer: Project Euler is good, but very mathematical - you'll spend as much time on the maths as on the programming. Definitely spend some time working on those questions, but once you reach your mathematical limit (I reached it fairly quickly, and I thought I was good at maths!) I'd recommend working on some simple games. If you still want a listing, here's one:

Text-based adventure
Tic-tac-toe
Tetris
Pacman
Breakout
Mario
Half-life
Comment: @Justin: I put that on the end as a joke - I forgot my `` tags though :P
Comment: Half-Life is a simple game? I have a feeling that the good folks at Valve Software would disagree.
Answer: Project Euler is a popular choice.
I also like CodingBat (has sections for Java and Python, but you can take the problems and use whatever language you like). Its problems are less like puzzles and more like basic programming concept practice.
Answer: Well, interesting depends on where your interests lie. diveintopython is more of a advanced book than a list of interesting projects that one can do.
If you like math, Project Euler is popular. But if you don't, like me, just look for a problem that you can solve, a tool that you could use personally. All practice can help ramp up your skills, doesn't matter what projects you work on.
Comment: I get your point on DiveIntoPython, what I just meant is that the examples used are very practical and are actually useful

Programming projects website


Direct Determinant of Block Matrix

Question: Prove $|C+\overrightarrow{Y}\overrightarrow{Y}'|=(1+\overrightarrow{Y}'C^{-1}\overrightarrow{Y})|C|$ where $Y$ is a $p \times 1$ vector and $C$ is a non-singular $p \times p$ matrix. See Exercise $4.11$ in $JW$.
$\mathbf{Proof}$
Define the block matrix
$$\mathbf{A}=\begin{pmatrix} C & -\overrightarrow{Y} \\ \overrightarrow{Y}^{'} & 1 \end{pmatrix}$$
Problem 4.11 in JW asserts that for any square block matrix $\mathbf{B}$:
$$|\mathbf{B}|=|\mathbf{B}_{11}||\mathbf{B}_{22}-\mathbf{B}_{21}\mathbf{B}_{11}^{-1}\mathbf{B}_{12}|$$
Using the result of $4.11$ we have that:
$$|\mathbf{A}|=|C||1-\overrightarrow{Y}^{'}C^{-1}\overrightarrow{Y}|=|C|(1-\overrightarrow{Y}^{'}C^{-1}\overrightarrow{Y})$$
I understand that for any block matrix $\mathbf{B}=\begin{pmatrix} A & B \\ C & D \end{pmatrix}$ it is not always the case that $|\mathbf{B}|$=AD-BC. Knowing this, I am confused on how I can evaluate the determinant of $\mathbf{A}$ without making use of the result of 4.11 so that $|\mathbf{A}|=|C+\overrightarrow{Y}\overrightarrow{Y}'|$ as desired.
Answer: You can factorise the underlying matrix as
$$
\pmatrix{C & 0\\0 &1}
\pmatrix{I & 0\\y^{T}&1}
\pmatrix{I & -C^{-1}y\\0^{T} & y^{T}C^{-1}y+1}
$$
and then all is clear.
Comment: Thank you! This was incredibly helpful

Direct Determinant of Block Matrix


Adding an item breaks getFilter() method

Question: Problem: Adding a list item prevents filter method from working. Otherwise the filter works correctly.
Expected: That the items and database are correctly updated from the both add item and filter methods.
Tested:

Filter on current list works and applies the layout.
Filter on filtered list works  and applies the layout.
Filter with no constraint loads the full list and applies the layout.
Adding item before filter works and applies the layout.
Adding item after filter works and applies the layout.
Filter after adding item fails to filter results and applies no changes to the layout. No run time errors are provided.

Probable Solution: I thought I was missing an assignment to the items list to grab the updated version of the list. After checking it seems that both add item and filter methods are grabbing the updated list. I am starting to think I don't understand how the filter method works and that I am missing a method or line that the filter needs to refresh. Would appreciate suggestions on how to find what I am missing.
<code>private void addProjectItem() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.project_add_layout, null);

        final EditText title = view.findViewById(R.id.addProjectTitle);
        final EditText description = view.findViewById(R.id.addProjectDescription);

        builder.setNegativeButton(
                android.R.string.cancel,
                (dialog, which) -> dialog.cancel()
        );

        builder.setPositiveButton(
                android.R.string.ok,
                (dialog, which) -> {
                    if (!title.getText().toString().isEmpty() && !description.getText().toString().isEmpty()) {
                        ProjectItem item = new ProjectItem(
                                title.getText().toString(),
                                description.getText().toString(),
                                appDataManager.getUid(),
                                false
                        );

                        projectListManager.addItem(item);
                        adapter.updateItems(projectListManager.getList());
                    } else {
                        Toast.makeText(SecondActivity.this, projectAddError, Toast.LENGTH_SHORT).show();
                    }
                }
        );

        builder.setView(view);
        builder.show();
    }

    private class ProjectItemAdapter extends ArrayAdapter<ProjectItem> implements Filterable {
        private Context context;
        private List<ProjectItem> items;

        private ImageButton projectCompleteButton;
        private ImageButton projectDescriptionButton;
        private TextView itemTitle;
        private ImageButton projectJoinButton;

        private ProjectItemAdapter( Context context, List<ProjectItem> items) {
            super(context, -1, items);

            this.context = context;
            this.items = items;
        }

        @NonNull
        @Override
        public Filter getFilter() {
            return projectFilter;
        }

        private final Filter projectFilter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();

                List<ProjectItem> found = new ArrayList<>();

                if(constraint == null || constraint.length() == 0) {
                    found.addAll(projectListManager.getList());
                } else {
                    String filterPattern = constraint.toString().toLowerCase().trim();

                    for(ProjectItem item : items){
                        if(item.getTitle().toLowerCase().contains(filterPattern)) {
                            found.add(item);
                        }
                    }
                }

                results.values = found;
                results.count = found.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                clear();
                addAll((List)results.values);
                notifyDataSetChanged();
            }
        };

        public void updateItems(List<ProjectItem> items) {
            this.items = items;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            // Removed as there is nothing that manipulates the list item.
            return convertView;
        }
    }
}
</code>
Answer: Problem was with the publish results not referencing the items list and properly casting results as a collections.
Solution:
<code>@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
    items.clear();

    items.addAll((Collection<? extends ProjectItem>) results.values);

    notifyDataSetChanged();
}
</code>


Flattening object and limitting number of nesting

Question: I would like to limit number of flattened structures inside an object. Consider example below.
Input:
const exampleObj = {
  foo: {
    bar: {
      biz: "hello"
    }
  }
};

Output:
{foo_bar_biz: "hello"}

I wanted to set a limiter (limit = 2) so that function will stop performing recursive function and return something like this
{foo_bar: "[Object] object"}

Here's a snippet:

const { useState, useEffect} = React;

const exampleObj = {
  foo: {
    bar: {
      biz: "hello"
    }
  }
};

let limit = 0;

function App() {
  const [state, setState] = useState({});

  useEffect(() => {
    flatten(exampleObj);
  }, []);

  const flatten = (data, parent, result = {}) => {
    for (let key in data) {
      const propName = parent ? parent + "_" + key : key;
      if (typeof data[key] === "object") {
        limit++;
        if (limit <= 1) {
          flatten(data[key], propName, result);
        } else {
          setState(prevState => {
            return {
              ...prevState,
              [propName]:
                typeof data[key] === "object" ? "[Object] object" : data[key]
            };
          });
        }
      } else {
        result[propName] = data[key];
        setState({
          ...state,
          [propName]: data[key]
        });
      }
    }
  };

  console.log(state);

  return (

Start editing to see some magic happen :)

  );
}

ReactDOM.render(<App />, document.getElementById("root"));

I've prepared a solution for that, but it is quite cumbersome. https://stackblitz.com/edit/react-u5klvc
Comment: How is react at all relevant here? This could be a simple question about data structures and changing them?
Comment: Maybe this example will help you. It splits the *flattening* from the react part. If this is anywhere near of what you're trying to do, let me know. Maybe it warrants an answer. https://codesandbox.io/s/gracious-galois-gyc0v?file=/src/App.js
Comment: Please add the relevant code here as well. If the external link is deleted or modified, the question will have no future value. You can also create [a runnable stack snippet](https://meta.stackoverflow.com/questions/358992)
Comment: Or if a visitor cannot open the link for any other reason, like it's being blocked.
Comment: Ahh sorry, this link should work https://stackblitz.com/edit/react-td5w6j?file=src/App.js
Comment: The problem isn't the *link* - the policy on Stack Overflow is to have the entire information for the post ***in*** the post. Visitors shouldn't need to go off-site to get context for the question.
Comment: The link works just fine. I meant the link might not work in the future for some reason ([Link rot](https://en.wikipedia.org/wiki/Link_rot))
Comment: Also, there are many solutions here: [Fastest way to flatten / un-flatten nested JSON objects](https://stackoverflow.com/questions/19098797) You just need to add the limit logic in there.
Comment: @adiga as a reminder, even *if* the link works, a visitor might still be unable to follow it because they might have it blocked on their network for whatever reason.
Comment: Okey, I get it. I will add full information regarding the problem next time.
Comment: @Yoshi they are doing `setState` inside the recursive function. (Not sure why. It could be moved outside and set once the final output is returned)
Comment: That's what I mean. It would be a lot simpler to handle the restructuring and simple call `setState` on the final result.
Comment: Thanks for the effort put in doing this example. This is almost what I needed thank you very much. The only part that was changed is
`[`${outer}_${inner}`]: isObject(value) ? "[Data not flattened]" : value`
Answer: Here's one possible implementation of flatten. Notice how it's completely decoupled from React or a specific React component. It works on any JavaScript objects -
const snakecase = s =>
  s.join("_")

const flatten = (t = {}, n = Infinity, join = snakecase) =>
{ const many = (t, n, path) =>
    n >= 0 && Object(t) === t
      ? Object.entries(t).flatMap(_ => one(_, n - 1, path))
      : [ [ join(path), t ] ]

  const one = ([ k, v ], n, path) =>
    many(v, n, [...path, k])

  return Object.fromEntries(many(t, n, []))
}

Given some example data -
const data =
  { a1: 11
  , a2: { b1: 21, b2: 22 }
  , a3: { b1: { c1: 311, c2: 312 }
        , b2: { c1: 321, c2: 322, c3: { d1: 3231 } }
        }
  }

A depth of 1 flattens one level -
flatten(data, 1)

{
  "a1": 11,
  "a2_b1": 21,
  "a2_b2": 22,
  "a3_b1": {
    "c1": 311,
    "c2": 312
  },
  "a3_b2": {
    "c1": 321,
    "c2": 322,
    "c3": {
      "d1": 3231
    }
  }
}

A depth of 2 flattens two levels -
flatten(data, 2) // => ...

{
  "a1": 11,
  "a2_b1": 21,
  "a2_b2": 22,
  "a3_b1_c1": 311,
  "a3_b1_c2": 312,
  "a3_b2_c1": 321,
  "a3_b2_c2": 322,
  "a3_b2_c3": {
    "d1": 3231
  }
}

The default depth is inifinity -
flatten(data) // => ...

{
  "a1": 11,
  "a2_b1": 21,
  "a2_b2": 22,
  "a3_b1_c1": 311,
  "a3_b1_c2": 312,
  "a3_b2_c1": 321,
  "a3_b2_c2": 322,
  "a3_b2_c3_d1": 3231
}

The default join is snakecase, but the parameter can be specified at the call site -
const camelCase = ([ first = "", ...rest ]) =>
  first + rest.map(upperFirst).join("")

const upperFirst = ([ first = "", ...rest ]) =>
  first.toUpperCase() + rest.join("")

flatten(data, 2, camelCase) // => ...

{
  "a1": 11,
  "a2B1": 21,
  "a2B2": 22,
  "a3B1C1": 311,
  "a3B1C2": 312,
  "a3B2C1": 321,
  "a3B2C2": 322,
  "a3B2C3": {
    "d1": 3231
  }
}

Expand the snippet below to verify the results in your own browser -

const data =
  { a1: 11
  , a2: { b1: 21, b2: 22 }
  , a3: { b1: { c1: 311, c2: 312 }
        , b2: { c1: 321, c2: 322, c3: { d1: 3231 } }
        }
  }

const snakecase = s =>
  s.join("_")

const flatten = (t = {}, n = Infinity, join = snakecase) =>
{ const many = (t, n, path) =>
    n >= 0 && Object(t) === t
      ? Object.entries(t).flatMap(_ => one(_, n - 1, path))
      : [ [ join(path), t ] ]

  const one = ([ k, v ], n, path) =>
    many(v, n, [...path, k])

  return Object.fromEntries(many(t, n, []))
}

const result =
  flatten(data, 2)

console.log(JSON.stringify(result, null, 2))
Comment: Haha I know the feeling. But it's not a competition  Your solution of combining other generics is great demonstration of how functions can build upon each other.
Comment: No, and I'm not really feeling competitive.  We are attracted to the same sorts of questions, and have an interesting mix of answers which are very similar to one another's and those very different from one another's.  It's quite fun, in fact.
Answer: Thankyou's answer is great.  But this is enough different to be worth posting, I think.
I keep handy functions like path and getPaths in my personal library.  For this, I had to alter getPaths to accept a depth parameter (d) to escape earlier.
With these and Object.fromEntries we can easily write a partialFlatten function that does what I think you want:

const path = (ps = []) => (obj = {}) =>
  ps .reduce ((o, p) => (o || {}) [p], obj)

const getPaths = (obj, d = Infinity) =>
  Object (obj) === obj && d > 0
    ? Object .entries (obj) .flatMap (
        ([k, v]) => getPaths (v, d - 1) .map (p => [Array.isArray(obj) ? Number(k) : k, ...p])
      )
    : [[]]

const partialFlatten = (obj, depth) =>
  Object .fromEntries (
    getPaths (obj, depth) .map (p => [p .join ('_'), path (p) (obj)])
  )

const exampleObj = {foo: {bar: {biz: "hello"}, baz: 'goodbye'}}

console .log ('depth 1:', partialFlatten (exampleObj, 1))
console .log ('depth 2:', partialFlatten (exampleObj, 2))
console .log ('depth 3:', partialFlatten (exampleObj, 3))
.as-console-wrapper {max-height: 100% !important; top: 0}