Q: $2$ dimensional foliations of space whose leaves contain the trajectories of a given vector field Assume that $X$ is a non-vanishing vector field on $\mathbb{R}^3$.

Is there a $2$-dimensional foliation of space such that every trajectory of $X$ is contained in a leaf of the $2$-dimensional foliation?

As a related question:

Is there a classification of all $1$-dimensional foliations of space tangent to the unit speed vector field $t$ for which the distributions $\{t,n\}$ and $\{t,b\}$ are integrable? Here $\{t,n,b\}$ is the associated Frenet frame.

A: No. For a counterexample, start with the Hopf map $S^3\to S^2$, a fiber bundle with $S^1$ fibers. Its fibers are the leaves of a $1$-dimensional foliation of $S^3$ in which all leaves are closed and the space of leaves is $S^2$. Choose a vector field tangent to the leaves. Remove one point from $S^3$ to get $\mathbb R^3$. A $2$-dimensional foliation of the kind asked for would give a $1$-dimensional foliation of $S^2$.


Q: Bash Regex to print out the matched string only? Im trying to read a file line by line and trying to match few strings,and im not able to echo the matched line using "$?" im not sure which "$" function to use. can anyone help? i dont want using grep, thanks in advance.
#!/usr/bin/bash
while read EachLine
    do
    if [[ "$EachLine =~ ^Pass: [0-9]\{1,\}" ]]
        then
    echo "$?"
    fi
    done < zoix.progress-N0
exit

A: If you just want to put out the lines that match your pattern in a file, have you tried the following:
grep -E "^Pass: [0-9]+" zoix.progress-N0


Q: hibernate validator, json schema generation and using common constraints We use Spring MVC, Jackson for json, Hibernate ORM. We need to add front end validations. I came across hibernate validator.
We have a set of Domain classes [DO classes] annotated with JPA.
We have another set of POJO classes [DTO classes] annotated for Json binding.
We want to implement infrastructure that does the following:

*

*DTO classes refer to the DO class constraints [where applicable] so that the truth is one place.

*Generate json schema , again by reusing the JPA annotations.

*Validate input to the rest calls.

For example, instead of the following:
PersonDTO{
  @NotNull
    @Size(min=2, max=60)
    private String firstName;
}

How about:
PersonDTO{
   @MapsTo(com.xyz.domain.PersonDO.firstName.Size) // referring to the JPA annotation
   private String firstName;
}

And then, a custom validator figures out the constraints to uphold by looking at the JPA annotation.
Is the strategy I outlined a typical approach? Any feedback or opinions is appreciated. Can you point me to relevant any articles?
Thank you.

A: There is no out-of-the-box functionality for copying constraints from one model to another in Hibernate Validator, but you could implement it yourself using existing APIs.
More specifically, there is an API for retrieving constraint metadata (standardized by Bean Validation) and an API for dynamically putting constraints to your types at runtime (provided by Hibernate Validator). You could use the former to read the constraints of your domain model and drive the creation of equivalent constraints on your DTO model using the latter. For that you'd of course need a strategy for matching corresponding types and properties of your source and target model.


Q: Help regarding test case code coverage public with sharing class searchpn {
    //variables
    Public Id parentId;
    public Integer qliRowNum1{get;set;}
    public Integer qliRowNum{get;set;}
    public Integer finalRowNum{get;set;}
    public Integer rowToClone{get;set;}
    Public Integer deleteBatchRow{get;set;}
    Public Integer deleteQliRow{get;set;}
    //map variables
    Public Map<Integer,Quote_line_Item__c> qouteLineItemMap{get;set;}
    public Map<integer,List<Batch__c>> batchMap{get;set;}
    //List variables
    public List<Batch__c> batchListTodelete;
    public List<Quote_line_Item__c> qliListtoDelete;
     public List<QuoteWrapper> QuoteWrapperList{get;set;}
     public List<QuoteWrapperOne> QuoteWrapperListOne{get;set;}
    public List<QuoteWrapperTwo> QuoteWrapperListTwo{get;set;}
    // constructor declaration
    public searchpn(ApexPages.StandardsetController controller) {}

    public void PNSearch(){
        //varible declarations
        parentId=Apexpages.currentPage().getParameters().get('id');
        //Query to retrieve all Quote line Items which are childs to current Quote
        list< Quote_line_Item__c> allQliList=[Select id,Name,Client_P_N__c,Comments__c,Quote1__c,Quote_Validity__c ,Description__c,Standard_Estimated_Lead_Time__c,createdDate,Other_Lead_Time__c  from Quote_Line_Item__c where Quote1__c=:parentId ORDER BY CreatedDate ] ;

        set<string> qliNameSet =new set<string>();
        List<String> qliNameList=new List<String>();
        list<Quote_line_Item__c> matchQliList=new list<Quote_line_Item__c>();
        List<Quote__c> QuoteList=new List<Quote__c>();
        Set<Id> nonMatchedQutIds=new Set<Id>();
        Set<id> QlId=new Set<Id>();
        Quote__c currentQuote;
        //creating instance to wrpper classes
        QuoteWrapperListTwo=new List<QuoteWrapperTwo>();
        QuoteWrapperListOne=new List<QuoteWrapperOne>();
        QuoteWrapperList=new List<QuoteWrapper>();
        // Declaring and creating instance to map
        map<id,List<Quote_line_Item__c>> allMatchedQlis= new map<id,List<Quote_line_Item__c>>();
        try{
            currentQuote=[select Account_Name__r.Name,id from Quote__c where id=:ParentId LIMIT 1];
        }catch(Exception e){System.debug('<----Quote exception------>'+e); }
        //condition to check quote lIne item  map size is greater than zero
        if(allQliList.size()>0){
            //iterating the loop to store the name quote line items in list and in set
            for(Quote_line_Item__c qli:allQliList){
                qliNameSet.add(qli.Name);
                qliNameList.add(qli.Name);
            }//End of for loop
            // Query to get all quoteline items  which are matched with current Quote line items names
            try{
                matchQliList=[Select id,Name,Quote1__r.Quote_Number_New__c,Quote1__r.Account_Name__c,Quote1__r.Account_Name__r.Name,Quote1__r.createdDate,Quote1__r.Name,Quote1__c from Quote_line_Item__c where Quote1__c!=:ParentId And Name in:qliNameSet];
            }catch(Exception e){ system.debug('<----Quote line item exception--------- >'+e);}
            //Iterating the loop to store the Quote ids in to the set
            for(Quote_line_Item__c q:matchQliList){
                QlId.add(q.Quote1__c);
            }
            //Query to get all quoteline items  which are matched with current Quote line items names
            try{
                QuoteList=[Select id,Quote_Number_New__c,Account_Name__c,Account_Name__r.Name,createdDate,(select id,Name,Quote1__r.Quote_Number_New__c,Quote1__r.Account_Name__c,Quote1__r.Account_Name__r.Name,Quote1__r.createdDate,Quote1__r.Name from Quote__c.Quote_line_Items__r) from Quote__c where id in:QlId ORDER BY CreatedDate  desc LIMIT 50000];
            }catch(Exception e){ System.debug('<***** Quote line item exception****>'+e);}
            //Iterating the loop to place the quote line items in a map with key as Quote id and value as quoteline items
            for(Quote__c qut:QuoteList){
                List<Quote_line_Item__c> qliList=new List<Quote_line_Item__c>();
                for(Quote_line_Item__c ql:qut.Quote_line_Items__r){
                    qliList.add(ql);
                }//End of for loop
                allMatchedQlis.put(qut.id,qliList);
            }//End of for loop
            //iterating the map to seperate the Quote values which have exact match with the current quote and non exact quotes
            for(Id mapkey:allMatchedQlis.keyset()){
                String accName=allMatchedQlis.get(mapkey)[0].Quote1__r.Account_Name__r.Name;
                List<String> dupQliNameList=new List<String>();
                //Iterating the loop to store all the Quoteline item's names for each quote
                for(Quote_line_Item__c qli:allMatchedQlis.get(mapkey)){
                    dupQliNameList.add(qli.Name);
                }//End of for loop
                // sorting the lists which helps us to compare the current QUote line item name with other Quote child Quotelineitem's name
                dupQliNameList.sort();
                qliNameList.sort();
                //condition to check for exact match
                if(qliNameList.equals(dupQliNameList)&& allMatchedQlis.get(mapkey).size()==qliNameList.size()){
                    // condition to check with the current account name and Adding values to display exact match with same accont
                    if(accName==currentQuote.Account_Name__r.Name && mapkey!=ParentId){
                        QuoteWrapperTwo qwt=new QuoteWrapperTwo();
                        qwt.Quote_Name_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Name;
                        qwt.Quote_Id_Two=allMatchedQlis.get(mapkey)[0].Quote1__c;
                        qwt.Account_Name_Two=accName;
                        qwt.Account_Id_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Account_Name__c;
                        qwt.Quote_Num_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Quote_Number_New__c;
                        qwt.Count_Two=qliNameList.size();
                        qwt.CR_Date_Two=Date.valueOf(allMatchedQlis.get(mapkey)[0].Quote1__r.CreatedDate);
                        QuoteWrapperListTwo.add(qwt);
                    }//End of if
                    //Adding values to display exact match with different accont
                    else{
                        QuoteWrapperOne qwt=new QuoteWrapperOne();
                        qwt.Quote_Name_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Name;
                        qwt.Quote_Id_One=allMatchedQlis.get(mapkey)[0].Quote1__c;
                        qwt.Account_Name_One=accName;
                        qwt.Account_Id_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Account_Name__c;
                        qwt.Quote_Num_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Quote_Number_New__c;
                        qwt.Count_One=qliNameList.size();
                        qwt.CR_Date_One=Date.valueOf(allMatchedQlis.get(mapkey)[0].Quote1__r.CreatedDate);
                        QuoteWrapperListOne.add(qwt);
                    }
                }//End of if
                //Storing non exact matched quote ids into a set
                else {
                    nonMatchedQutIds.add(mapkey);
                }
            }//End of for loop
            //Query to get the Quote values in descending order depending on the counting of Quotelineitem names  which are in non exact match
            AggregateResult[] groupedResults   = [SELECT   COUNT_DISTINCT(Name) nameCount,count( Id ) idCount  ,Min( Quote1__r.Name  )   QuoteName  ,Min( Quote1__c  )   QuoteId  ,Min( Quote1__r.Account_Name__r.Name ) AccountName, Min( Quote1__r.Account_Name__c ) AccountId ,Min(Quote1__r.Quote_Number_New__c)QuoteNum, MIN(Quote1__r.CreatedDate) CRDate  FROM Quote_Line_Item__c  where   ( name in :qliNameSet  AND Quote1__c != null AND  Quote1__c in :nonMatchedQutIds)  Group By Quote1__r.Id ORDER BY COUNT_DISTINCT(Name) desc, MIN(Quote1__r.CreatedDate)desc];
            //Iterating the loop to display non exact matched quotes
            for(AggregateResult aggr:groupedResults){
                QuoteWrapper qw=new QuoteWrapper();
                qw.Quote_Name=String.valueOf(aggr.get('QuoteName'));
                qw.Quote_Id=String.valueOf(aggr.get('QuoteId'));
                qw.Account_Name=String.valueOf(aggr.get('AccountName'));
                qw.Account_Id=String.valueOf(aggr.get('AccountId'));
                qw.Quote_Num=String.valueOf(aggr.get('QuoteNum'));
                qw.Count=Integer.valueOf(aggr.get('nameCount'));
                qw.CR_Date=Date.valueOf(aggr.get('CRDate'));
                QuoteWrapperList.add(qw);
            }//End of for loop
        }//End of if
    }//End of method
    // Method to save the QuoteLineItems as well as batches
    //Wrapper class to display non exact matched Quotes
      public class QuoteWrapper {
        Public string Quote_Name{get;set;}
        Public string Quote_Id{get;set;}
        Public string Account_Name{get;set;}
        Public string Account_Id{get;set;}
        Public string Quote_Num{get;set;}
        Public Integer Count{get;set;}
        Public Date CR_Date{get;set;}
    }//End of class
       public PageReference cancel1(){
        PageReference pgr = new PageReference('/'+parentId);
        pgr.setRedirect(True);
        return pgr;
    }
    //Wrapper class to display exact match wtih another account
     public class QuoteWrapperOne {
        Public string Quote_Name_One{get;set;}
        Public string Quote_Id_One{get;set;}
        Public string Account_Name_One{get;set;}
        Public string Account_Id_One{get;set;}
        Public string Quote_Num_One{get;set;}
        Public Integer Count_One{get;set;}
        Public Date CR_Date_One{get;set;}
    }//End of class
    //Wrapper class to display exact match with same account
    public class QuoteWrapperTwo {
        Public string Quote_Name_Two{get;set;}
        Public string Quote_Id_Two{get;set;}
        Public string Account_Name_Two{get;set;}
        Public string Account_Id_Two{get;set;}
        Public string Quote_Num_Two{get;set;}
        Public Integer Count_Two{get;set;}
        Public Date CR_Date_Two{get;set;}
    }//End of wrapper class
}//End of main class

Test class:
@IsTest
private class Testsearcpn{
    static testmethod void testMethod1(){
        Test.startTest();
        Account acc=new account(Name='NicoTestacc',BillingCountry='India');
        insert acc;
        System.assertEquals(acc.name,'NicoTestacc');

        Account acc1=new account(Name='kvptestacc1',BillingCountry='China');
        insert acc1;
        System.assertEquals(acc1.name,'kvptestacc1');

        Opportunity op= new opportunity(Name='NicoTestOpp',CloseDate=date.today(),StageName='Qualification',Product_Type__c='DPI',Accountid=acc.Id);
        insert op;
        System.assertEquals(op.name,'NicoTestOpp');

        Opportunity op1= new opportunity(Name='NicoTestOpp',CloseDate=date.today(),StageName='Qualification',Product_Type__c='DPI',Accountid=acc1.Id);
        insert op1;
        System.assertEquals(op1.name,'NicoTestOpp');

        Quote__c q1 = New Quote__c (Opportunity_Name__c = op.Id,Account_Name__c = acc.Id,Subject__c='ABCD');
        insert q1;
        System.assertEquals(q1.Subject__c,'ABCD');

        Quote__c q2 = New Quote__c (Opportunity_Name__c = op1.Id,Account_Name__c = acc1.Id,Subject__c='ABCD');
        insert q2;
        System.assertEquals(q2.Subject__c,'ABCD');

        Quote__c q3 = New Quote__c (Opportunity_Name__c = op.Id,Account_Name__c = acc.Id,Subject__c='ABCD');
        insert q3;
        System.assertEquals(q3.Subject__c,'ABCD');

        Quote_Line_Item__c  qll = new Quote_Line_Item__c (Name='test',Quote1__c = q1.id);
        insert qll;
        System.assertEquals(qll.name,'test');

        Quote_Line_Item__c  ql2 = new Quote_Line_Item__c (Name=qll.Name,Quote1__c = q1.id);
        insert ql2;
        System.assertEquals(ql2.name,'test');
        batch__c bat =new batch__c( Asked_Qty__c ='1111',Quote_Line_Item__c = qll .id);
        insert bat;
        System.assertEquals(bat.Asked_Qty__c ,'1111');

        batch__c bat1 =new batch__c( Asked_Qty__c ='222',Quote_Line_Item__c = ql2 .id);
        insert  bat1;
        Test.stopTest();
        System.assertEquals(bat1.Asked_Qty__c ,'222');
        list<Quote_line_item__c> tst=[select id from quote_line_item__c where id =:qll.id];
                ApexPages.StandardsetController sc = new ApexPages.StandardsetController(tst);
        ApexPages.currentPage().getParameters().put('CF00NN0000000KbJB_lkid',q1.Id);
        searchpn nqlibc=new searchpn(sc);
        searchpn.QuoteWrapper qw=new searchpn.QuoteWrapper();
        searchpn.QuoteWrapperOne qwo=new searchpn.QuoteWrapperOne();
        searchpn.QuoteWrapperTwo qwt=new searchpn.QuoteWrapperTwo();
           nqlibc.PNSearch();
            nqlibc.cancel1();
    }

This sections in controller not covering in test class
if(qliNameList.equals(dupQliNameList)&& allMatchedQlis.get(mapkey).size()==qliNameList.size()){
                        // condition to check with the current account name and Adding values to display exact match with same accont
                        if(accName==currentQuote.Account_Name__r.Name && mapkey!=ParentId){
                            QuoteWrapperTwo qwt=new QuoteWrapperTwo();
                            qwt.Quote_Name_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Name;
                            qwt.Quote_Id_Two=allMatchedQlis.get(mapkey)[0].Quote1__c;
                            qwt.Account_Name_Two=accName;
                            qwt.Account_Id_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Account_Name__c;
                            qwt.Quote_Num_Two=allMatchedQlis.get(mapkey)[0].Quote1__r.Quote_Number_New__c;
                            qwt.Count_Two=qliNameList.size();
                            qwt.CR_Date_Two=Date.valueOf(allMatchedQlis.get(mapkey)[0].Quote1__r.CreatedDate);
                            QuoteWrapperListTwo.add(qwt);
                        }//End of if
                        //Adding values to display exact match with different accont
                        else{
                            QuoteWrapperOne qwt=new QuoteWrapperOne();
                            qwt.Quote_Name_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Name;
                            qwt.Quote_Id_One=allMatchedQlis.get(mapkey)[0].Quote1__c;
                            qwt.Account_Name_One=accName;
                            qwt.Account_Id_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Account_Name__c;
                            qwt.Quote_Num_One=allMatchedQlis.get(mapkey)[0].Quote1__r.Quote_Number_New__c;
                            qwt.Count_One=qliNameList.size();
                            qwt.CR_Date_One=Date.valueOf(allMatchedQlis.get(mapkey)[0].Quote1__r.CreatedDate);
                            QuoteWrapperListOne.add(qwt);
                        }
                    }//End of if
                    //Storing non exact matched quote ids into a set
                    else {
                        nonMatchedQutIds.add(mapkey);
                    }
                }//End of for loop
                //Query to get the Quote values in descending order depending on the counting of Quotelineitem names  which are in non exact match
                AggregateResult[] groupedResults   = [SELECT   COUNT_DISTINCT(Name) nameCount,count( Id ) idCount  ,Min( Quote1__r.Name  )   QuoteName  ,Min( Quote1__c  )   QuoteId  ,Min( Quote1__r.Account_Name__r.Name ) AccountName, Min( Quote1__r.Account_Name__c ) AccountId ,Min(Quote1__r.Quote_Number_New__c)QuoteNum, MIN(Quote1__r.CreatedDate) CRDate  FROM Quote_Line_Item__c  where   ( name in :qliNameSet  AND Quote1__c != null AND  Quote1__c in :nonMatchedQutIds)  Group By Quote1__r.Id ORDER BY COUNT_DISTINCT(Name) desc, MIN(Quote1__r.CreatedDate)desc];
                //Iterating the loop to display non exact matched quotes
                for(AggregateResult aggr:groupedResults){
                    QuoteWrapper qw=new QuoteWrapper();
                    qw.Quote_Name=String.valueOf(aggr.get('QuoteName'));
                    qw.Quote_Id=String.valueOf(aggr.get('QuoteId'));
                    qw.Account_Name=String.valueOf(aggr.get('AccountName'));
                    qw.Account_Id=String.valueOf(aggr.get('AccountId'));
                    qw.Quote_Num=String.valueOf(aggr.get('QuoteNum'));
                    qw.Count=Integer.valueOf(aggr.get('nameCount'));
                    qw.CR_Date=Date.valueOf(aggr.get('CRDate'));
                    QuoteWrapperList.add(qw);
                }//End of for loop
            }//End of if

Can any body help to get the code coverage for the controller
Thankyou in advance.

A: Here is the issue:
Your controller expects to get a parameter with key = 'id'
public void PNSearch(){
    //varible declarations
    parentId=Apexpages.currentPage().getParameters().get('id');

Yet your test method creates a parameter with a different key:
ApexPages.currentPage().getParameters().put('CF00NN0000000KbJB_lkid',q1.Id);
    searchpn nqlibc=new searchpn(sc);
    searchpn nqlibc=new searchpn(sc);
    searchpn.QuoteWrapper qw=new searchpn.QuoteWrapper();
    searchpn.QuoteWrapperOne qwo=new searchpn.QuoteWrapperOne();
    searchpn.QuoteWrapperTwo qwt=new searchpn.QuoteWrapperTwo();
    nqlibc.PNSearch();

hence parentId in the controller is null
You can also simplify your testmethod somewhat by doing bulk operations, for example
List<Quote__c> qList = new List<Quote__c> {
  new Quote__c(Opportunity_Name__c = oList[0].Id,Account_Name__c = aList[0].Id,Subject__c='ABCD'),
  new Quote__c (Opportunity_Name__c = oList[1].Id,Account_Name__c = aList[1].Id,Subject__c='ABCD'),
  new Quote__c (Opportunity_Name__c = oList[0].Id,Account_Name__c = aList[0].Id,Subject__c='ABCD')
};
insert qList;

and equivalent for the accounts, opportunities, and quote items. This helps avoid too many SOQL limits in test methods, and verifies your triggers on these objects, if any, are properly bulkified
and lastly, in Quote__c, the field opportunity_name__c is not best practice for naming an ID field (confuses the reader in thinking it is the opportunity name - a text field) . SFDC convention would be to name this field opportunity__c.


Q: C++ A multiple inheritance pproblem with pure virtual functions I have produced a minimal example to replicate the problem I am seeing with a more complex class hierarchy structure:
#include <string>
#include <iostream>

class A
{
protected:

    virtual
    ~A() = 0;

};

inline
A::~A() {}

class B : public A
{
public:

    virtual
    ~B()
    {
    }

    std::string B_str;
};

class BB : public A
{
public:

    virtual
    ~BB()
    {
    }

    std::string BB_str;
};

class C : public A
{
protected:

    virtual
    ~C()
    {
    }

    virtual
    void Print() const = 0;
};

class D : public B, public BB, public C
{
public:

    virtual
    ~D()
    {
    }
};

class E : public C
{
public:

    void Print() const
    {
        std::cout << "E" << std::endl;
    }
};

class F : public E, public D
{
public:

    void Print_Different() const
    {
        std::cout << "Different to E" << std::endl;
    }

};

int main()
{

    F f_inst;

    return 0;
}

Compiling with g++ --std=c++11 main.cpp produces the error:
error: cannot declare variable ‘f_inst’ to be of abstract type ‘F’

    F f_inst;

note:   because the following virtual functions are pure within ‘F’:

    class F : public E, public D
          ^
note:   virtual void C::Print() const

    void Print() const = 0;
         ^

So the compiler thinks that Print() is pure virtual.
But, I have specified what Print() should be in class E.
So, I've misunderstood some of the rules of inheritance.
What is my misunderstanding, and how can I correct this problem?
Note: It will compile if I remove the inheritance : public D from class F.

A: Currently your F is derived from C in two different ways. This means that an F object has two separate C bases, and so there are two instances of C::Print().
You only override the one coming via E currently.
To solve this you must take one of the following options:

*

*Also override the one coming via D, either by implementing D::Print() or F::Print()

*Make Print non-pure

*Use virtual inheritance so that there is only a single C base.

For the latter option, the syntax adjustments would be:
class E : virtual public C

and
class D : public B, public BB, virtual public C

This means that D and E will both have the same C instance as their parent, and so the override E::Print() overrides the function for all classes 'downstream' of that C.
For more information , look up "diamond inheritance problem".  See also Multiple inheritance FAQ


Q: Recording Xero check payments via payments endpoint - will they automatically match bank statement? I'm trying to work around the Xero API's lack of support for payment via checks.
If I use the payments endpoint to create and apply new payments to existing invoices, and as part of the PUT add the check number to the reference field, does anyone know if that will be automatically matched when the check is cashed and shows up in our bank statement feed? I can't find Xero's internal reconciliation rules detailed anywhere.
Our issue is that we write about 2k checks per month and many have the same amounts, so we rely on the check number to match and reconcile. Currently Xero automatically matches 95%+ of our checks to bank statement lines we get via our bank feed. My concern is that without a check number linked to the API-created payment, Xero won't match checks to the correct bank statement items, and then we've got 2,000 payments that have to each be reconciled by manual searches for the reference number.
I've imported a test CSV bank rec file and that matched 3 of 3 test payments, but need to explore this more using identical amounts. In the demo company I could create 1,000 bill payments, apply 1,000 payments to them, and import 1,000 statement lines and see how the reconciliation screen looks, but wanted to see if someone already knew the answer!
(I believe we'll also lose the ability to quickly search payments via the check register but we may have to accept that. We send our check list to an outside printing/mailing firm so don't actually need to print the checks in Xero.)


Q: convert Json object to java object: The logic I have a json weather API that forecasts five days every three hours. I put part of the json with two forcasts since it is too long and repetitive:
{

    "cod": "200",
    "message": 0.4194,
    "city": {
        "id": 1851632,
        "name": "Shuzenji",
        "coord": {
            "lon": 138.933334,
            "lat": 34.966671
        },
        "country": "JP",
        "population": 0
    },
    "cnt": 40,
    "list": [
        {
            "dt": 1399950000,
            "main": {
                "temp": 287.82,
                "temp_min": 287.82,
                "temp_max": 287.82,
                "pressure": 923.74,
                "sea_level": 1018.93,
                "grnd_level": 923.74,
                "humidity": 100,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 501,
                    "main": "Rain",
                    "description": "moderate rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 92
            },
            "wind": {
                "speed": 0.51,
                "deg": 226.005
            },
            "rain": {
                "3h": 6
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2014-05-13 03:00:00"
        },
        {
            "dt": 1399960800,
            "main": {
                "temp": 291.36,
                "temp_min": 291.358,
                "temp_max": 291.36,
                "pressure": 921.65,
                "sea_level": 1016.09,
                "grnd_level": 921.65,
                "humidity": 87,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 20
            },
            "wind": {
                "speed": 0.87,
                "deg": 12.0018
            },
            "rain": {
                "3h": 0.5
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2014-05-13 06:00:00"
        },

My problem is that I do not understand the logic of making java objects. I used jsongen for generating the java objects, but it seems it does not give me the right objects.
by jsongen my java object classes are:
public class Jweather {

        private Number cod;
        private Number message;
        private City city;
        private Number cnt;
        private myList list;
                   ...
                 }

public class City{
    private Coord coord;
    private String country;
    private Number id;
    private String name;
    private Number population;
            ...
           }

public class Coord{
    private Number lat;
    private Number lon;
            ...
           }

public class myList{

    List list = new ArrayList();
    private Number clouds;
    private Number deg;
    private Number dt;
    private Number humidity;
    private Number pressure;
    private Number speed;
    private Temp temp;
    private List weather;
              ...
            }

public class Temp{
    private Number day;
    private Number eve;
    private Number max;
    private Number min;
    private Number morn;
    private Number night;
           ...
         }

public class Weather{
    private City city;
    private Number cnt;
    private String cod;
    private List list;
    private Number message;
            ...
         }

I think myList, temp, weather classes are wrong. Am I write or wrong?
I think list.java should contain dt, main, weather, clouds, wind, rain, sys and dt_txt
and I also need a main.java class including: temp, temp_min, temp_max, pressure, sea_level, grnd_level, humidity and temp_kf
and a cloud.java class including: all
and wind class including: speed, deg
and rain class including:3h
and a sys class including: pob
Any help would be highly appreciated.

A: Based on the JSON you pasted in, I agree that the generated classes don't look correct. For example, morn does not seem to appear in the JSON at all. Did you paste in the entire JSON content that was used to generate the classes?
What are you using to serialize/deserialize the JSON? Jackson is a common framework with which to do that. You would need to define mappers from the beans that store the deserialized JSON to the POJO beans.
I've not used it myself (I use Jackson and create the JSON and POJO beans myself), but based on the json gen doc, it appears that it's intended to generate the JSON-bean side of things. So you would still need to (at least potentially) define your POJO beans (unless they happened to map 100%, which seems unlikely for a variety of reasons, from different JSON property names versus POJO field names, etc.).


Q: When will the roof cave in on me? How big can I make an underground room before it collapses?
It's a simple question that I haven't been able to get a good answer to.  I assume that rooms made of stone can be larger than rooms made of clay or sand.
If I want to make a very larger room, can I place pillars in it to hold up the ceiling?  (i.e. Can I just not dig out small sections of the stone, to leave small sections of wall to act as pillars?)

A: Currently, only totally disconnected material collapses. See the cave-in article at the Dwarf Fortress Wiki for lots of details.

A: In the Current Versions of DF (.34 as of this writing), he Earth, Stone, and Soil of Dwarf Fortress does not obey the laws of physics (yet!).
This means, you never have to worry about collapse, as long as the tiles above you are anchored to something other than simple air. Material has nothing to do with it; dunes of sand can be hollowed out just the same as loamy hills or dacite mountains.
Tiles in Dwarf Fortress have two parts: the tile body and the tile floor. If you mine out the tile body, the tile floor remains. If either of these pieces is wholly disconnected, a cavein will occur. Therefor, you might be causing caveins if you're hollowing out rooms via a combination of dig and channel. Instead, start from the top, and tell your dwarves to Carve Ramps into the layer below. This will hollow out the same area, but removes the risk of dropping floors that channeling has.


Q: 14.10 NVIDIA driver makes internet very slow after install I have Ubuntu 14.10. I was using my PC long time, when suddenly I found out one problem- it was cause of Noveau driver did not support GLSL(still doesn't). It also has very bad performance. I have NVIDIA GF119 GeForce GT 610 (ver a1) graphics card. I decided to install new driver from additional drivers (I took proprietary, tested) and- ops!- after installing it internet speed slowed about 5 times. It was pining like 5 seconds and download speed was below 2 Mbps. I basicaly have 13 ms pining, 12 Mbps dowload and 5 Mbps upload. When I changed driver back, internet began to work fast. Maybe you know why is it so and how to make it "compromise"- I want there to be NVIDIA driver AND normally working internet. Please, help me!
I have wired ethernet adapter, my router is Huawei E5172!
My NIC is Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)
My kernel driver in use is  r8169(I think so it is faulty)

A: I do not believe your graphics card driver is at fault. It sounds more like your having a problem with your Huawei router configuration. Go to the HUAWEI.com web site and find your router set-up guide by model # and reconfigure your router for the fastest speed.I apoligize for the wrong information I gave you. You can also see this link for more information Slow Internet on Ubuntu 12.10


Q: NuGet Packages claiming to not be correctly installed I have a project that references
WindowsAzure.ServiceBus

However, when I rebuild the project, I get the error:

1>C:\Users\xyz\documents\visual studio
  2017\Projects\MyProject\Class.cs(1,17,1,27): error
  CS0234: The type or namespace name 'ServiceBus' does not exist in the
  namespace 'Microsoft' (are you missing an assembly reference?)
1>C:\Users\xyz\documents\visual studio
  2017\Projects\MyProject\Class.cs(12,24,12,38): error
  CS0246: The type or namespace name 'EventHubClient' could not be found
  (are you missing a using directive or an assembly reference?)

I've removed and restored the packages directory for the solution, but to no avail.  I've tried re-installing the NuGet packages:
Update-Package -reinstall

Which claimed to successfully restore the package.  I can Build the project successfully, but a Rebuild fails.  Issuing an MSBuild in the command prompt also fails.
Just to alay any theories that there's no using statement, Class.cs:
using Microsoft.ServiceBus.Messaging;

I'm at a loss to how to progress with this; can anyone offer any ideas where to go next?

A: Posting for the points :) (I love them)
Other thing that comes to my mind is to Upgrade your .NET Framework version. If nuget dll was build for higher .NET runtime, there is just a Warning message printed in Output window and Error window stays clear. But Build fails.


Q: How to sync light to the current song with Raspberry Pi? I want to make an LED attached to my Raspberry Pi blink in sync with the music playing on the Raspberry.
The problem is that I don't know how to get the current level of volume of the track which is in line audio. How can I do this?
I use Raspbian.


Q: Factorial design for ANOVA question The scenario is as follows:
I want to test a new teaching method on non-native English speaking children to see if it is more effective that the current method. I therefore plan to have the following factors in my design:
A control group (existing teaching method); and
An experimental group
Futher, I want to split these into students into those with a high standard of English vs those with low.
I will give them all a test at the start of term and then a similar one at the end of term. My null hypotheses are:
1) My new teaching method isn't significant
2) The English ability of the children prior to term isn't significant
3) There is no interaction between English ability and my new teaching method.
I'm fairly sure I need a factorial ANOVA model here, but cannot figure out whether it should be a 2x2 where I take the delta between the pre and post experiment test results as my 'values', or whether this should be a 2x2x2 design where the English ability, teaching method and time (before and after) are my factors.

A: I'll first provide an example, retaining the high vs. low distinction you made in your original question. Then, I will argue for why you should not distinguish between high and low—but use a continuous predictor instead.
I would recommend using a mixed-model (also known as multilevel or hierarchical models). You can think of your data being measured at two "levels":

*

*Level 1: Measurement occasion

*Level 2: Person

Your score is then predicted by measurement occasion (start vs. end), condition (experimental vs. control), and standard of English (high vs. low), as well as all of the two-way interactions, and the three-way interaction between the variables.
You can set up a model where occasion is a Level 1 predictor and the Level 2 predictors are condition and standard of English. The model would be:
Level 1:
$y_{ij} = \beta_{0j} + \beta_{1j}X_{ij} + e_{ij}$
Level 2:
$\beta_{0j} = \gamma_{00} + \gamma_{01}Z_j + \gamma_{02}W_j + \gamma_{03}Z_jW_j + u_{0j}$
$\beta_{1j} = \gamma_{10} + \gamma_{11}Z_j + \gamma_{12}W_j + \gamma_{13}Z_jW_j + u_{1j}$
Where $i$ is the subscript for Level 1 observations and $j$ is the subscript for Level 2 observations, $y$ is the score on the test, $X$ is the measurement occasion, $Z$ is the treatment condition, and $W$ is the standard of English.
Written in the syntax of the popular lme4 R package, this formula would be:
score ~ time * condition * standard_of_english + (1 + condition * standard_of_english | id)

Where id would be an identification variable for each of your participants.
So why use this instead of an ANOVA? Two reasons:
First, the 2x2 fully between-subjects analysis relies on difference scores. Using difference scores is something hotly contested. A classic reference on this is Edwards, J. E. (2001). Ten Difference Score Myths. Organizational Research Methods.
Simply avoid all that hassle and problems with difference scores by not using them! So then that leaves you with being able to use the 2x2x2 mixed-analysis ANOVA, where the within-subjects factor is measurement occasion (before vs. after). The problem here is that you have to dichotomize something that is fundamentally continuous. You are losing a lot of information in doing this, and splitting a continuous variable into two groups is pretty roundly panned these days. A classic reference for this is MacCallum et al. (2002). On the Practice of Dichotomization of Quantitative Variables. Psycholgical Methods..
What is great about using the mixed-model approach I described above is that $W$ (or standard_of_english) in the model (or lme4 formula) above can be continuous—you do not have to cut it into two groups and lose lots of information.
So, my suggestion would be to use the mixed-model, described above.


Q: Create bootable ISO from Live USB I have created a Ubuntu 11.04 Live USB with Unetbootin. I was wondering if it was possible to create a bootable iso from the usb stick.

A: You should reconsider the overall question and do as Thiago M suggests.  A Live CD needs to be configured to boot and pass off the boot sequence in a manner that differs from USB thumb drives.  There is a similar question about migrating between different thumb drives on https://unix.stackexchange.com/questions/14435/cloning-a-bootable-usb-stick-to-a-different-size-stick is currently being discussed.  That technical challenge is much simpler than moving to a CD and it is quite complex so I would punt.

A: You can download the image from the Ubuntu website and burn it to a CD, it will be a bootable Live install.


Q: Wrapping long text into a container, causes overflow Flutter I'm creating a notification center for my application, and it contains a bit of long strings for the title and the body, and it always causes overflow, I've tried using Expanded widgets, and these following stack over flow questions: Question 1, Question 2 But I cannot apply it to my code, here is what it looks like right now:

I get the text from my firebase cloud firestore, and I'm outputting the texts using a listview.
The title text is this: "Allen Indefenzo has rescinded consent for you to access his/her data"
The body text is this : "He/she has removed all your access and you will no longer be able to view / change his data, to have access again ask for the user to give you his/her special code again."
Here is my code:
Container(
        color: Colors.white,
        child: StreamBuilder(
          stream: db
              .collection('users')
              .document(userData.userID)
              .collection('notifications')
              .snapshots(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            if (snapshot.data.documents.length != 0) {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Row(
                      children: <Widget>[
                        Container(
                          height: 150,
                          width: 100,
                          child: Image(
                            image: NetworkImage(
                                snapshot.data.documents[index]['dpURL']), fit: BoxFit.contain,
                          ),
                        ),
                        Column(
                          children: <Widget>[
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['title']),
                            ),
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['body']),
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
                },
              );
            }
          },
        ),
      ),

Any help is appreciated and if you can explain it would be amazing! Thank you so much!

A: try to wrap your Column inside Expanded,
 Container(
              child: Row(
                children: <Widget>[
                  Container(
                    height: 150,
                    width: 100,
                    child: Image(
                      image: NetworkImage(
                          'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQLBtBU3nUOK7osT41ZsQhP4VBV7fd9euqXvXVKQH0Q7bl4txeD'),
                      fit: BoxFit.contain,
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: <Widget>[
                        Text(
                            'Reallly looooooooooooooooooooooooooooooong textttttttttttttttttttttttttttttttttttttttttttttttt'),
                        Text(
                            'Reallly looooooooooooooooooooooooooooooong textttttttttttttttttttttttttttttttttttttttttttttttt'),
                      ],
                    ),
                  ),
                ],
              ),
            );

output:

Additionally if you want to limit lines of Text use,
  Text(
'Reallly looooooooooooooooooooooooooooooongtextttttttttttttttttttttttttttttttttttttttttttttttt',
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
                        ),

Output:

A: Just wrap your column inside expanded widget
Expanded(child:
               Column(
                          children: <Widget>[
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['title']),
                            ),
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['body']),
                            ),
                          ],
      ),
),

Expanded widget is useful when you want to fill all the remaining space when a column or row widget have 2 or more child widgets. so wrapping a child inside an expanded widget will fill up the remaining space accordingly.

A: return Container(child: Row(
                            children: <Widget>[
                              Container(
                                height: 150,
                                width: 100,
                                child: Image(
                                  image: NetworkImage(snapshot.data.documents[index]['dpURL']), fit: BoxFit.contain,
                                ),
                              ),
                             new Expanded(
                                child: Column(
                                  children: <Widget>[
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: TitleText(
                                        text:snapshot.data.documents[index]['title'] ,
                                        maxLine: 5,
                                      ),
                                    ),
                                    Container(
                                      height: 50,
                                      width: MediaQuery.of(context).size.width * 0.8,
                                      child: TitleText(
                                          text:snapshot.data.documents[index]['body']),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );


Q: How to insert an image in the linear layout? I just wanted to insert an image in linear layout similar to this
Can anyone help me with this???

A: You are probably looking for ImageButton since your picture shows something similar to that.
Alternatively, take a look at ImageView

A: set layout's orientation to horizontal, then add 4 images in xml, one after another, add ids like image1, image2 etc, then call them in your onCreate like ImageView image
ImageView image1 = (ImageView) findViewById(R.id.image1)

and so on, then you can either set "src" attribute in yoru xml or say image1.setImageBitmap or any other method available in ImageView class to set the image you want from your res/drawable/

A: you can use ImageButton in horizontal LinearLayout
make background of the ImageButton @null
then put the margins between them


Q: How could I implement a trap to indicate ASP.Net Session expiry I need to create a user login/logout/Session expiry tracking page(ASP.Net)..
It is obvious that I can invoke my tracking page when user logs in and logs out..
How do I detect session expirey ?

A: Your most obvious way in a stateful app is to assume that any hit on a non-login page without being logged in implies that the session has expired.

A: use the Session_End event in Global.asax. Keep in mind this event does not fires when sessions are persisted outside of the process (in SQL for example)


Q: CSS3 Animation not working on chrome or safari I'm trying to get a simple css3 animation to work. Till now it works fine in Firefox, but not in Chrome or Safari.
I added @-webkit-keyframes so it should work on all browsers (maybe not in IE).
This is my css:
.myFace {
        display: block;
        width: 266px;
        height: 266px;
        background: url(http://cl.ly/image/443k292m2C24/face2x.png) no-repeat 0 0;}
.myFace:hover {
    animation: threesixty 1s;
    -webkit-animation: threesixty 1s; /* Safari and Chrome */
}
@keyframes threesixty {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
@-webkit-keyframes threesixty {
    0% {transform: rotate(0deg);}
    100% {transform: rotate(360deg);}
}

This is what i'm trying to do -
http://jsfiddle.net/dansku/JTcxH/4/

A: I believe that's because inside your keyframes, you're using transform:, which will work for IE10, Firefox and Opera, but haven't also got the webkit equivalent - specifically -webkit-transform which will work for Chrome and Safari.
@keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-rotate(0deg);
    -ms-transform:rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-rotate(360deg);
    -ms-transform:rotate(360deg);
  }
}
@-webkit-keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-rotate(0deg);
    -ms-rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-rotate(360deg);
    -ms-rotate(360deg);
  }
}

You should also include the -ms- prefix as I've shown above, for versions of IE before 10.

A: From the MDN article on transforms:
Webkit browsers (Chrome, Safari) still needs the -webkit prefix for transforms, while Firefox, as of version 16, does not.
This code should do the job for you:
@keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg); }
  }
@-webkit-keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
  }
}

For Opera and IE9+ support, use -o and -ms prefixes respectively. (IE10 does not require the prefix)


Q: About the integral $\int _{\ln 2} ^{\ln 3} \frac { e ^x} {e ^{4x}-1} \,d x$ How do I compute $$\int \limits _{\ln 2} ^{\ln 3} \frac {e ^x} {e ^{4x}-1} \,  d x $$
? Thank you so much for your answer.

A: Put $e^x=y$ , the limits change to 2 & 3.
Now ,  $\displaystyle I=\int_{2}^{3} \dfrac{dy}{y^4-1} = \frac{1}{2} (\int_{2}^{3} \frac{dy}{y^2-1} - \frac{dy}{y^2+1}) = \frac{1}{4}( \int_{2}^{3} \frac{dy}{y-1}-\frac{dy}{y+1}) - \frac{1}{2} [\tan^{-1}(y)]_{2}^{3} = \frac{1}{4}(\ln2 -\ln1 - \ln4 + \ln3) - \frac{1}{2}(\tan^{-1}(3)-\tan^{-1}(2)) $
So , I hope it demonstrates the process clearly.

A: $$I=\int_{\log 2}^{\log 3}\frac{e^{x}}{e^{4x}-1}\,dx = \int_{2}^{3}\frac{du}{u^4-1}\,du=\int_{2}^{3}\frac{1}{2}\left(\frac{1}{u^2-1}-\frac{1}{u^2+1}\right)\,du $$
leads to:
$$ I = \int_{2}^{3}\frac{1}{2}\left(\frac{1/2}{u-1}-\frac{1/2}{u+1}-\frac{1}{u^2+1}\right)\,du = \frac{1}{4}\log\left(\frac{3}{2}\right)-\frac{\arctan 3-\arctan 2}{2}$$
or to:
$$ I = \frac{1}{4}\left(\log\frac{3}{2}-\arctan\frac{7}{24}\right).$$

A: $$\int_{\ln(2)}^{\ln(3)}\frac{e^x}{e^{4x}-1}\space\text{d}x=$$

Substitute $u=e^x$ and $\text{d}u=e^x\space\text{d}x$.
This gives a new lower bound $u=e^{\ln(2)}=2$ and upper bound $u=e^{\ln(3)}=3$:

$$\int_{2}^{3}\frac{1}{u^4-1}\space\text{d}u=$$

Use partial fractions:

$$\int_{2}^{3}\left[\frac{1}{4(u-1)}-\frac{1}{4(u+1)}-\frac{1}{2(u^2+1)}\right]\space\text{d}u=$$
$$\frac{1}{4}\int_{2}^{3}\frac{1}{u-1}\space\text{d}u-\frac{1}{4}\int_{2}^{3}\frac{1}{u+1}\space\text{d}u-\frac{1}{2}\int_{2}^{3}\frac{1}{u^2+1}\space\text{d}u=$$
$$\frac{1}{4}\int_{2}^{3}\frac{1}{u-1}\space\text{d}u-\frac{1}{4}\int_{2}^{3}\frac{1}{u+1}\space\text{d}u-\frac{1}{2}\left[\arctan(u)\right]_2^3=$$

For the integral $\int\frac{1}{u+1}\space\text{d}u$:
Substitute $s=u+1$ and $\text{d}s=\text{d}u$.
This gives a new lower bound $s=2+1=3$ and upper bound $s=3+1=4$:

$$\frac{1}{4}\int_{2}^{3}\frac{1}{u-1}\space\text{d}u-\frac{1}{4}\int_{3}^{4}\frac{1}{s}\space\text{d}s-\frac{1}{2}\left[\arctan(u)\right]_2^3=$$
$$\frac{1}{4}\int_{2}^{3}\frac{1}{u-1}\space\text{d}u-\frac{1}{4}\left[\ln|s|\right]_3^4-\frac{1}{2}\left[\arctan(u)\right]_2^3=$$

Substitute $p=u-1$ and $\text{d}p=\text{d}u$.
This gives a new lower bound $p=2-1=1$ and upper bound $p=3-1=2$:

$$\frac{1}{4}\int_{1}^{2}\frac{1}{p}\space\text{d}p-\frac{1}{4}\left[\ln|s|\right]_3^4-\frac{1}{2}\left[\arctan(u)\right]_2^3=$$
$$\frac{1}{4}\left[\ln|p|\right]_1^2-\frac{1}{4}\left[\ln|s|\right]_3^4-\frac{1}{2}\left[\arctan(u)\right]_2^3=$$
$$\frac{1}{4}\left(\ln|2|-\ln|1|\right)-\frac{1}{4}\left(\ln|4|-\ln|3|\right)-\frac{1}{2}\left(\arctan(3)-\arctan(2)\right)=$$
$$\frac{1}{4}\left(\ln|2|-0\right)-\frac{1}{4}\left(\ln|4|-\ln|3|\right)-\frac{1}{2}\left(\arctan(3)-\arctan(2)\right)=$$
$$\frac{\ln(2)-\ln(4)+\ln(3)}{4}-\frac{\arctan(3)-\arctan(2)}{2}\approx0.03041774972495909$$


Q: Website images overlapping(Shopify) I am using shopify and added a section using my own html into it. I added the picture of the lipstick, the face and the one under those that is being overlapped by one of the products from the 'featured products' section that comes built into the theme.  I was wondering how I would be able to fix this? Do I need to go in and fix something with liquid?
I have solved this issue by using a table in html instead; Ive provided my solution for future readers.
HTML

A: Add padding to the photographs. Padding (e.g. of 10px) will add a 10px white space on all sides (unless you specify padding-top or padding-bottom etc.. which you can do if you prefer. ) You could also add a margin to the container. A negative margin-top will  shift the appearance of the position of the container upwards, likewise it can be applied to the photographs as well. (Positive or negative)
Hope this helps
Rachel


Q: residually finite-by-$\mathbb{Z}$ groups are residually finite I believe I read somewhere that residually finite-by-$\mathbb{Z}$ groups are residually finite. That is, if $N$ is residually finite with $G/N\cong \mathbb{Z}$ then $G$ is residually finite.
However, I cannot remember where I read this, and nor can I find another place which says it. I was therefore wondering if someone could confirm whether this is true or not, and if it is give either a proof or a reference for this result? (If not, a counter-example would not go amiss!)
Note that I definitely know it is true if $N$ is f.g. free (this can be found in a paper of G. Baumslag, "Finitely generated cyclic extensions of free groups are residually finite" (Bull. Amer. Math. Soc., 5, 87-94, 1971)).

A: This is not true if $N$ is not assumed f.g. E.g. the wreath product of a nonabelian finite group $H$ by the integers is not residually finite (Gruenberg 1957, can be checked as a exercise). Here $N$ is an infinite direct sum of copies of $H$ (shifted by the action of the integers) and is residually finite.

A: This is not true. The most prominent examples of non-residually finite central extensions of residually finite groups (by $\mathbb Z$) are certain lattices in non-linear Lie groups.
See for example
M. S. Raghunathan. Torsion in cocompact lattices in coverings of Spin(2, n). Math. Annalen 266, 403–419, 1984.
or
P. Deligne. Extensions centrales non residuellement finies de groupes arithmetiques. CR Acad. Sci. Paris, serie A-B, 287, 203–208, 1978.

A: The modified question has a positive answer if $N$ is finitely generated.
Consider an extension $1 \to N \to G \to \mathbb Z \to 1$ and take a lift $u \in G$ of the generator of $\mathbb Z$. If $N$ is finitely generated and $H' \subset N$ is a subgroup of finite index, then the intersection of all subgroups of index $[N:H']$ (call it $H$) is invariant under conjugation by $u$. Hence, for all $m \in \mathbb Z$, the subgroup $Hu^{m \mathbb Z}$ is a finite index normal subgroup of $G$.
Hence, if $N$ is finitely generated and residually finite, then $G$ is residually finite as well.

A: I think what Yves meant in his comment to Andreas' answer is the result of Mal'cev [A. I. Mal'cev, On homomorphisms onto finite groups, Ivanov. Gos. Ped. Inst. Ucen. Zap., 18 (1958), pp. 49-60, in Russian] stating that any split extension of a finitely generated residually finite group by a residually finite group is residually finite. This is indeed an easy exercise. In particular, this implies that every (f.g. residually finite) - by - Z group is residually finite as every extension by a free group (e.g., by Z) splits.
If either of the conditions "finitely generated" or "split" is relaxed, the result does not hold. The counterexample with infinitely generated kernel is already provided by Yves. For non-split extensions there are even examples of the form $$1\to \mathbb Z/2\mathbb Z \to G\to Q\to 1,$$ where $Q$ is (finitely generated) residually finite while $G$ is not. In particular, being residually finite is not a quasi-isometry invariant.
Such examples can be found among solvable (moreover, center-by-metabelian) groups or even among groups of intermediate growth (see [A. Erschler, Not residually finite groups of intermediate growth, commensurability and non-geometricity, Journal of Algebra, 272 (2004), 154-172].


Q: Response to preflight request doesn't pass access control check with Angular 2 I am trying to connect to an API using Angular 2. I am unable to connect to it as it is giving me a OPTIONS error as well as:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
I have the Google Chrome plugin as well as the headers. Here is the code
map.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MapService {

    private headers = new Headers();
    constructor(private http: Http) { }

    getMarkers() {
        this.headers.append("Access-Control-Allow-Origin", '*');
        this.headers.append("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
        this.headers.append("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token');
        this.headers.append("Authorization", 'Bearer ' + 'mysecretcode');
        return this.http.get('https://api.yelp.com/v3/businesses/search?location=suo&limit=50', { headers: this.headers})
            .map(response => response.json());
    }

}

map.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import { Marker } from '../../models/map/marker';
import { MapService } from '../../services/map/map.service';
import {Observable} from 'rxjs/Rx';
import {Http, Response, Headers } from '@angular/http';

@Component({
    moduleId: module.id,
    selector: 'map-view',
    templateUrl: 'map.component.html',
    styleUrls: ['map.component.css'],
})

export class MapComponent {

    marker: Object;

    constructor(mapService: MapService) {
        mapService.getMarkers()
            .subscribe(
                marker => this.marker = marker,
                error => console.error('Error: ' + error),
                () => console.log('Completed!')
            );
    }

I understand that this is most likely a problem with CORS. Is this something i can do to fix or is this on yelps end?
EDIT:
Here is one of the errors:
Error: Response with status: 0  for URL: null(anonymous function) @ map.component.ts:24SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.error @ Subscriber.ts:202Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109onError @ http.umd.js:1186ZoneDelegate.invokeTask @ zone.js:262onInvokeTask @ core.umd.js:7768ZoneDelegate.invokeTask @ zone.js:261Zone.runTask @ zone.js:151ZoneTask.invoke @ zone.js:332

A: The reason for pre-flight failing is a standard problem with CORS:
How does Access-Control-Allow-Origin header work?
It is fixed by having server to set correct Access-Control-Allow-Origin.
However, the root cause of your problem could be in misconfiguration of your server or your client, since 500 is the server internal error. So it might not be accessing intended server code, but some generic handler in apache or whatever is hosting the service. Most of the generic error handlers dont provide CORS support as default.
Note, if you are using REST API, 500 is not a code you should see in a successful API use scenario. It means that the server is not capable of handling the request properly.
Maybe this link would have relevant information:
EXCEPTION: Response with status: 0 for URL: null in angular2


Q: How to scrape latitude longitude from java script I am fairly new to BeautifulSoup4 and am having trouble extracting latitude and longitude values out of javascript. The file is quite long and I have to prepare data frame from all the latitude longitudes
The Java script file will have strings like these:
var marker_9795626cfd584471ab4406d756a00baf = L.marker([19.041691972000024, 72.85052482000003],{}).addTo(feature_group_ad623471194f451d9f1cf7fc718747c5);

The marker id, here, would be - 9795626cfd584471ab4406d756a00baf
The latitude would be - 19.041691972000024
And the longitude would be - 72.85052482000003
How to extract marker id, latitude and longitude out of the strings using BeautifulSoup.

A: if all you need is to isolate those 2 numbers from that string try this:
def parse(text):
   return [float(i) for i in text.split('[', 1)[1].split(']', 1)[0].split(', ')]

long_lat = parse(your_string_var)

EDIT:
oh and to get the id something like this should do:
def parse2(text):
   return text.split('_', 1)[1].split(' ', 1)[0]

id = parse2(your_string_var)

A: This is Javasascript script, so BeautifulSoup won't execute/parse it. You can use re module to get the information.
For example:
import re
txt = '''var marker_9795626cfd584471ab4406d756a00baf = L.marker([19.041691972000024, 72.85052482000003],{}).addTo(feature_group_ad623471194f451d9f1cf7fc718747c5);'''

marker_id, lat, lon = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', txt).groups()

print(marker_id)
print(lat)
print(lon)

Prints:
9795626cfd584471ab4406d756a00baf
19.041691972000024
72.85052482000003

EDIT: To parse the variables from file, you can use this script:
import re

with open('<YOUR FILE>', 'r') as f_in:
    for line in f_in:
        m = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', line)
        if m:
            marker_id, lat, lon = m.groups()
            print(marker_id, lat, lon)

EDIT2: New version:
import re

with open('<YOUR FILE>', 'r') as f_in:
    data = f_in.read()

for marker_id, lat, lon in re.findall(r'marker_([a-fA-F\d]+).*?\[(.*?),\s*(.*?)\]', data):
    print(marker_id, lat, lon)


Q: Sphinx MVA sql_attr_multi results always on first field in FACET Query I am trying to achieve a filter in Sphinx so that I can filter out the results from two MVA attributes (what I need is a double condition, but since MVA is only 2 fields..) from the same joined table, but whatever I do, It seems that I keep getting the same results since there is always a match on the first field in the multi attribute?
Maybe there's another solutions but I can't seem to find out how to get my desired result, I got to simplify 4 tables: PRODUCT, CATEGORY, PRICE and POSITION.
Data set-up
Below a sample of the data structure:
PRODUCT
+------+-------------+-----------------+---------------+
|  ID  | CATEGORY_ID | MANUFACTURER_ID |     TITLE     |
+------+-------------+-----------------+---------------+
| 1000 |        1000 |            1000 | Apple iPhone  |
| 1001 |        1000 |            1000 | Apple iPad    |
| 1002 |        1000 |            1000 | Apple iPod    |
| 1003 |        1001 |            1001 | Do not show   |
+------+-------------+-----------------+---------------+

CATEGORY
+------+-------+
|  ID  | TITLE |
+------+-------+
| 1000 | Apple |
| 1001 | Other |
+------+-------+

PRICE
+------+--------+---------+
|  ID  | USERID |  PRICE  |
+------+--------+---------+
| 1000 |   1000 |  359.00 |
| 1001 |   1001 | 1058.30 |
| 1002 |   1002 | 1078.00 |
| 1003 |   1003 | 1160.45 |
| 1004 |   1004 | 1180.00 |
| 1005 |   1000 | 1190.00 |
| 1006 |   1000 |  228.76 |
+------+--------+---------+

POSITION
+------+------------+--------+------+
|  ID  | PRODUCT_ID | USERID | RANK |
+------+------------+--------+------+
| 1000 |       1000 |   1000 |    1 |
| 1001 |       1001 |   1001 |    1 |
| 1002 |       1001 |   1002 |    2 |
| 1003 |       1001 |   1003 |    3 |
| 1004 |       1001 |   1004 |    4 |
| 1005 |       1001 |   1000 |    5 |
| 1006 |       1002 |   1000 |    1 |
+------+------------+--------+------+

Sphinx Set-up:
source product
{
        type                            = mysql

        sql_host                        = localhost
        sql_user                        = ...
        sql_pass                        = ...
        sql_db                          = ...

        sql_query_pre                   = SET NAMES utf8
        sql_query                       = SELECT P.ID AS ID, C.ID AS SEARCH_CAT_ID, P.CATEGORY_ID, P.MANUFACTURER_ID, P.TITLE AS TITLE_SORT FROM CATEGORY C, PRODUCT P WHERE P.CATEGORY_ID=C.ID
        sql_attr_uint                   = CATEGORY_ID
        sql_attr_uint                   = MANUFACTURER_ID
        sql_attr_string                 = TITLE_SORT
        sql_attr_multi                  = uint POS_RANK from query; SELECT PRODUCT_ID, RANK FROM POSITION
        sql_attr_multi                  = uint POS_USERID from query; SELECT PRODUCT_ID, USERID FROM POSITION
}
index product
{
        source                   = product
        path                     = ...
        docinfo                  = extern
        min_word_len             = 1
}

MySQL Dump:
CREATE TABLE IF NOT EXISTS `CATEGORY` (
  `ID` int(11) NOT NULL,
  `TITLE` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `CATEGORY` (`ID`, `TITLE`) VALUES
(1000, 'Apple'),
(1001, 'Other');

CREATE TABLE IF NOT EXISTS `POSITION` (
  `ID` int(11) NOT NULL,
  `PRODUCT_ID` int(11) NOT NULL,
  `USERID` int(11) NOT NULL,
  `RANK` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `USERID` (`USERID`),
  KEY `PRODUCT_ID` (`PRODUCT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `POSITION` (`ID`, `PRODUCT_ID`, `USERID`, `RANK`) VALUES
(1000, 1000, 1000, 1),
(1001, 1001, 1001, 1),
(1002, 1001, 1002, 2),
(1003, 1001, 1003, 3),
(1004, 1001, 1004, 4),
(1005, 1001, 1000, 5),
(1006, 1002, 1000, 1);

CREATE TABLE IF NOT EXISTS `PRICE` (
  `ID` int(11) NOT NULL,
  `USERID` int(11) NOT NULL,
  `PRICE` decimal(9,2) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `USERID` (`USERID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `PRICE` (`ID`, `USERID`, `PRICE`) VALUES
(1000, 1000, '359.00'),
(1001, 1001, '1058.30'),
(1002, 1002, '1078.00'),
(1003, 1003, '1160.45'),
(1004, 1004, '1180.00'),
(1005, 1000, '1190.00'),
(1006, 1000, '228.76');

CREATE TABLE IF NOT EXISTS `PRODUCT` (
  `ID` int(11) NOT NULL,
  `CATEGORY_ID` int(11) NOT NULL,
  `MANUFACTURER_ID` int(11) NOT NULL,
  `TITLE` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `CATEGORY_ID` (`CATEGORY_ID`),
  KEY `MANUFACTURER_ID` (`MANUFACTURER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `PRODUCT` (`ID`, `CATEGORY_ID`, `MANUFACTURER_ID`, `TITLE`) VALUES
(1000, 1000, 1000, 'Apple iPhone'),
(1001, 1000, 1000, 'Apple iPad'),
(1002, 1000, 1000, 'Apple iPod'),
(1003, 1001, 1001, 'Do not show');

ALTER TABLE `POSITION`
  ADD CONSTRAINT `POSITION_ibfk_1` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `POSITION` (`ID`) ON DELETE CASCADE;

ALTER TABLE `PRODUCT`
  ADD CONSTRAINT `PRODUCT_ibfk_1` FOREIGN KEY (`CATEGORY_ID`) REFERENCES `CATEGORY` (`ID`) ON DELETE CASCADE;

Test 1
SphinxQL Query for filter USERID:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID (first set seems OK this time, second returns everything):
+------+
|  id  |
+------+
| 1000 |
| 1001 |
| 1002 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        3 |
+----------+----------+

What I expected:

*

*Product ID (1000,1001,1002)

*Position Rank (1 with count 3, 5 with count 1)

Test 2
SphinxQL Query for filter USERID 1000 and RANK 5:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) AND POS_RANK IN (5) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID and RANK (first set seems OK this time, second returns everything):
+------+
|  id  |
+------+
| 1001 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        1 |
+----------+----------+

What I expected:

*

*Product ID (1001)

*Position Rank (5 with count 1)

Test 3
SphinxQL Query for filter USERID 1000 and RANK 4:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) AND POS_RANK IN (4) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID and RANK (first stil returns product, second returns everything):
+------+
|  id  |
+------+
| 1001 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        1 |
+----------+----------+

What I expected:

*

*Product ID (empty set)

*Position Rank (empty set)

I hope you guys understand what I am trying to achieve and can help me out?


Q: Mixing objects and rows, carrying muliples objects. How going from row datasets to datasets of objects (a Dataset where + mean: "join")? The following question is rather long. It depicts this:

*

*I have a row dataset made of primitive types a1, a2...a10, b1, b2...b8, c1..c4, d1.

*They are hiding objects A, B, C accompanied sometimes with others primitives attributes not in a class: d1, for example.

*I could return instead of a Dataset<Row> a Dataset<E> where E would be a class having for members the A, B, C objects and the attribute d1.

*But I want to avoid this, if I can, yet, and see how much I can approach a solution where I would return a dataset of joined objects [and attributes] : Dataset<A+B+C+d1>
(where the + sign means that objects are linked together by a join).
If it's possible, is it really manageable?

My code uses mostly Dataset<Row>.
For example, I have a method that builds a (French) city description:
/**
* Obtenir un Dataset des communes.
* @param session Session Spark.
* @param anneeCOG Année du Code Officiel Géographique de référence.
* @param verifications Vérifications demandées.
* @return Dataset des communes.
* @throws TechniqueException si un incident survient.
*/
public Dataset<Row> rowCommunes(SparkSession session, int anneeCOG, Verification... verifications) throws TechniqueException {
  String nomStore = "communes_par_codeCommune";

  Dataset<Row> communes = loadFromStore(session, "{0}_{1,number,#0}", nomStore, anneeCOG, verifications);

  if (communes != null) {
     return communes;
  }

  LOGGER.info("Constitution du dataset des communes depuis pour le Code Officiel Géographique (COG) de l'année {}...", anneeCOG);

  Dataset<Row> c = loadAndRenameCommmunesCSV(session, anneeCOG, false, verifications);
  Dataset<Row> s = this.datasetSirenCommunaux.rowSirenCommunes(session, anneeCOG, TriSirenCommunaux.CODE_COMMUNE);

  Column condition1 = c.col("codeCommune").equalTo(s.col("codeCommune"));
  Column condition2 = c.col("codeCommuneParente").equalTo(s.col("codeCommune"));

  verifications("jonction communes et siren par codeCommune", c, null, s, condition1, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  Dataset<Row> join1 = c.join(s, condition1)
     .drop(s.col("codeCommune"))
     .drop(s.col("nomCommune"))
     .drop(s.col("codeRegion"))
     .drop(s.col("codeDepartement"));

  verifications("jonction communes et siren par codeCommune, join1", c, null, null, null, verifications);

  verifications("jonction communes et siren par codeCommuneParente", c, null, s, condition2, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  Dataset<Row> join2 = c.join(s, condition2)
     .drop(s.col("codeCommune"))
     .drop(s.col("nomCommune"))
     .drop(s.col("codeRegion"))
     .drop(s.col("codeDepartement"));

  verifications("jonction communes et siren par codeCommuneParente, join2", c, null, null, null, verifications);

  communes = join1.union(join2);

  // La strate communale doit concorder avec celle des comptes individuels des communes.
  communes = communes.withColumn("strateCommune",
     when(s.col("populationTotale").between(0, 249), lit(1))       // communes de moins de 250 hab
     .when(s.col("populationTotale").between(250, 499), lit(2))     // communes de 250 à 500 hab
     .when(s.col("populationTotale").between(500, 1999), lit(3))    // communes de 500 à 2 000 hab
     .when(s.col("populationTotale").between(2000, 3499), lit(4))   // communes de 2 000 à 3 500 hab
     .when(s.col("populationTotale").between(3500, 4999), lit(5))   // communes de 3 500 à 5 000 hab
     .when(s.col("populationTotale").between(5000, 9999), lit(6))   // communes de 5 000 à 10 000 hab
     .when(s.col("populationTotale").between(10000, 19999), lit(7)) // communes de 10 000 à 20 000 hab
     .when(s.col("populationTotale").between(20000, 49999), lit(8)) // communes de 20 000 à 50 000 hab
     .when(s.col("populationTotale").between(50000, 99999), lit(9)) // communes de 50 000 à 100 000 hab
     .otherwise(lit(10)));                                          // communes de plus de 100 000 hab

  // Obtenir les contours des communes.
  // "(requête SQL) contours" est la forme de substitution pour Spark. cf https://stackoverflow.com/questions/38376307/create-spark-dataframe-from-sql-query
  String format = "(select insee as codecommuneosm, nom as nomcommuneosm, surf_ha as surface2, st_x(st_centroid(geom)) as longitude, st_y(st_centroid(geom)) as latitude from communes_{0,number,#0}) contours";
  String sql = MessageFormat.format(format, anneeCOG);

  Dataset<Row> contours = sql(session, sql).load();
  contours = contours.withColumn("surface", col("surface2").cast(DoubleType)).drop(col("surface2"))
     .orderBy("codecommuneosm");

  Column conditionJoinContours = col("codeCommune").equalTo(col("codecommuneosm"));

  verifications("jonction communes et contours communaux OSM (centroïde, surface)", communes, null, contours, conditionJoinContours, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  communes = communes.join(contours, conditionJoinContours, "left_outer")
     .drop(col("codecommuneosm")).drop(col("nomcommuneosm"));
  verifications("jonction communes et contours communaux OSM (centroïde, surface)", communes, null, null, null, verifications);

  // Associer à chaque commune son code intercommunalité, si elle en a un (les communes-communautés peuvent ne pas en avoir).
  Dataset<Row> perimetres = this.datasetPerimetres.rowPerimetres(session, anneeCOG, EPCIPerimetreDataset.TriPerimetresEPCI.CODE_COMMUNE_MEMBRE).selectExpr("sirenCommuneMembre", "sirenGroupement as codeEPCI", "nomGroupement as nomEPCI");
  Column conditionJoinPerimetres = communes.col("sirenCommune").equalTo(perimetres.col("sirenCommuneMembre"));

  verifications("jonction communes et périmètres", communes, null, perimetres, conditionJoinPerimetres, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  communes = communes.join(perimetres, conditionJoinPerimetres, "left");

  // Y associer les départements.
  communes = this.datasetDepartements.withDepartement(session, "codeDepartementRetabli", communes, "codeDepartement", null, true, anneeCOG)
     .drop("codeRegionDepartement")
     .drop("codeDepartementRetabli");

  communes = communes.repartition(col("codeDepartement"))
     .sortWithinPartitions(col("codeCommune"))
     .persist(); // Important : améliore les performances.

  saveToStore(communes, new String[] {"codeDepartement"}, "{0}_{1,number,#0}", nomStore, anneeCOG);
  LOGGER.info("Le dataset des communes du Code Officiel Géographique de l'année {} est prêt et stocké.", anneeCOG);

  return communes;
}

Sometimes, it's useful if I convert these rows to a Commune object, because business objects, at least on server side, can have methods that bring them some kind of intelligence (limited to looking at themselves or to the objects of their package).
For example, the Commune object has this method to help detecting it has the same name than another one when an article can be found in its name.
/**
* Déterminer si notre commune a le même nom que celle en paramètre.
* @param nomCandidat Nom de commune : il peut contenir une charnière.
* @return true si c'est le cas.
*/
public boolean hasMemeNom(String nomCandidat) {
  // Si le nom soumis vaut null, répondre non.
  if (nomCandidat == null) {
     return false;
  }

  // Faire une comparaison directe de nom de commune tout d'abord, car l'emploi du collator est très coûteux.
  if (nomCandidat.equalsIgnoreCase(this.nomCommune)) {
     return true;
  }

  // Puis, rechercher avec les différentes charnières.
  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.AUCUN))) {
     return true;
  }

  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.A))) {
     return true;
  }

  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.POUR))) {
     return true;
  }

  // En cas d'échec, reprendre ces tests, mais avec le collator, plus lent, mais qui passera outre les caractères accentués.
  if (collator.equals(nomCandidat, this.nomCommune)) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.AUCUN))) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.A))) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.POUR))) {
     return true;
  }

  return false;
}

To do that conversion from a Dataset<Row> to a Dataset<Commune>, I wrote this function, which works, but troubles me because it looks clumsy to me:
/**
* Obtenir un Dataset des communes (comme objets communes, incluant les données siren communaux).
* @param session Session Spark.
* @param anneeCOG Année du Code Officiel Géographique de référence.
* @return Dataset des communes.
* @throws TechniqueException si un incident survient.
*/
public Dataset<Commune> obtenirCommunes(SparkSession session, int anneeCOG) throws TechniqueException {
  Dataset<Row> communes = rowCommunes(session, anneeCOG);

  return communes
     .select(communes.col("typeCommune"), communes.col("codeCommune"), communes.col("codeRegion"), communes.col("codeDepartement"),
         communes.col("arrondissement"), communes.col("typeNomEtCharniere"), communes.col("nomMajuscules"), communes.col("nomCommune"),
         communes.col("codeCanton"), communes.col("codeCommuneParente"), communes.col("sirenCommune"), communes.col("populationTotale").alias("population"),
         communes.col("strateCommune"), communes.col("codeEPCI"), communes.col("surface"), communes.col("longitude"), communes.col("latitude"),
         communes.col("nomDepartement"), communes.col("nomEPCI"))
     .as(Encoders.bean(Commune.class))
     .cache();
}

However, my main problem is:
The Commune object (or rows) is almost never used (or returned) alone in most datasets, after that.
Often a Commune will come with some employment data associated, or with financial information linked. Or sometimes, a calculation method can associate only one or two raw (primitive) data values to a city, if they make sense.
So, until today, what happened?

*

*I was starting with a Dataset<Row> of let's say 20 columns.

*if I was doing some joins, calculations, enrichments, etc.: that dataset reached 40 or 50 columns sometimes,

*

*Let's say that a record was: a1, a2...a10, b1, b2...b8, c1..c4, d1 of rows columns having primitive types.

*then I was extracting from that record, through the mean of Encoders.bean(...) method, the various business objects it was hiding, depending on my needs.

*

*From a record, I could extract A from a1, a2...a10 or C from c1...c4.

It worked (and it's working) but I'm not really proud of this manner of doing things.
I would enjoy more starting with a plain Dataset<Commune> dataset, hiding completely the row phase to the users of my API, then being able to return to them, depending of their needs:

*

*a dataset containing Commune and Employment business object together, or Commune and Accounting.

*a dataset containing Commune, but with also few row values of columns "d1", "h1" and "k1" (if some calculation was needed to provide a specific information for that city, for some exceptional purpose/case that don't lead to changing the whole business object description, but only at this time to return an extra column value aside that city description).
It means that I will encounter cases where I would like to return a dataset showing per "record":
A, B (concrete objects coming together)
or
A, C
or even sometimes A,B,C.
Or what I'm fearing the most:
A, C, d1 (two concrete objects, plus... a primitive value).
Can you give me some ideas about how treating such problems before I start great moves?

Warning: this problem isn't a simple one. It could even not have a clear solution.

*

*Starting from row records made of primitive types a1, a2...a10, b1, b2...b8, c1..c4, d1, I am able to extract A, B, C objects from them, if I agree to do up to n additional transformations for n different objects types I can find in my attributes.

*But I wonder about approaching the most I can the situation where, given the + sign would mean: join, I had a dataset :
Dataset<A+B+C>
and even: Dataset<A+B+C+d1>, where d1 would still be a primitive type not in an object.

*If this could be achieved, it could cause troubles.
What is a Dataset<A+B+C+d1>.foreach?
A A, B or C object?
How would you manage it after that?
I'm living in a magma of attributes yet, and I wonder if I can improve my datasets to new ones using objects. Objects that are tied together to describe a single record.

This question could have the solution of creating an E object having for members A, B or C objects and the d1 primitive attribute, and returning a Dataset<E>.
But this I want to avoid the most I can, at this time. And try to find what I can do else, first.


Q: How to find and remove optgroup and option in select? I've this select structure:
<select id="select-service" class="required span4" multiple="">
        <optgroup label="Capelli">
              <option selected="false" value="14">Colore capelli</option
        </optgroup>
        <optgroup label="Nessuna categoria">
              <option selected="false" value="13">Taglio capelli</option>
              <option selected="false" value="15">Mesh</option>
        </optgroup>
</select>

Now my goal is remove all option in select, so I've made this code:
$('#select-service')
  .find('option')
  .remove()
  .end();

but the problem's that this code remove only the option not the optgroup, how I can remove in one step option and optgroup?

A: You could simply pass two, comma-separated, selectors to the find() method:
$('#select-service').find('optgroup, option').remove();

You could also just remove all children elements for the same result:
$('#select-service').children().remove();
// or:
$('#select-service > *').remove();

The most concise approach would be to just remove the element using the .empty() method:
$('#select-service').empty();

A: The simplest way
$('#select-service optgroup').remove()

Since optgroup is the parent of option it will remove it as well.

A: Like this:
$('#select-service')
.find('optgroup')
.remove();

This will not only remove your optgroup, but all contents within it, meaning your option will also be removed.


Q: Include assets in Twig Extension with Symfony2 I want to include asset with some script file in Twig extension. E.g. I want to declare twig function {{ init_project() }}, but when I writing in my twig function '<script type="text/javascript" src="{{ asset('bundles/mybundle/js/script.js') }}"></script>', it dont work, it return 404 error in debug panel of browser. So how I can do this?

A: Look at the 'asset' twig function :
You can find it in \Symfony\Bundle\TwigBundle\Extensions\AssetsExtension
public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
    {
        $url = $this->container->get('templating.helper.assets')->getUrl($path, $packageName, $version);

        if (!$absolute) {
            return $url;
        }

        return $this->ensureUrlIsAbsolute($url);
    }

Instead of calling '{{asset}}' in your extension, just call the public function getAssetUrl()


Q: Selecting the second child of an ancestor with XPath I need to fetch some text from a HTML page. I'm trying to avoid relying on tag names or classes, because they will change.
Starting from an element that contains the text "Hello", I'm looking for the text stored in the grandparent's second element.
<...>
  <...>
    <...>
      Hello
    </...>
  </..>
  <...>       <!-- UNCLE -->
    <...>
      World   <!-- I need this! -->
    </...>
  <...>
</...>

I tried fetching the element UNCLE using XPath, with: //*[text()=="Hello")]/../..[2], but it doesn't work. It seems that [] cannot be applied to ..?
How can I fetch the second child of a node's grandparent?
Are there better ways to retrieve the text I'm looking for, instead of a similar XPath query and document.evaluate?

A: Try this:
//*[*[1][*[normalize-space()='Hello']]]/*[2]/*

It will select the element that contains "World".
It's testing the value of the descendant in the first child and then selecting the descendant of the second child.


Q: Correct way for thread safe indexing operator in c++ I want to have thread safe indexing operator and I came with the following code which seems to work.
Can you see any problems with it except for bounds checking?
Is there a better way to do the same thing (with overloading indexing operator, not with get/set functions)?
class A
{
public:

A()
{
    for (auto i = 0; i < 100; ++i)
    {
        v[i] = i + 1;
    }
};

    class Proxy
    {
        int* val;
        A* parent;
    public:
        Proxy(int& a, A* p) : parent(p)
        {
            parent->z.lock();
            val = &a;
        };

        ~Proxy()
        {
            parent->z.unlock();
        }

        int operator=(int a)
        {
            *val = a;
            return a;
        };

        operator int() const
        {
            return *val;
        };
    };

int operator[](int i) const
{
    z.lock();
    int r = v[i];
    z.unlock();
    return r;
}

Proxy operator[](int i)
{
    return Proxy(v[i], this);
}

int v[100];
Z z; // some locking mechanism, not important

};

A: Since the locking mechanism isn't specified I'd assume it uses a normal mutex in which case the obvious problem is this:
A a;
a[0] = a[1];

Put differently, it is very easy to dead-lock the program. This problem is avoided with recursive mutexes.
The other obvious problem is that the code depends on copy-elision which is not guaranteed to always happen. If the copy is not elided upon return the temporary will release the lock and the copy will release it again which normally is undefined behavior. In addition, access to the member is unguarded and will potentially introduce data races. To avoid this problem you should define a move constructor and make sure that the moved from state doesn't try to release the mutex, e.g.:
A::Proxy::Proxy(Proxy&& other)
    : val(other.val)
    , parent(other.parent) {
    other.parent = 0;
}
A::Proxy::~Proxy() {
    if (parent){
        parent->unlock();
    }
}

The not so obvious issue is that it is unlikely to result in an efficient implementation.


Q: Differentiate between Table Views I have three table views inside a view controller (going to show/hide table views to display a list of options in different contexts)
Just wondering what the best way is to distinguish between different table views that are using the same delegate.
Thanks

A: Use three separate instance variables in your view controller to store the table views. Then in the delegate methods you can do something like this:
if (tableView == myFirstTableView) {
    // Do whatever you need for table view 1.
} else if (tableView == mySecondTableView) {
    // Do whatever you need for table view 2.
}


Q: Use VisualBasic DLLs in Java I have to access VBA-code of Office applications from my Java application, I found THIS that says I can access VBA-code through VisualBasic DLLs using JNI. I don't want to use a COM-bridge if not necessary, I'd rather go with a DLL-solution.
I created a VisualBasic Class Library in Visual Studio 2013 (a simple example to test if it works):
Public Class Test1
    Public Function box()
        MsgBox("boxtest!")
    End Function
End Class

I built is as a release and put this in my Java project:
public class Test1 {
    static{
        System.loadLibrary("Test1");
    }
    public native void box();
}

The function is being called by new Test1().box();.
I receive the following exception: Exception in thread "main" java.lang.UnsatisfiedLinkError: test.Test1.box()V
I also used JNA to access the DLL but after hours of trying I couldn't get it to work (I also read that it can't be used with VisualBasic DLLs).
I set the Native Library Folder of my src Folder to to folder containing the DLL.
question: Can I use VisualBasic DLLs in Java, if yes, with JNA or JNI (or both) and if so what did I do wrong, how can I access the function properly? (I guess the rest with returning and parameters is easy then...)
Thank you very much in advance and merry christmas to you all! :)

A: No idea why it cannot find your library.  From what I remember of JNI, it does not appear that you've done the JNI setup for calling a native routine, but the error message just says it cannot find it.  You might try figuring out if the library load statement worked.
A DLL is a library following certain rules and conventions; I am not aware of any great difference between a "Visual Basic DLL" and any other kind.  At some level they need to be the same, because Windows programs don't distinguish among DLLs written with different languages, afaik, and I've done VB enough to know that I haven't seen documentation that says "this can be used from VB but not from other languages" etc.
Getting JNI/JNA stuff to work is tricky and tedious.  The normal stuff that a language runtime tells you, especially a Java runtime, are not there for you in this case.  You must painstakingly go through every line of whatever documentation you have, every parameter you are passing, every use of value versus reference, etc.
I once got things to work with the GitHub library here.
Good luck.

A: I have not found an answer how to call VB DLLs directly from Java but after some days of research I found out that you are able to call VB DLLs with the help of a C++ wrapper.
It may be possible to call VB DLL methods with JNI but there is no documentation on how to do it.
You find a lot about how to create C++ libraries that are able to communicate with JNI in the JNI specifications from Oracle.
In this special case (control Office Applications with Java) I suggest to write the code to access the Office Application in C++ and create a DLL.
The basic approach on creating a C++ DLL that may interact with JNI is:

*

*Think of names for the methods you want to create in C++ and a .dll-name [NAME].dll

*Create a Java class for the DLL, loading the library:
static{
  System.loadLibrary([NAME].dll);
}

The Native Library path has to be set (in Eclipse, right-click on the folder containing your class and click Build-Path).

*Include the method names public native void [methodname]();.

*Compile the .java file using javac.exe (or let for example Eclipse do the work).

*Create a C++ header-file using javah.exe with -jni parameter.

*Create a new project in Visual Studio (Visual C++ MFC DLL).

*Copy the created header-file (your Java Project), the jni.h (JDK) and the jni_md.h (JDK)

*Include all three header-files in your Visual C++-project header-file [Project-Name].h

*Include the created header-file and the jni.h-file in [Project-name].cpp.

*Write desired code in your [Project-name].cpp.

*Build the DLL, put it inside your defined path for Native Libraries (see italic in 2.).

*Run and be happy!
Sorry for any mistakes!
An example with Visual Basic-DLL and JNI can be found 1HERE and somewhere else, google "classle" and "JNI" (can't post 2 links).


Q: Finding the value of p while solving a recurrence equation using Akra-Bazzi method? I am learning to solve recurrence equations using Akra-Bazzi method. I am stuck in figuring out how to find out the value of p by solving equations like:
$$\left(3\over4\right)^p + \left(1\over6\right)^p=1$$
$$\left(1\over2\right)^p + \left(1\over4\right)^p + \left(1\over8\right)^p=1.$$
I want to find it out with using a scientific calculator and not wolfram alpha as online tools are not allowed during my exam.

A: First off, in general $p$ will be some transcendental number without a clean closed form in terms of familiar constants.  So I assume you just want to find $p$ to some reasonable accuracy.
I would attack this with  the following method, illustrated for the first of your equations. I would convert (by multiplying the whole equations by the least common multiple of the fractions on the left) to
$$
9^p + 2^p = 12^p
$$
Then starting with a guess $p_{old} = 1$ I would iterate using $p_{old}$ on the left and the next guess $p_{new}$ on the
$$
p_{temp} = \log_{12} (9^{p_{old}} + 2^{p_{old}}) \\
p_{new} = 2 p_{temp} - p_{old}
$$
This algorithm converges geometrically, that is, each new guess has half the error of the previous guess.  FOr this example, going through this step (which can easily be set up to need just a couple of button pushes) converges to better that $.001$ accuracy after seven steps.  ($p_7 = 0.852537$; the correct value is $.851838$.)
However, you have to be careful.  Sometimes (for example if all of the fractions are greater than $1$), $p$ needs to be negative, and then this method will not converge.  You can generally manipulate it into some related equation where it does converge.
For your second example, this method for some reason converges really quickly. The fourth iteration already gives 6-digit accuracy.


Q: Customize List's cells in DashCode I have my site created with Dashcode and I am using the List object but I don't like the default blue background when a cell is selected.
How can I customize this? For example change it to grey or white, etc.
(As far as i know, everything is customizable in Dashcode, is just sometimes you have to do it using code and not Dashcode UI.)
Thanks in advance.

A: Answer to my self:
looking at main.css I found something like:
.listRowTemplate_template.selected {
    background-color: rgb(56, 0, 217);
}

Which is the color I want to change ;)

A: Which would have been my answer, shall i vote you up? ;-)
It is easy to forget that when in Dashcode it is "just" JavaScript, CSS and HTML and so many problems will often succumb to those type of solutions such as you have done.