text:
Q: can we a prove ⊢ (α → α) → (α → α) The system L0 is defined as follows:
Axioms:
A1 (α → (β → α))
A2 2. (α → (β → γ) → ((α → β) → (α → γ))
A3 ((¬β → ¬α) → ((¬β → α) → β))
In one of my problem sheets, I am told that I am allowed to use the following theorem:
if
⊢ (α → α)
⊢ (α → α) → (α → α)
My attempt to solve/prove the second one
⊢ (α → α) → (α → α)
choose 2 axioms which match.
α →α
β→α
γ→α
(α → (α → α) → ((α → α) → (α → α))
I'm struggling to see an obvious way of proving the theorem.
Is it provable? And if so, can you point me in the right direction?
Thanks a lot!

A: The other answers show how to prove $P\to P$ and then set $P\equiv(\alpha\to\alpha)$. This works, of course.
But your particular goal can be reached faster with the axioms you have:

*

*$(\alpha\to(\alpha\to\alpha))$

*$(\alpha\to(\alpha\to\alpha))\to((\alpha\to\alpha)\to(\alpha\to\alpha))$
are instaces of your axioms 1 and 2, respectively.
Now use Modus Ponens once and you're done.

A: Here is a proof of $\alpha \to \alpha$:
\begin{array}{lll}
1 & (\alpha \to ((\alpha \to \alpha) \to \alpha) \to ((\alpha \to (\alpha \to \alpha)) \to (\alpha \to \alpha)) &A2\\
2 & \alpha \to ((\alpha \to \alpha) \to \alpha & A1\\
3 & (\alpha \to (\alpha \to \alpha)) \to (\alpha \to \alpha)& MP \ 1,2\\
4 & \alpha \to (\alpha \to \alpha) & A1\\
5 & \alpha \to \alpha & MP \ 3,4\\
\end{array}
To get a proof of $(\alpha \to \alpha) \to (\alpha \to \alpha)$, simply substitute $\alpha \to \alpha$ for $\alpha$ in the previous proof:
\begin{array}{lll}
1 & ((\alpha \to \alpha) \to (((\alpha \to \alpha) \to (\alpha \to \alpha)) \to (\alpha \to \alpha)) \to (((\alpha \to \alpha) \to ((\alpha \to \alpha) \to (\alpha \to \alpha))) \to ((\alpha \to \alpha) \to (\alpha \to \alpha))) &A2\\
2 & (\alpha \to \alpha) \to (((\alpha \to \alpha) \to (\alpha \to \alpha)) \to (\alpha \to \alpha) & A1\\
3 & ((\alpha \to \alpha) \to ((\alpha \to \alpha) \to (\alpha \to \alpha))) \to ((\alpha \to \alpha) \to (\alpha \to \alpha))& MP \ 1,2\\
4 & (\alpha \to \alpha) \to ((\alpha \to \alpha) \to (\alpha \to \alpha)) & A1\\
5 & (\alpha \to \alpha) \to (\alpha \to \alpha) & MP \ 3,4\\
\end{array}
Notice how you can always do this substitution trick: once you have proving something using some statements variables, you can always substitute any complex statement for those variables. That is, once you have proven that $\vdash \alpha \to \alpha$, then you can immediately conclude that  $\vdash (\alpha \to \alpha) \to (\alpha \to \alpha)$ without having to write out an actual derivation.

A: A logical axiom is a schema (plural: schemata, or schemas) i.e. a "template" that we can use to produce infinitely many formulas all having the same patter.
Thus, all the following formulas are instances of the axiom schema A.1 :

$p \to (q \to p), p \to (p \to p), (p\to q) \to (r \to (p \to q))$, etc.

The same holds for theorems, i.e. logical (schematic) formulas derived from axioms.
Thus $\vdash \alpha \to \alpha$ is again a schema, meaning that every instance of it is derivable in the calculus :

$p \to p, q \to q, (p \to q) \to (p \to q), (p \to p) \to (p \to p)$, etc.

The proof of $\vdash \alpha \to \alpha$ is quite simple :
1) $\vdash \alpha \to ((\beta \to \alpha) \to \alpha)$ --- Ax.1
2) $\vdash \alpha \to(\beta \to \alpha)$ --- Ax.1
3) $\vdash (1) \to ((2) \to (\alpha \to \alpha))$ --- Ax.2

4) $\vdash \alpha \to \alpha$ --- from 3), 1) and 2) by Modus Ponens twice.

For an alternative approach, see the post A Logical Axiom that is Not a Schema.


text:
Q: REST equivalent of CreateEnvelopeFromTemplates? The SOAP method CreateEnvelopeFromTemplates takes a list of TemplateReference objects which allows me to create a 1-1 mapping of documents in my ECM system to DocuSign Templates. This has worked great up until now and has allowed me to build an envelope creation algorithm without having to know how many documents are involved in a specific use case.
SOAP however does not support the new Payment tabs. In trying to find a REST replacement for this API call I haven't been able to find a way to create an envelope where each document references a different Template. The envelopes: create method for example only allows for one templateID in the envelopeDefinition. Is there a way to port the functionality I've built over to REST?
BONUS QUESTION: Why does the DocuSign backend differentiate between SOAP and REST created envelopes when applying Templates? I didn't expect to be able to programatically create Payment tabs on an envelope with SOAP, but I'm surprised specifying a Template with Payment tabs using SOAP prevents those tabs from working.
This is my SOAP call with non-functional referencing a Template with non-functional Payment tabs:
    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CreateEnvelopeFromTemplates xmlns="http://www.docusign.net/API/3.0">
            <TemplateReferences>
                <TemplateReference>
                    <TemplateLocation>Server</TemplateLocation>
                    <Template>8E556CD1-D343-4C07-9401-D88B00A67671</Template>
                    <Document>
                        <ID>90267</ID>
                        <Name>DS - Template Mapping - 12/4/2017 John Payme2 (90267)</Name>
                        <PDFBytes>omitted</PDFBytes>
                        <FileExtension>pdf</FileExtension>
                    </Document>
                    <RoleAssignments>
                        <RoleAssignment>
                            <RoleName>Payer</RoleName>
                            <RecipientID>37974046</RecipientID>
                        </RoleAssignment>
                    </RoleAssignments>
                    <Sequence>1</Sequence>
                </TemplateReference>
            </TemplateReferences>
            <Recipients>
                <Recipient>
                    <ID>37974046</ID>
                    <UserName>John Payme2</UserName>
                    <Email>ANDREW.MORTON@HYLAND.COM</Email>
                    <Type>Signer</Type>
                    <AccessCode />
                    <RequireIDLookup>false</RequireIDLookup>
                    <RoutingOrder>1</RoutingOrder>
                    <Note/>
                    <RoleName>Payer</RoleName>
                </Recipient>
            </Recipients>
            <EnvelopeInformation>
                <AccountId>9cace92e-1384-4cf7-9b4c-a2bd70aab9a1</AccountId>
            </EnvelopeInformation>
            <ActivateEnvelope>true</ActivateEnvelope>
        </CreateEnvelopeFromTemplates>
    </soap:Body>
</soap:Envelope>

A: Ergin responded to your primary qs, now for your Bonus qs, DocuSign will still allow you to create an envelope using SOAP API if you are using template which has Payment tabs. I don't see any issue in creating an envelope using SOAP API. I tested it, and I got the payment screen at the time of signing. Please find the SOAP Request to create an envelope with Payment's Template. It uses different operation CreateEnvelopeFromTemplatesAndForms and CompositeTemplate design pattern. You just have to set accountGuid, TemplateGuid and RoleName which is set in a template.
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
  <SOAP-ENV:Body>
    <CreateEnvelopeFromTemplatesAndForms xmlns="http://www.docusign.net/API/3.0">
      <ActivateEnvelope>true</ActivateEnvelope>
      <EnvelopeInformation>
        <AccountId>{{accountId}}</AccountId>
        <Subject>Test SOAP Subject</Subject>
        <EmailBlurb>Test SOAP Body</EmailBlurb>
      </EnvelopeInformation>
      <CompositeTemplates>
        <CompositeTemplate>
          <ServerTemplates>
            <ServerTemplate>
              <Sequence>1</Sequence>
              <TemplateID>{{TemplateId}}</TemplateID>
            </ServerTemplate>
          </ServerTemplates>
          <InlineTemplates>
            <InlineTemplate>
              <Sequence>2</Sequence>
              <Envelope>
                <AccountId>{{accountId}}</AccountId>
                <Recipients>
                  <Recipient>
                    <ID>1</ID>
                    <RoleName>Signer1</RoleName>
                    <UserName>Signer 1</UserName>
                    <Email>email@gmail.com</Email>
                    <Type>Signer</Type>
                  </Recipient>
                </Recipients>
              </Envelope>
            </InlineTemplate>
          </InlineTemplates>
        </CompositeTemplate>
      </CompositeTemplates>
    </CreateEnvelopeFromTemplatesAndForms>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

A: What you are looking for is called Composite Templates in the REST API.  Composite templates are a very powerful feature though they can get complex pretty quickly - using CTs you can do things like combine a template and a document in the same envelope, or combine multiple templates, etc.
One of the better resources on composite templates is the features page on Templates found in the Developer Center, which has a section for composite templates:
https://www.docusign.com/developer-center/explore/features/templates#composite
There's a section in the Envelopes:create API documentation that talks about composite templates.

Example Usage:
Here's a quick sample from one of the above resources, in this example two templates are combined into one single envelope:
{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle Foursquare hours API to find out if the venue is opened or closed I have a foursquare hours array (Foursquare API) that stores segments of hours when a specific venue is open. It looks something like this:
[{
    "days":[1,2,3,4,7],
    "includesToday":true,
    "open":[
        {"end":"+0200","start":"1000"}],
    "segments":[]},
{
    "days":[5,6]
    ,"open":[
        {"end":"+0300","start":"1000"}],
    "segments":[]}
]

How do I find out if the venue is opened or closed at current time?

A: I handle it like this: 4sq hours API gist
-(NSDictionary*)isVenueOpenDictionaryForHours:(NSArray*)hours{
  //  defaults and inits
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDictionary *lastSegmentYesterday = [[NSDictionary alloc] init];
    NSDate *dateNow = [NSDate date];
    NSString *venueOpenText = [[NSString alloc] init];
    NSString *venueOpen = @"no";

  //  get components for today
    NSDateComponents *compsNow = [gregorian components:NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:dateNow];

  //  get weekday for today and yesterday so we can lookup 4sq API
    NSInteger weekday = [compsNow weekday];
    NSInteger weekdayYesterday = (weekday>1)?weekday-1:7;

  //  look for todays' segment
    NSMutableArray *venueOpenSegments = [[NSMutableArray alloc] init];   //  stores all the segments when the venue is open
    for (NSDictionary *segment in hours){
      //  get today's segment (if it exists)
        if ([segment[@"days"] containsObject:[NSNumber numberWithInteger:weekday]]){
          for (NSDictionary *dictOpen in segment[@"open"])
            [venueOpenSegments insertObject:@{@"end": [dictOpen[@"end"] mutableCopy], @"start":[dictOpen[@"start"] mutableCopy]}.mutableCopy atIndex:venueOpenSegments.count];
        }

      //  check the day before if the venue is open past midnight
        if (([segment[@"days"] containsObject:[NSNumber numberWithInteger:weekdayYesterday]] && [segment[@"open"] count])){
          //  get the last segment (that should be the one passing midnight)
            NSDictionary *tempSegment = [segment[@"open"] lastObject];

            //  if it has more than 4 characters it's after midnight ("+02:00"), also, ignore if it closes at midnight
              if ([tempSegment[@"end"] length] > 4 && ![tempSegment[@"end"]isEqualToString:@"+0000"]){
                //  create a new segment that starts at midnight and lasts till the time it closes (early AMs usually)
                  lastSegmentYesterday = @{@"start":@"0000", @"end":[tempSegment[@"end"] substringFromIndex:1]};
              }
        }
      }

  //  add last night segment that passes midnight as the first segment of today
    if (lastSegmentYesterday.count){
      [venueOpenSegments insertObject:lastSegmentYesterday atIndex:0];
    }

// go through all the segments and find out if the venue is closed or open
  if (venueOpenSegments.count){
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init];
    timeFormatter.dateFormat = @"HH:mm";    //  set time output format

    int segmentNumber = 0;
    for (NSMutableDictionary *segment in venueOpenSegments){
      segmentNumber++;

      //  confing start date
        [comps setDay:compsNow.day];
        [comps setMonth:compsNow.month];
        [comps setYear:compsNow.year];
        [comps setHour:[[segment[@"start"] substringToIndex:2] intValue]];
        [comps setMinute:[[segment[@"start"] substringFromIndex:2] intValue]];
        NSDate *dateStart = [[[NSCalendar currentCalendar] dateFromComponents:comps] copy];

      //  config end date
        //  check if the segment goes to next day
          BOOL closesTomorrow = NO;
          if ( [segment[@"end"] length]==5 ){
            segment[@"end"] = [segment[@"end"] substringFromIndex:1];
            closesTomorrow = YES;
          }

          [comps setHour:[[segment[@"end"] substringToIndex:2] intValue]];
          [comps setMinute:[[segment[@"end"] substringFromIndex:2] intValue]];
          NSDate *dateEnd = [[[NSCalendar currentCalendar] dateFromComponents:comps] copy];

          //  add a day if it closes tomorrow
            if (closesTomorrow){
              NSDateComponents *nextDayComponent = [[NSDateComponents alloc] init];
              nextDayComponent.day = 1;
              dateEnd = [gregorian dateByAddingComponents:nextDayComponent toDate:dateEnd options:0];
            }

        //  start checking if it's open or closed
          //  now < segment start
            if ([dateNow compare:dateStart] == NSOrderedAscending){
              venueOpenText = [NSString stringWithFormat:@"opens at %@",[timeFormatter stringFromDate: dateStart]];
              venueOpen = @"later";
              break;
            }

          //  segment end < now
            else if ([dateEnd compare:dateNow] == NSOrderedAscending){
              if (segmentNumber == venueOpenSegments.count){
                venueOpenText = [NSString stringWithFormat:@"closed since %@",[timeFormatter stringFromDate: dateEnd]];
                break;
              }
              continue;
            }

          //  segment start < now < segment end
            else if ([dateStart compare:dateNow] == NSOrderedAscending && [dateNow compare:dateEnd] == NSOrderedAscending){
              venueOpenText = [NSString stringWithFormat:@"open till %@",[timeFormatter stringFromDate: dateEnd]];
              venueOpen = @"yes";
              break;
            }

          //  rare but possible... last minute of the venue being open (I treat it as closed)
            else {
              venueOpenText = @"closing right now";
            }
        }
    }
    else venueOpen = @"closed today";    //  no segments for today, so it's closed for the dayæ

  //  return results
    return      @{@"open":venueOpen, @"string":venueOpenText};
}

and I update my UILabel like this:
NSDictionary *venueOpen = [self isVenueOpenDictionaryForHours:_arrayVenues[indexPath.row][@"hours"]];
label.text = venueOpen[@"string"];
if ([venueOpen[@"open"] isEqualToString:@"no"]){
    label.textColor = [UIColor colorWithHexString:@"b91d47" alpha:1];   // red
} else if ([venueOpen[@"open"] isEqualToString:@"yes"]) {
    label.textColor = [UIColor colorWithHexString:@"1e7145" alpha:1];   // green
} else if ([venueOpen[@"open"] isEqualToString:@"later"]) {
    label.textColor = [UIColor colorWithHexString:@"e3a21a" alpha:1];   // yellow
}

BTW, I use pod 'HexColors' for colorWithHexString methods


text:
Q: How to appear Appendix in list of contents? I wounder if you could help me to appear (Appendix A) in list of contents.
my code is:
\documentclass[12pt]{report}
\usepackage{times} %Times new roman font
%\usepackage{mathptmx}

\usepackage[top=2.5cm, bottom=2.5cm, left=3.5cm, right=2.5cm]{geometry}
\usepackage{amsfonts,amsmath,amssymb}

\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}

\begin{document}
\chapter*{Copyright}
\addcontentsline{toc}{chapter}{Copyright}
test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test Appendix \ref{app:benchmark}
\newpage

\tableofcontents
\addcontentsline{toc}{chapter}{Contents}
\newpage

\appendix
\makeatletter
\makeatother

\chapter{}

\section{IEC microgrid data}
\label{app:benchmark}
\begin{itemize}
\item Utility: rated short-circuit MVA=1000, f=60 Hz, rated kV=120, $V_{base}$=120 kV.
\item Distributed Generations (DGs):
\begin{itemize}
\item DG1, DG3: synchronous generator with rated MVA=9, f=60Hz, rated kV=2.4, Inertia constant H=1.07 s, friction factor F=0.1 pu, Rs=0.0036 pu, $Xd$=1.56 pu, $Xd^\prime$=0.296 pu, $Xd^{\prime\prime}$=0.177 pu, $Xq$=1.06 pu, $Xq^{\prime\prime}$=0.177 pu, $Xl$=0.052 pu, $Td^\prime$=3.7 s, $Td^{\prime\prime}$=0.05 s, $Tq0^{\prime\prime}$=0.05 s.
\end{itemize}
\end{itemize}
\section{Distributed energy source data}
\end{document}

A: I have added Appendix A that appear into list of contents using \usepackage[titletoc]{appendix} and \begin{appendices} .... \end{appendices}. Is it the result you wanted to achieve?

\documentclass[12pt]{report}
\usepackage{newtxtext, newtxmath}
\usepackage[top=2.5cm, bottom=2.5cm, left=3.5cm, right=2.5cm]{geometry}
\usepackage{amsfonts,amsmath,amssymb, lipsum}
\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}
\usepackage[titletoc]{appendix}

\begin{document}
\chapter*{Copyright}
\addcontentsline{toc}{chapter}{Copyright}
\lipsum[1-2]

\ref{app:benchmark}
\newpage

\tableofcontents
\addcontentsline{toc}{chapter}{Contents}
\newpage
\makeatletter
\makeatother
\begin{appendices}
\chapter{}

\section{IEC microgrid data}
\label{app:benchmark}
\begin{itemize}
\item Utility: rated short-circuit MVA=1000, f=60 Hz, rated kV=120, $V_{base}$=120 kV.
\item Distributed Generations (DGs):
\begin{itemize}
\item DG1, DG3: synchronous generator with rated MVA=9, f=60Hz, rated kV=2.4, Inertia constant H=1.07 s, friction factor F=0.1 pu, Rs=0.0036 pu, $Xd$=1.56 pu, $Xd^\prime$=0.296 pu, $Xd^{\prime\prime}$=0.177 pu, $Xq$=1.06 pu, $Xq^{\prime\prime}$=0.177 pu, $Xl$=0.052 pu, $Td^\prime$=3.7 s, $Td^{\prime\prime}$=0.05 s, $Tq0^{\prime\prime}$=0.05 s.
\end{itemize}
\end{itemize}
\section{Distributed energy source data}
\end{appendices}
\end{document}


text:
Q: How to embed servlet generated PDF into  tag? In my servlet, I use Jasper to generate a PDF report as follows:
        JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameters, conn);
        response.setContentType("application/pdf");
        servletOutputStream.flush();
        servletOutputStream.close();

This is my AJAX call to generate the PDF. When the call to the service completes successfully and I attempt alert the data, it shows binary data that starts with "%PDF-1.4...".
        $.ajax({
            url : pdfURL,
            success : function(data) {
                alert(data); //contains "%PDF-1.4..."

                //How do I put this "data" into an <OBJECT>?
                //This code below is NOT working
                var obj = $('<object type="application/pdf" width="100%" height="100%" border="2"></object>');
                obj.attr('src',data);
                $('#rptDiv').append(obj);
            }
        });

Now how do I put this PDF data into an OBJECT element and embed it to a DIV?


text:
Q: Using awk to find all words matching all patterns Given an tab-delimited input like this:
us-west-2       vpc-abcdefg  42   elb-foo-bar-baz
us-east-1       foo     vpc-123455      eipalloc-bar

I want to use awk to do some pattern matching such that I can find all the words that matches vpc-*, elb-*, or eipalloc-* in the input. I also want awk to only read the input in one pass.
My outputs should be space-delimited matched values:
vpc-abcdef vpc-123455
elb-foo-bar-baz
eipalloc-bar

How would I go about it?

A: Try this (where gash.txt is your input file):
awk -f - gash.txt << '__END__'
    BEGIN {
        tags["vpc"] = ""
        tags["elb"] = ""
        tags["eipalloc"] = ""
    }
    { for (i=1; i <= NF; i++) {
          n = split($i, a, "-")
          if (a[1] in tags)
              print $i
      }
    }

__END__

The associative array in the BEGIN block is probably an overkill, but it makes it easier to add more targets in the future.
EDIT:
I realised I was not producing the output in the same style as required, apologies.  Using that associative array it becomes fairly easy to modify:
awk -f - gash.txt << '__END__'
    BEGIN {
        tags["vpc"] = ""
        tags["elb"] = ""
        tags["eipalloc"] = ""
    }
    { for (i=1; i <= NF; i++) {
          n = split($i, a, /-/)
          if (a[1] in tags)
              tags[a[1]] = tags[a[1]] $i " "
      }
    }
    END {
        for (item in tags)
            print tags[item]
    }

__END__

A: Might consider using grep with -o that will extract matches:
% grep -oE '(vpc|elb|eipalloc)-[^ ]*' data.txt
vpc-abcdefg
elb-foo-bar-baz
vpc-123455
eipalloc-bar

I know it doesn't give the exact output format, but it might be ok?

A: another awk
$ awk -v RS='\t|\n' 'BEGIN{split("vpc- elb- eipalloc-",ks)}
                          {for(k in ks) if($0~ks[k]) a[k]=a[k]?a[k] FS $0:$0}
                       END{for(k in a) print a[k]}' file

vpc-abcdefg vpc-123455
elb-foo-bar-baz
eipalloc-bar


text:
Q: Installing applications temporarily I am using Ubuntu 13.10. To post some answers I may need to install some applications which I won't use much. So I would love to install those apps in way that they are gone after a restart.
How can I do this?

A: Try overlayfs. I've used it lots of places. Here are the steps to set it up (it's really easy)
Note: this will sandbox your whole system until you either remove the mount or restart. The way I describe it, it's an all-or-nothing situation. Either you're sandboxing everything (browser history, changed settings, etc.) or nothing at all. If you do some research you might be able to tweak it more to your needs, but give it a try!
First, make the directory to host your sandbox:
mkdir /tmp/sandbox

Now, mount that bad boy
sudo mount -t overlayfs -o upperdir=/tmp/sandbox,lowerdir=/ overlayfs /

That's it! You should now be running a sandboxed machine! When you reboot /tmp/sandbox should be gone.


text:
Q: Why doesn't light affect a compass? In our daily life a lot of photons of visible light, infrared and radio etc move around us. We know that light is an electromagnetic radiation. So why doesn't that electromagnetic radiation affect a magnetic compass?

A: Most electromagnetic radiation is of very high frequency - the magnetic field changes many times per second. This means that the compass just doesn't have time to "follow" the magnetic field changes.
The only thing that does affect a compass is a DC magnetic field - usually this is a large piece of iron etc. that gets magnetized (e.g. by the earth's magnetic field) and thus causes distortion; or it can be a DC current loop of some kind.
But even the low frequencies of the mains (50 or 60 Hz depending on where you live) are much too fast to affect the compass (although in the presence of a strong source of electromagnetism, such as a large transformer, you can see vibration in the needle as observed by @vsz). Radio starts in the kHz (for long wave) to MHz (FM) or GHz (WiFi etc). And light, with wavelengths around 500 nm and a speed of 3x10$^8$ m/s,  has frequencies in the hundreds of THz range. Too fast.
UPDATE - adding a bit of math(s):
A compass in the earth's field can be thought of as a damped oscillator: on the one hand there's the torque on the needle that is proportional to the displacement from magnetic North, on the other there's the inertia of the needle; and finally, there are damping terms (a good compass is critically damped - meaning that the damping is such that it will go to the right position in the shortest time).  We can write the equation of motion as
$$I\ddot\theta + \mu\dot\theta + k\theta = 0$$
In this expression, $\mu$ is the damping term (proportional to the angular velocity) and $k$ is the factor that describes how much torque the needle experiences with displacement.
This is a general equation for a Simple Harmonic Oscillator (SHO), and we typically recognize three regimes: lightly damped, heavily damped, and critically damped.
How such an oscillator responds when you give it a displacement and then let it go depends on the kind of damping - see this graph:

In particular, the critically damped oscillator converges to its equilibrium position as fast as possible - which is why it's preferable for things like a compass.
Now when you drive a SHO with an oscillating force, you get a response that depends on the frequency of the drive signal and the natural frequency of the system. If you drive at the natural frequency, you get resonance and the amplitude becomes large; as the difference in frequency gets larger, the amplitude of the response gets smaller.  For a lightly damped (or underdamped) system*, the amplitude response is given by
$$A = \frac{s_0}{\sqrt{\left[1-\left(\frac{\omega_d}{\omega_0}\right)^2\right]^2 +\left[\frac{\omega_d/\omega_0}{Q}\right]^2}}$$
In the limit of large frequencies, the response scales with
$$A \propto \left(\frac{\omega_0}{\omega_d}\right)^2$$
where $\omega_0$ is the natural frequency $\sqrt{\frac{k}{I}}$ and $\omega_d$ is the driving frequency. When the driving frequency is many orders of magnitude larger than the natural frequency, the amplitude response will be negligible.
As was pointed out in a comment by MSalters, at extremely high frequencies (above 10 GHz) the wavelength of the EM radiation becomes short compared to the length of the compass needle, so the above is further complicated by the fact that different parts of the needle will experience forces in different directions. All of which points in the same direction: the needle won't move.

* I am taking the easy way out here... did not find the expression for the critically damped driven oscillator and don't have the intestinal fortitude to derive it right now and trust myself to get it right. But this is 'directionally correct' even for critically damped oscillator

A: The frequency is one very good argument (and I guess the most important factor) but it might be worth also looking at the magnitudes of the fields.
The earth's magnetic field has a strength of roughly $31µT$. The intensity of the sunlight hitting the earth is about $1300W/m^2$. Since the intensity is related to the electric field $E$ of an electromagnetic wave in the following way $$I=\frac{1}{2}\epsilon_0 c E^2 $$ and the magnetic field strength is given by $B=1/c \times E$, one can easily calculate that the magnitude of the magnetic field is given by $$B\approx 3.3 µT.$$
So the earth's magnetic field is roughly ten times stronger.
But: It can now be argued that fields with higher intensity would have greater impact. Now the frequency argument rescues us and in fact this argument seems to be the correct one, as one does not notice a deflection of a compass needle in the presence of a strong laser.

A: Basically the same reason as what Floris said, but this also has another important aspect:
Visible light has a far too small wavelength to affect a compass. Not only does the field oscillate too quickly around an average of zero – even at any single "snapshot" in time of the electromagnetic wave, there would nowhere be a large region where the field points in one direction. Only fractions of a micrometer are exposed to a field in a single direction; move a hair-width and the field may point in the opposite direction. Overall, at any given time, the forces on all parts of the needle cancel almost completely. So even if the light frequency wasn't to high for the needle to follow, it would still not move.


text:
Q: C++ error in a custom queue: pointer being freed was not allocated I'm trying to create a generic queue class based off a custom vector. My code runs fine in the sense that it outputs everything I want it to given my input, and doesn't crash. However, if I call my queue.pop(), I get the following as the program finishes executing:
a.out(6878) malloc: *** error for object 0x7fb210403981: pointer being freed was not allocated

My vector is built around an array of type T, declared T * typeArray;. All queue.pop() does is call a function from my vector, vector.pop_front(). The line that seems to be causing the problem is
// Assign the pointer to the second position in the array.
typeArray = &typeArray[1];

What am I doing wrong? Why doesn't this work? Thanks!

A: You're only allowed to delete a pointer that was returned to you by new (the same principle holds for malloc and free).
Once you replace the original pointer with
typeArray = &typeArray[1];

it's an error to
delete [] typeArray;

You need to maintain separate pointers for the allocated storage and for the queue's head.


text:
Q: CosmosDb count distinct elements Is there a direct function to count distinct elements in a CosmosDb query?
This is the default count:
SELECT value count(c.id) FROM c

And distinct works without count:
SELECT distinct c.id FROM c

But this returns a Bad Request - Syntax Error:
  SELECT value count(distinct c.id) FROM c
How would count and distinct work together?

A:
How about SELECT COUNT(1) FROM (SELECT distinct c.id FROM c) AS t;? – Evaldas Buinauskas May 30 '18 at 14:44

On 15 May 2019, The comment above is working with Where condition, I didn't try with a Join but the request does return the answer I'm looking for.
And it is working with the 100 elements limitation in CosmosDB.
If I make an example with Product it should be :
SELECT COUNT(1) FROM (SELECT DISTINCT c.Id FROM c WHERE c.Brand = 'Coca')

A: I know this is an old thread.
However, just to keep the topic updated, currently (Jul 2020) you are able to do SELECT DISTINCT over Cosmos DB table. However directly applying COUNT(DISTINCT..) doesnt give correct results.
Hence, you need to apply a workaround as below using a subquery based approach to get the correct distinct count results
SELECT COUNT(UniqueIDValues) AS UniqueCount
FROM (SELECT Id FROM c GROUP BY Id) AS UniqueIDValues

A: I did some investigation and found solution for it. In order to get count of distinct results you can not use count(1). You need to "wrap" subquery with AS subqueryName and then use count(subqueryName) like below:
select count(subqueryName) from (SELECT distinct r.x FROM r) as subqueryName

Cheers!

A: As I know, for now, Cosmos DB does not support nested queries.
The only way to do what u want is to return all distinct ids as a query result and then do count on them. You can either do in directly in code or with help of stored procedure(that should be more efficient on big number of docs).

A: [Update 19 Nov 2020]
Here is another query that solves the district issue and works for count. Basically, you need to encapsulate the distinct and then count. We have tested it with paging for cases that you want the unique records and not just the count and it's working as well.
select value count(1) from c join (select distinct value c from p in c.products)

You can also use where clause inside and outside of the bracket depending on what your condition is based on.
This is also mentioned slightly differently in another answer here.
Check the select clause documentation for CosmosDB.
@ssmsexe brought this to my attention and I wanted to update the answer here.
[Original Answer]
Support for distinct has been added on 19th Oct 2018
The following query works just fine
SELECT distinct value c FROM c join p in c.products

However, it still doesn't work for count.
The workaround for counting distinct is to create a stored procedure to perform the distinct count. It will basically query and continue until the end and return the count.
If you pass a distinct query like above to the stored procedure below you will get a distinct count
function count(queryCommand) {
  var response = getContext().getResponse();
  var collection = getContext().getCollection();
  var count = 0;

  query(queryCommand);

  function query(queryCommand, continuation){
    var requestOptions = { continuation: continuation };
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        queryCommand,
        requestOptions,
        function (err, feed, responseOptions) {
            if (err) {
                throw err;
            }

            //  Scan results
            if (feed) {
                count+=feed.length;
            }

            if (responseOptions.continuation) {
                //  Continue the query
                query(queryCommand, responseOptions.continuation)
            } else {
                //  Return the count in the response
                response.setBody(count);
            }
        });
    if (!isAccepted) throw new Error('The query was not accepted by the server.');
  }
}

The issue with that workaround is that it can potentially cross the RU limit on your collection and be unsuccessful. If that's the case you can implement a similar code on the server side which is not that great.

A: To count distinct elements you have to use COUNT and GROUP BY together. You don't need need subqueries, it works in a very simple query like this example where we want to list all the family unique last names in our container and the count of families having the same name:
select count(1) as numfam, f.lastName from f group by f.lastName

result:
[
    {
        "numfam": 1
    },
    {
        "numfam": 1,
        "lastName": "Wakefield"
    },
    {
        "numfam": 2,
        "lastName": "Andersen"
    }
]

Notice I have one item in my collection without lastName, freedom of being schemaless.
unfortunately today is not yet possible to add an "order by" clause to the query to sort for example the most common names in descending order. The cosmos team declared is working on it though, so this feature is expected at some point. You can always sort the result  in your client code.
If you want to know the count for a specific name you can use this query (you can use a parametrized query to input the name in one place) :
select "Andersen" as lastName, count(1) as numfam from f
where  f.lastName = "Andersen"

result:
[
    {
        "lastName": "Andersen",
        "numfam": 2
    }
]

A: Azure cosmos DB doesn't support the distinct keyword yet as part of the SQL API.
The best way to achieve this is by using the stored procedure with custom code.
Please find more details regarding the custom stored proc here.
It seems the distinct keyword is underdevelopment.
Please find the reference link here.
cosmos DB supports most of the aggregate functions, please see the list of of supported aggregate functions here.
Please find the more details in the following link.


text:
Q: DropDownList display only Name of Models i have to create a DropDownList which value filled from database through WCF REST. as this far the json got the data, but when i use it and put it on DropDownList HTML Helper, the SelectList always shown only Name of the Model.
Screenshot Result Name of model
but when i put the model on @HTML.DisplayFor , the data shown like this
View
@Html.DisplayFor(model => model.GetClassID, "Select")
@Html.DropDownListFor(model => model.GetSchedule.ClassIDS, new SelectList(Model.GetClassID, "ClassID"), new { @class = "select2" })

i'm used Select 2 but pretty sure this isn't class mistake, coz nothing changed when i delete the class
Retrieve JSON from WCF
public List<ClassIDOnly> GetSingleClassID()
{
    var json = new WebClient().DownloadString(SU.URLService + "ViewSingleClassID");
    JObject rss = JObject.Parse(json);
    JArray items = (JArray)rss["GetSingleClassIDResult"];
    var myReturn = new List<ClassIDOnly>();
    for (int i = 0; i < items.Count; i++)
    {
        myReturn.Add(new ClassIDOnly
        {
            ClassID = Convert.ToInt32(rss["GetSingleClassIDResult"][i]["ClassID"]),
        });
        Console.WriteLine(myReturn);
    }
    return myReturn;
}

it works properly.
Model
public class MixSchedule
{
    public Schedule GetSchedule { get; set; }
    public List<ClassIDOnly> GetClassID { get; set; }
}

Controller
ClassModel cm = new ClassModel();
var viewm = new MixSchedule
{
    GetClassID = cm.GetSingleClassID()
};
return View (viewm);

i was try many way including use ViewBag but the result are same. is there something wrong with my code? Thanks in advance.

A: So I think you need to review a few things:

*

*In your model, GetClassID should not reflect a list of elements but the element selected by the user:
I could look like this:
public class MixSchedule { public string ClassID { get; set; } }

*If you don't tell SelectList which is the dataTextField it will call to ToString method. That's why you're not getting the right text. So it should look something like this:
@Html.DropDownListFor(model => model.ClassID, new SelectList(Model.GetClassID(), "ClassID", "ClassID"), new { @class = "select2" })


text:
Q: How to efficiently extract large dataset from Oracle to a file? I have a oracle server from where i need to extract data using python into files. These files are used by downstream systems as inputs.
Few technical details:
Oracle and Python are running on different server. The database is client hosted while all scripts are running on an AWS RHEL EC2 server. Details of the EC2 instance are highlighted in this screenshot. .
My Approach
To do this i choose Python's Pyodbc library to connect to the Remote Oracle client and extract data using the SQL query. Below is an extract of the code that fetches the data based on SQL Query provided.
def fetch_data_to_file(self,curr,query,dataset):
    try:
        self.logger.info('Executing query: {}'.format(query))
        start = time.time()
        curr.execute(query)
        query_time = time.time()-start
        start = time.time()
        rowcount=0
        with open(dataset,'a+') as f:
            writer = csv.writer(f,delimiter='|')
            writer.writerow([i[0] for i in curr.description])
            self.logger.info('Writing file: {}'.format(dataset))
            while True:
                rows = curr.fetchmany(self.batch_limit)
                self.logger.info('Writing {} rows'.format(self.batch_limit))
                rowcount+=len(rows)
                if not rows:
                    break

        self.timer.info('{} Query Execution Time: {} seconds'.format(dataset,query_time))
        self.timer.info('{} File Writing Time: {} seconds. at {} rows/second'.format(dataset,time.time()-start,int(rowcount / (time.time()-start))))

        self.logger.info("File written.")
    except Exception as e:
        self.error.info("Error in fetching data.Error: {}".format(e))
        raise SystemExit(1)

The dataset that I am extracting is close to 8GB uncompressed size (close to 35Million rows returned). And it takes the code ~1.5 hours to download the file on my EC2 server.
I tested with multiple variations of batch_limits and found 1Million - 2Million to be the optimal size to batch download data however I am unsure if there is something else i can do more efficiently to figure out what my batch size should be.
What else have i looked into
I was looking online to figure out ways to write large datasets to files using python, and many suggested using Pandas. I tried to figure that out but failed to do so. Also, it is important that i preserve the data and its datatypes while extracting them to files.
My ask here is: is there anything i can do better to make this code more efficient ? Is Python the best suited language for this? (Please note, i need to be able to automate the jobs whatever language i choose. Going for licensed libraries is a bit difficult at this point due to internal pricing challenges at my firm).
Also, not sure if this helps, but here is a snapshot of my memory usage while the code was downloading data (htop)

A: One possibility would be to download the free "SQLcl" utility, basically a Java based SQL-Plus but does much more. Download here. What you can do with SQLcl is drop it on the client machine and use it to extract the data, while also taking care of the delimiter for you. Here I'm setting the delimiter to the pipe symbol. This may be more efficient than trying to do it via Python, and you'd still be able to script it and call it from Python, or wherever.
$ sqlcl username/password@'<hostname>:<port>/ORACLE_SID'
> Set sqlformat delimited |
> Spool <some file to hold the data>
> Select * from <some table>;
> Spool off

And the above can easily be dropped into a shell script.
#!/bin/bash

sqlcl username/password@'<hostname>:<port>/ORACLE_SID' <<EOF
Set sqlformat delimited |
Spool <some file to hold the data>
Select * from <some table>;
Spool off
EOF

Example
sqlcl> Select * from emp;
"EMPNO"|"ENAME"|"JOB"|"MGR"|"HIREDATE"|"SAL"|"COMM"|"DEPTNO"
7839|"KING"|"PRESIDENT"||17-NOV-81|5000||10
7698|"BLAKE"|"MANAGER"|7839|01-MAY-81|2850||30
7782|"CLARK"|"MANAGER"|7839|09-JUN-81|2450||10
7566|"JONES"|"MANAGER"|7839|02-APR-81|2975||20
7788|"SCOTT"|"ANALYST"|7566|09-DEC-82|3000||20
7902|"FORD"|"ANALYST"|7566|03-DEC-81|3000||20
7369|"SMITH"|"CLERK"|7902|17-DEC-80|800||20
7499|"ALLEN"|"SALESMAN"|7698|20-FEB-81|1600|300|30
7521|"WARD"|"SALESMAN"|7698|22-FEB-81|1250|500|30
7654|"MARTIN"|"SALESMAN"|7698|28-SEP-81|1250|1400|30
7844|"TURNER"|"SALESMAN"|7698|08-SEP-81|1500|0|30
7876|"ADAMS"|"CLERK"|7788|12-JAN-83|1100||20
7900|"JAMES"|"CLERK"|7698|03-DEC-81|950||30
7934|"MILLER"|"CLERK"|7782|23-JAN-82|1300||10

A: A very fast solution for dumping data in CSV format is SQL*Plus 12.2's CSV mode.  If you don't already have it, you can get SQL*Plus for free from the Instant Client packages.
Create a SQL script ex.sql like:
set feedback off
set arraysize 500
select * from locations;
exit

You can/should tune ARRAYSIZE for optimum performance.
Then invoke SQL*Plus with the -m 'csv on' option.  This uses a new, fast I/O subsystem:
sqlplus -l -s -m 'csv on delim |' cj@'"localhost/orclpdb1"' @ex.sql

Note the -s option will make the prompt for the password invisible.
The output will be like:
"LOCATION_ID"|"STREET_ADDRESS"|"POSTAL_CODE"|"CITY"|"STATE_PROVINCE"|"COUNTRY_ID"
1000|"1297 Via Cola di Rie"|"00989"|"Roma"||"IT"
. . .

My release announcement blog post has some more details.

A: Just a thought in mind is to create a python method that is multithreaded breaking your dataset in parts. Depending on your target database these files can be read to external tables to eliminate one more step if you want to push it to a table.


text:
Q: Most performant storage for very large postgres data directory on Docker for Mac? I'm exploring using Docker for Mac for my local development environment. Most things are pretty clear but I'm wondering what the best approach to storage for my Postgres data directory is. My company uses full snapshots of our very large production database in development, so that adds some constraints. "Best" in this case translates roughly to whatever will be most performant.
Currently I'm using a bind mount, so the data directory lives on my host machine. This works fine. Container storage is pretty clearly a non-starter. Volumes seem like a potentially good alternative, but using the local volume type results in running out of space when the Docker.qcow2 file fills up. I know there are many other volume drivers but it's not clear if any of them are particularly good for this use case, or if I should just stick with a bind mount.

A: I think the most performant is the mount on the host, just because it is local and native. As far as I know, other drivers are often made to use remote (so less performant) storages.
For development, keep your bind mount.


text:
Q: VBA changes from a cell To explain my title, basically i have a macro code which ill display in sec that is requesting number of days that need it to be exported from our shared mailbox. Now on a daily basis I have to change the number of days we need to export and is getting really frustrating. The following line is in question:
If VBA.DateValue(VBA.Now) - VBA.DateValue(vItem.ReceivedTime) <= 10 Then

That number 10 needs to change on a daily basis so i tried with active cell but no success as i get a runtime error 438.
So my question is: Is there a way that in a separated spreadsheet to input the number of days i need to export and that line in question can take the information from there and carry on with the code ?
Please see full code below.
    Sub Accomplished()
   Application.Run "Module5.OptimizeCode_Begin"
    Dim Folder As Outlook.MAPIFolder
    Dim sFolders As Outlook.MAPIFolder
    Dim iRow As Integer, oRow As Integer
    Dim MailBoxName As String, Pst_Folder_Name  As String
    Dim vItems As Outlook.Items
    Dim vItem As Object

     'Mailbox or PST Main Folder Name (As how it is displayed in your Outlook Session)
    MailBoxName = "Castle Donington Time and Attendance"

     'Mailbox Folder or PST Folder Name (As how it is displayed in your Outlook Session)
    Pst_Folder_Name = "Accomplished" 'Sample "Inbox" or "Sent Items"

     'To directly a Folder at a high level
     'Set Folder = Outlook.Session.Folders(MailBoxName).Folders(Pst_Folder_Name)

     'To access a main folder or a subfolder (level-1)

    For Each Folder In Outlook.Session.Folders(MailBoxName).Folders
        If VBA.UCase(Folder.Name) = VBA.UCase(Pst_Folder_Name) Then GoTo Label_Folder_Found
        For Each sFolders In Folder.Folders
            If VBA.UCase(sFolders.Name) = VBA.UCase(Pst_Folder_Name) Then
                Set Folder = sFolders
                GoTo Label_Folder_Found
            End If
        Next sFolders
    Next Folder

Label_Folder_Found:
    If Folder.Name = "" Then
        MsgBox "Invalid Data in Input"
GoTo End_Lbl1:
    End If

     'Read Through each Mail and export the details to Excel for Email Archival
    ThisWorkbook.Sheets(3).Activate

    Folder.Items.sort "Received"

     'Insert Column Headers
    ThisWorkbook.Sheets(3).Cells(1, 1) = "Sender"
    ThisWorkbook.Sheets(3).Cells(1, 2) = "Subject"
    ThisWorkbook.Sheets(3).Cells(1, 3) = "Date"
    ThisWorkbook.Sheets(3).Cells(1, 4) = "Sent"
    ThisWorkbook.Sheets(3).Cells(1, 5) = "EmailID"
    ThisWorkbook.Sheets(3).Cells(1, 6) = "Categories"
    ThisWorkbook.Sheets(3).Cells(1, 7) = "Parent"
     'ThisWorkbook.Sheets(1).Cells(1, 6) = "Body"

     'Export eMail Data from PST Folder
    oRow = 1
    Set vItems = Folder.Items
    For iRow = 1 To vItems.Count
        Set vItem = vItems.Item(iRow)
        If vItem.Class = 43 Then
         'If condition to import mails received in last 60 days
         'To import all emails, comment or remove this IF condition
        If VBA.DateValue(VBA.Now) - VBA.DateValue(vItem.ReceivedTime) <= 10 Then
            oRow = oRow + 1
            ThisWorkbook.Sheets(3).Cells(oRow, 1).Select
            ThisWorkbook.Sheets(3).Cells(oRow, 1) = Folder.Items.Item(iRow).SenderName
            ThisWorkbook.Sheets(3).Cells(oRow, 2) = Folder.Items.Item(iRow).Subject
            ThisWorkbook.Sheets(3).Cells(oRow, 3) = Folder.Items.Item(iRow).ReceivedTime
            ThisWorkbook.Sheets(3).Cells(oRow, 4) = Folder.Items.Item(iRow).SentOn
            ThisWorkbook.Sheets(3).Cells(oRow, 5) = Folder.Items.Item(iRow).ConversationID
            ThisWorkbook.Sheets(3).Cells(oRow, 6) = Folder.Items.Item(iRow).Categories
            ThisWorkbook.Sheets(3).Cells(oRow, 7) = Folder.Items.Item(iRow).Parent
            'ThisWorkbook.Sheets(3).Cells(oRow, 8) = Folder.Items.Item(iRow).Sent
            'ThisWorkbook.Sheets(1).Cells(oRow, 6) = Folder.Items.Item(iRow).Body
             End If
        End If
    Next iRow
    MsgBox "Extration Complete ^.^"
    Set Folder = Nothing
    Set sFolders = Nothing

    ' sheet3_copypaste Macro

    Sheets("Sheet3").Select
    ActiveWindow.SmallScroll Down:=-33
    Range("A2:H3001").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Full List").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

    'Format
    Sheets("Full List").Select
    Columns("D:E").Select
    Selection.NumberFormat = "m/d/yyyy h:mm"
    Range("D1").Select

    ' sort Macro
    Range("D6").Select
    ActiveWorkbook.Worksheets("Full List").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Full List").sort.SortFields.Add Key:=Range("D6"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Full List").sort
        .SetRange Range("A5:I4976")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("D1").Select
End_Lbl1:
Application.Run "Module5.OptimizeCode_End"
End Sub

Thank you for taking interest.
Any questions i'm happy to answer

A: Just for consistency sake with excel and macros a workbook is a full xlsm file that contains a collection of worksheets (individual tabs that you put data on).  By a seperated spreadsheet I'm assuming a different workbook.
Here is some useful code for getting data from a spreadsheet.
The main function GetData at the bottom, instead of storing the data in a local cell you would just put it in a variable and use that in your "<" statement.
Sub GetDataDemo()

    Dim FilePath$, Row&, Column&, Address$

     'change constants & FilePath below to suit
     '***************************************
    Const FileName$ = "Book1.xls"
    Const SheetName$ = "Sheet1"
    Const NumRows& = 10
    Const NumColumns& = 10
    FilePath = ActiveWorkbook.Path & "\"
     '***************************************

    DoEvents
    Application.ScreenUpdating = False
    If Dir(FilePath & FileName) = Empty Then
        MsgBox "The file " & FileName & " was not found", , "File Doesn't Exist"
        Exit Sub
    End If
    For Row = 1 To NumRows
        For Column = 1 To NumColumns
            Address = Cells(Row, Column).Address
            Cells(Row, Column) = GetData(FilePath, FileName, SheetName, Address)
            Columns.AutoFit
        Next Column
    Next Row
    ActiveWindow.DisplayZeros = False
End Sub

Private Function GetData(Path, File, Sheet, Address)
    Dim Data$
    Data = "'" & Path & "[" & File & "]" & Sheet & "'!" & _
    Range(Address).Range("A1").Address(, , xlR1C1)
    GetData = ExecuteExcel4Macro(Data)
End Function

If its from the same workbook you would just use something like
dim NUMDAYS as double

NUMDAYS = sheets("sheet2").range("A1").value to assign to a variable which would be used later in your macro.

If VBA.DateValue(VBA.Now) - VBA.DateValue(vItem.ReceivedTime) <= NUMDAYS Then


text:
Q: Font awesome not working server hello awesome font style icon sets on the web site using the icons at the local level, but I look at, but the server does not appear when.

A: Are you declaring for UTF-8 in your document as well as in your stylesheet?
<meta charset="UTF-8">

or
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

and in stylesheet (note, must be first line, first col):
@charset "utf-8";

or
Font Awesome into your website with a single line of code. You don't even have to download or install anything!
Paste the following code into the  section of your site's HTML.
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

Most likely the actual font files are not being found. If you look in the font awesome CSS file you will probably see something like:
 @font-face {
      font-family: 'FontAwesome';
      src: url('../font/fontawesome-webfont.eot');
    }

A: Add this to your web.config:
<system.webServer>
<staticContent>
  <remove fileExtension=".svg" />
  <remove fileExtension=".eot" />
  <remove fileExtension=".woff" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
  <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
system.webServer>


text:
Q: Email verification with Strongloop loopback - verification token returned I am currently developing an API. I am using Strongloop (Loopback).
I am trying to implement email verification for when a user registers. I have a "user" model which extends the built-in "User" model.
Right now, when the user registers (POST /users), an email is sent with a link to /users/confirm with the three appropriate parameters i.e. uid, redirect and a token. When the user clicks on the link, the latter's email address is correctly verified (emailVerification field becomes true).
However, I've noticed that when making a POST request on /users, the response contains the verification token. Is this normal? Isn't the verification token be accessible only via the sent email?
Because as it is, by making a POST request on /users and getting the verification token in the response, one can easily send another request to users/confirm with the appropriate parameters (which includes the verification token) and verify the email address even if the address doesn't exist.
I am new to Strongloop and maybe I'm missing something. Can you guys help?

A: I just finished the example. See:
https://github.com/strongloop/loopback-faq-user-management

A: if you want to create user registration verification link but not use the built in user moder then you need to create verification token and then send the link.i have added the two methods.you need to use also remote method with one argument who is object type:the you need to send the parameter with register email.the method is like this....here we use the user=any variable name,modelN=model name
modelN.sendVerificationEmail = function (data, callback) {
  var user = loopback.models.modelN;

  if (!data.email) {
    return callback(commonUtils.buildError(
      'Recipient email is required.', 400, 'EMAIL_REQUIRED'
    ));
  }

  if (!emailValidator.validate(data.email)) {
    return callback(commonUtils.buildError(
      'Must provide a valid email.', 400, 'INVALID_EMAIL'
    ));
  }

  var findOneuserPromise
    = modelN.findOne({ 'where': { 'email': data.email }});

  findOneBusinessEmployeePromise.then(function (user) {
    if (!user) {
      return callback();
    }

    var sendVerificationEmailPromise
      = anothermodelname.sendVerificationEmail(user.id);

    sendVerificationEmailPromise.then(function () {
      callback();
    });

    sendVerificationEmailPromise.then(null, function (error) {
      callback(error);
    });
  });

  findOneuserPromise.then(null, function (error) {
    callback(error);
  });
};

i have add another model model method after then add this,....
anothermodelname.sendVerificationEmail = function (userid) {
  var modelN = loopback.models.modelN;
  var Email = loopback.models.Email;
  var deferred = Q.defer();
  var findByIduserPromise = modelN.findById(userId);

  findByIduserPromise.then(function (user) {
    if (!user) {
      return deferred.reject(commonUtils.buildError(
        'Unknown "modelN" id "' + userId + '".',
        404, 'MODEL_NOT_FOUND'
      ));
    }
    if (!user.verificationToken) {
      return deferred.resolve(true);
    }

    modelN.generateVerificationToken(user,
      function (verificationTokenError, verificationToken) {
        if (verificationTokenError) {
          return deferred.reject(verificationTokenError);
        }

        user.verificationToken = verificationToken;

        var saveuserPromise = user.save();

        saveuserPromise.then(function (updateduser) {
          var link = emailConf.clientBaseUrl +
            emailConf.verifyEmailRedirect + '?uid=' +
            updateduser.id + '&token=' +
            updateduser.verificationToken;
               console.log("check+link:",link);
          /*eslint camelcase: [0, {properties: "never"}]*/
          emailOptions.to = updateduser.email;
          emailOptions.template = { 'name': 'verify' };
          emailOptions.global_merge_vars = [];

          emailOptions.global_merge_vars.push({
            'name': 'USER_NAME',
            'content': updateduser.name
            || updateduser.username || updateduser.email
          });

          emailOptions.global_merge_vars.push({
            'name': 'LINK',
            'content': link
          });
          Email.send(emailOptions, function () {});

          deferred.resolve(true);
        });

        saveuserPromise.then(null, function (error) {
          deferred.reject(error);
        });
      });
  });

  findByIduserPromise.then(null, function (error) {
    deferred.reject(error);
  });

  return deferred.promise;
};

A: @user2483431, verify email exposes the email verification token in response along with user id. As you correctly pointed, it risks fooling the system. One solution is to strip off the token value from response.
Inside the afterRemote for user create, you can use,
user.verify(options, function(err, response, next2) {
  if (err) {
    // error handling code
  }
  // stripping off verificationToken from response for security
  var replacementText = "check email"
  context.result.verificationToken = replacementText;
  next();
});

Hope this helps!


text:
Q: GMSMapView myLocation not giving actual location I have a GMSMapView properly loaded and working inside my viewcontroller
what i'm not being able to do is setting the GMSCameraPosition around my location
this is my code:
mapView_.myLocationEnabled = YES;
CLLocation* myLoc = [mapView_ myLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLoc.coordinate.latitude
                                                        longitude:myLoc.coordinate.longitude
                                                             zoom:4];
[mapView_ setCamera:camera];

GPS is enabled and application has all needed permissions but myLocation returns a nil CLLocation, consequentially cameraWithLatitude:longitude:zoom: get 0 0  coordinates and displays Africa instead of my actual location (that is not in africa :) )

A: From official Google Maps iOS SDK documentation:

*

*(BOOL) myLocationEnabled [read, write, assign]
  Controls whether the My Location dot and accuracy circle is enabled.

  Defaults to NO.

*

*(CLLocation*) myLocation [read, assign]
  If My Location is enabled, reveals where the user location dot is being drawn.

  If it is disabled, or it is enabled but no location data is available, this will be nil. This property is observable using KVO.

So when you set mapView_.myLocationEnabled = YES;, it only tells the mapView to reveal the blue dot only if you have a location value given to the myLocation property. The sample code from Google shows how to observe the user location using the KVO method.(Recommended) You can also implement the CLLocationManagerDelegate method, to update the mapView.
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [mapView animateToLocation:newLocation.coordinate];
    // some code...
}

Here are the code from google maps sample code on how to use KVO to update user location.
// in viewDidLoad method...
// Listen to the myLocation property of GMSMapView.
  [mapView_ addObserver:self
             forKeyPath:@"myLocation"
                options:NSKeyValueObservingOptionNew
                context:NULL];
// Ask for My Location data after the map has already been added to the UI.
  dispatch_async(dispatch_get_main_queue(), ^{
    mapView_.myLocationEnabled = YES;
  });

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
  if (!firstLocationUpdate_) {
    // If the first location update has not yet been recieved, then jump to that
    // location.
    firstLocationUpdate_ = YES;
    CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
    mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                     zoom:14];
  }
}

A: Try to using MapKit, under the VieDidLoad or ViewWillApper using:
myMapView.showsUserLocation = YES;

You can add this simple code under the IBAction if you want, like a :
- (IBAction)getLocation:(id)sender{

         myMapView.showsUserLocation = YES;

}

I hope this help you


text:
Q: findAllByX incorrectly limited to 10 results In Spring Data Elasticsearch - I noticed something that looks like a bug with the generated findAllByFoo type methods.
These seem to be limited to the default size (of 10) - which goes against the semantics you would expect from a findAll operation.
The main findAll() operation does work correctly however and does return all documents.
So - is this a bug or is there something I'm missing?
Cheers,
Eugen.

A: It doesn't look like a bug.
According to elasticsearch's documentation (from/size) it looks like 10 is the default number of results that elasticsearch will return from a search query.
You can modify the page size with an appropriate Pageable parameter, e.g.:
Page<User> users = repository.findAll(new PageRequest(1, 20))

A: You can use ElasicsearchTemplate to search through multiple nodes and provide the number of pageRequest (or results) you want. The default is 10.
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

public List<MyElasticDocument> getData() {

    String textToSearch = "John";

    QueryBuilder query = QueryBuilders.boolQuery()
            .should(
                    QueryBuilders.queryStringQuery(textToSearch)
                            .lenient(true)
                            .field("jsonNode1")
            )
            .should(
                    QueryBuilders.queryStringQuery(textToSearch + "*")
                            .lenient(true)
                            .field("jsonNode2")
                            .field("jsonNode3")
            );

    NativeSearchQuery build = new NativeSearchQueryBuilder()
            .withQuery(query)
            .withPageable(new PageRequest(0, 20)) // provide the no. of results you want
            .build();

    List<MyElasticDocument> elasticDocumentList = elasticsearchTemplate.queryForList(build, MyElasticDocument.class)

    return elasticDocumentList;
}

A: According to https://jira.spring.io/browse/DATAES-58 it works as designed and is not subject to change. Read the comments in this issue to understand the performance background.


text:
Q: vue with vuex computed property not updating I'm using vuex and socket.io for state.Nodes.nodes update. I'm updating single node (index 4) and when I'm logging using setInterval the output_state and computed properties that is exactly the same (node 4 output_state) - they differ after mutation!
computed: {
  tmpStatus () {
    if (this.$store.state.Nodes.nodes.length !== 0) {
      return this.$store.state.Nodes.nodes[4].output_state
    } else {
      return null
    }
  }
},
created () {
  this.debugInterval = setInterval(() => {
    console.log('Devicesstate', this.$store.state.Nodes.nodes[4].output_state, this.tmpStatus)
  }, 2000)
},

The mutation is done that way:
let nodeFound = state.nodes.filter(item => item.node_id === node.node_id)[0]
let nodeIndex = state.nodes.indexOf(nodeFound)
state.nodes[nodeIndex] = node

result before update (both are the same):
Devicesstate true true
result after update - changing to false (they differ!):
Devicesstate false true
I have changed the mutation like that (importing Vue to file):
Vue.set(state.nodes, nodeIndex, node)

And it works.

A: I have changed the mutation like that (importing Vue to file):
Vue.set(state.nodes, nodeIndex, node)

And it works.


text:
Q: Disabling hyperfootnotes when using pdfx package I have a problem setting certain options of the hyperref package when also using pdfx:
The pdfx manual states that pdfx already loads the hyperref package and that therefore custom options should be set using \hypersetup{<options>}. However, there are certain options for hyperref that need to be provide at loading time. Among them is the hyperfootnotes option which I would like to set.
If I try set the option using \hypersetup I get a warning that the option was ignored ("Option `hyperfootnotes' has already been used ..."). A minimal  working example is as follows:
\documentclass{article}

\usepackage[a-1b]{pdfx}
\hypersetup{hyperfootnotes=false}

\begin{document}
Some text.\footnote{A footnote.}
\end{document}

If I instead try to pass the option by loading the hyperref package myself (\usepackage[hyperfootnotes=false]{hyperref}) after loading the pdfx package, I get an "Option clash" error message. Loading hyperref before pdfx also doesn't work.
My question is: Is there a way to tell pdfx to load hyperref with the desired hyperfootnotes option? Alternatively, is there a way to manually patch the \footnote command to not produce a hyperlink?

A: Use \PassOptionsToPackage before loading hyperref.
\documentclass{article}

\PassOptionsToPackage{hyperfootnotes=false}{hyperref}
\usepackage[a-1b]{pdfx}

\begin{document}
Some text.\footnote{A footnote.}
\end{document}


text:
Q: function is not differentiable on $\mathbb R\setminus\{0\}$ I need to prove that the given function $f$ is not differentiable on $\mathbb R \setminus\{0\}$.
$$
f(x) =  \begin{cases} x^2, \ x \in \mathbb{Q}\\
0,  \ x \in \mathbb{R}-\mathbb{Q}
\end{cases}
$$
Can anyone tell me for $c\in\mathbb R \setminus \{0\}$ my work is correct or not and also if you have any different way to this question comment them please thanks
Suppose $c\in\mathbb R \setminus \{0\}$ be arbitrary
CASE 1  $c\in\mathbb R \setminus \mathbb Q$.
Let $\varepsilon = c^2>0$
Let $δ>0$ be arbitrary
Suppose $|x-c|<δ$
If $c > 0$ choose $x'\in(c,c+\delta) \cap \mathbb R \setminus\mathbb Q$.
If $c < 0$ choose $x'\in(c-\delta,c) \cap \mathbb R \setminus\mathbb Q$.
Since $|f(x')-f(c)|=|x'^2-0^2 |=|x'^2-0^2 |>c^2=ε$.
$f$ is not continuous at $0$ hence $f$ is not differentiable at $\mathbb R \setminus\mathbb Q$.

A: Your idea is good, but the work is not complete. It's easier to do it with sequences.

The function is clearly not differentiable at any point $x$ with $x\ne0$, because we can find two sequences, $(a_n)$ in $\mathbb{Q}$ and $(b_n)$ in $\mathbb{R}\setminus\mathbb{Q}$ so that
$$
\lim_{n\to\infty}a_n=x=\lim_{n\to\infty}b_n
$$
and
$$
\lim_{n\to\infty}f(a_n)=\lim_{n\to\infty}a_n^2=x^2,
\qquad
\lim_{n\to\infty}f(b_n)=0
$$
so $f$ is not continuous at $x$. A function differentiable at $x$ is continuous at $x$.
So the only possibility is differentiability at $0$. Now
$$
\lim_{x\to0}\frac{f(x)-f(0)}{x-0}=0
$$
because, for $x\ne0$,
$$
-|x|\le \frac{f(x)}{x}\le |x|
$$
and the squeeze theorem applies.


text:
Q: ReactiveX Retry with Multiple Consumers Quick question, because I feel like I must be missing something.
I'm using rxjs here because it's what I've got in-front of me, this is a general reactiveX question, I believe.
Let's say I have a set of Observables like so:
network_request = some_thing // An observable that produces the result of a network call
event_stream = network_request.flatMapLatest(function(v) {
    return connectToThing(v) // This is another observable that needs v
}) // This uses the result of the network call to form a long-term event-based connection

So, this works ok.
Problem, though.
Sometimes the connection thing fails.
So, if I do event_stream.retry() it works great. When it fails, it redoes the network call and gets a new v to use to make a new connection.
Problem
What happens if I want two things chained off of my network_request?
Maybe I want the UI to do something every time the network call completes, like show something about v in the UI?
I can do:
shared = network_request.share() // Other implementations call this refCount
event_stream = shared.flatMapLatest(...) // same as above
ui_stream = shared.flatMapLatest(...) // Other transformation on network response

If I didn't do share then it would have made two requests, which isn't what I want, but with share, when event_stream later has an error, it doesn't retry the network request because the refcount is still at 1 (due to ui_stream), so it immediately returns completed.
What I want
This is obviously a small example I've made up to explain my confusion.
What I want is that every time the result of event_stream (that long term connection) has an error all of the following happens:

*

*the network request is made again

*the new response of that request is used to build a new connection and event_stream goes on with new events like nothing happened

*that same response is also emitted in ui_stream to lead to further processing

This doesn't feel like a complicated thing, so I must just be misunderstanding something fundamental when it comes to splitting / fanning out RX things.
Workarounds I think I could do but would like to avoid
I'm looking to export these observables, so I can't just build them again and then say "Hey, here's the new thing". I want event_stream and all the downstream processing to not know there's been a disconnection.
Same for ui_stream. It just got a new value.
I could probably work something out using a Subject as a generation counter that I ping every time I want everything to restart, and put the network_request into a flatMap based on that, so that I can break the share...
But that feels like a really hacky solution, so I feel there has to be a better way than that.
What have I fundamentally misunderstood?

A: As I've been thinking about this more I've come to the same realization as ionoy, which is that retry just disconnects and reconnects, and upstream doesn't know it was due to an error.
When I thought about what I wanted, I realized I really wanted something like a chain, and also a spectator, so I've got this for now:
network_request = some_thing
network_shadow = new Rx.Subject()

event_stream = network_request.do(network_shadow).flatMapLatest(...)
ui_stream = network_shadow.whatever

This has the property where an retry in event_stream or downstream will cause the whole thing to restart, whereas ui_stream is its own thing.
Any errors over there don't do anything, since network_shadow isn't actually a subscriber to event_stream, but it does peel the values off so long as the main event chain is running.
I feel like this isn't ideal, but it is better than what I was concerned I would have to do, which is have a restartEverything.onNext() in an doOnError, which would have been gross.
I'm going to work with this for now, and we'll see where it bites me...

A: You need to make your cold observable hot by using Publish. Read http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#HotAndCold for a great explanation.


text:
Q: Automatic uniqueidentifier during table design I've created a new table and made column id the primary key and defined it as uniqueidentifier.
Is there a way during the tables design in SQL Server Management Studio to assign a rule that all new rows auto generate a new uniqueidentifier in the id column?
At the moment to make my form (made on Retool) write to the table I need to type out a random set of characters, essentially self creating my own uniqueidentifier which obviously isn't correct.

A: Avoid the designers, they've been a complete and utter mess for 17 years. Do this in a query window:
USE tempdb;
GO

CREATE TABLE dbo.what
(
  id uniqueidentifier NOT NULL
      CONSTRAINT DF_what_id DEFAULT(NEWSEQUENTIALID()),
      -- or NEWID() if you like page splits
  name nvarchar(128),
  CONSTRAINT PK_what PRIMARY KEY (id)
);

INSERT dbo.what(name) VALUES(N'hi'),(N'there');

SELECT id, name FROM dbo.what;

Output (yours will have different values for id):

id
name

84c37c76-8c0e-ed11-ba5d-00163ef319ff
hi

85c37c76-8c0e-ed11-ba5d-00163ef319ff
there


text:
Q: how to launch resident vid player from mobile site im trying to launch the resident vid player in a phone from a url on a mobile site
and having a tough time doing this
there are lots of complexities
1) the vids are on amazons cloudfront
2) they are signed and streaming
3) i want to write one codebase and have it work for both iOS and android
so ive got the signed and streaming bit to work on the normal desktop site
and using flowplayer
in order to keep to the one codebase idea
im using html5/jquery mobile
so whats the html5 that will launch the vid player for both platforms
is there even such a thing
thanks so much for your help

A: Checkout jw player http://www.longtailvideo.com


text:
Q: No Tonelli or Fubini Whenever we can interchange summation (perhaps due to Tonelli-Fubini), good things happen. Otherwise, one has to struggle evaluating double sums in just one way, because the alternative results in a divergent series. Having said that, I'm currently interested in the following:

Have you encountered in your own research or do you recall from someone's research paper "interesting" double sums that are convergent where reversing order of summation does not work? Please provide references.

A: At L. Spice's suggestion, I hereby reify (!) my comment "Fourier inversion on the real line? Too mundane?" :)
But while we're here, I'd want to remark that to my mind much modern analysis (e.g., post-Schwartz, post-Grothendieck, et al) amounts to reconsideration of seemingly illegitimate symbol manipulation that mysteriously gives reliable answers (e.g., in Heaviside's work in the 1890's and thereafter, in Dirac's physics beginning c. 1928, H. Bethe's and others' work in the early 1930s).
In that context, one might argue that the ground-breaking work of the Italian, German, and French analysts in the late 19th and early 20th century was wonderful, but did not go far enough. In particular, although (as I've ranted elsewhere or other occasions) the precisification of the notion of "function" in set-theoretic terms was an excellent thing, it was/is arguably too restrictive (witnessed already by the "almost everywhere" kludge/revelation in Lebesgue-et-al theory).
In particular, although Fubini-Tonelli's theorem can fail due to "pointwise" problems, if sufficiently recast about not-literal integrals but continuous functionals, it can be designed-to-succeed in many situations where pointwise failure is irrelevant. Thus, in many practical situations, a "literal failure"'s incorrect conclusions can sometimes be salvaged by not being sucked down into the miasma of (irrelevant) pointwise issues.
To my mind, an archetype for this is Clairault's theorem on the interchangeability of partial derivatives ... under some conditions. Naturally, at the time, and still nowadays for many, this is a pointwise issue. However, taking Fourier transforms, we find that distributionally the derivatives are always interchangeable.
Back to the immediate question: another number-theoretic example (which I included as a prank-question in my old book on Hilbert modular forms) is about the "inner product" (which it cannot literally be...) of a holomorphic Poincare series and a holomorphic Eisenstein series. The seeming paradox is that if we unwind the Eisenstein series, we (correctly) compute the zeroth Fourier coef of the Poincare series, which is (in the holomorphic case only!) $0$. But, if we unwind the Poincare series (which is not ok... ) we seem to compute a higher Fourier coefficient of the Eisenstein series, thus, seeming to show that Eisenstein series are constants. The fallacy is that the Poincare series cannot be unwound here because there was cancellation in the summing of it: when unwound, Fubini-Tonelli does not apply, and, indeed, the seeming conclusion is incorrect.
The non-frivolousness of that example resides in a standard procedure in analytic number theory (and in automorphic extensions of the classical versions thereof) where both Eisenstein series and Poincare series are extended by a sort of Hecke-summation device to depend on a complex parameter $s$, and wherein a fairly arbitrary thing is "wound up" to make an automorphic form, and then spectrally decomposed, etc. It is common practice to simply ignore convergence issues in such spectral expansions, with a few exceptions. And, indeed, even in the tiniest cases, $L^2$ convergence is some distance from pointwise, but the discussion is all too often pointwise.
Another archetype is the spectral decomposition of pseudo-Eisenstein series (in various contexts) in terms of genuine Eisenstein series. This decomposition in the simplest cases is derived from ordinary Fourier inversion applied to test-function data for a pseudo-Eisenstein series, with the idea to wind up this expression to an integral of Eisenstein series. The obstacle is convergence. Thus, the Fourier-Mellin inversion path is moved sufficiently far to the right to legitimize the winding up (by Fubini-Tonelli, for example), and then the path is moved back to the critical line. The small surprise, which may seem innocuous in the simplest cases, is that residues of the Eis appear. For $SL(2,\mathbb Z)$, the residues are essentially constants, which may be misleading. Namely, for higher-rank groups (e.g., $SL(4)$ or $Sp(4)$, the residues are highly-nontrivial automorphic forms (Speh forms).
(The previous are arguably even-simpler issues than difficulties in evaluating traces in the obvious fashion.)

A: Would you accept a trace-integral as a double sum?  The distribution character of a representation $\pi$ (of a, let's say semisimple, $p$-adic group $G$, although I think that most of what I say here is also true for real Lie groups) is given by
$$
\operatorname{tr} \pi(f) = \operatorname{tr} \int_G \pi(g)f(g)\mathrm dg.
$$
One would very much like to say, as in the case of $G$ compact, that
$$
\operatorname{tr} \pi(f) = \int_G (\operatorname{tr} \pi(g))f(g)\mathrm dg.
$$
This is not possible for $\pi$ infinite-dimensional unitary, but it is a very deep result of Harish-Chandra that there is a locally integrable function $\Theta_\pi$ with various nice properties (for example, it is locally constant on the regular semisimple locus) so that
$$
\operatorname{tr} \pi(f) = \int_G \Theta_\pi(g)f(g)\mathrm dg.
$$
The computation of this function $\Theta_\pi$ is, due to its indirect definition, quite difficult.  My own research is largely concerned with the case where $\pi$ is an irreducibly compactly induced representation $\pi = \operatorname{Ind}_K^G \rho$, in which case more work of Harish-Chandra shows that
$$
\Theta_\pi(\gamma) = \int_G \int_K \dot\theta_\rho(g k\gamma k^{-1}g^{-1})\mathrm dk\,\mathrm dg.
$$
(The inner integral over a compact open subgroup $K$ also comes, if one digs into the details of the proof, from the failure of a double integral to be 'switchable'.)
I believe that the (non-compact case of) the trace formula can also be viewed as a lengthy and difficult matter of dealing with the failure of Fubini, but I couldn't talk in any intelligible fashion about this (and could well be wrong).  Perhaps, if I'm not completely off, someone else could discuss it.

A: Since there's a "number theory" tag, I suggest the quasimodular form
$E_2(\tau)$, defined for $\tau$ in the upper half-plane as a multiple of
$\sum_{m\in\bf Z} {\sum_{n\in\bf Z}}' (m\tau+n)^{-2}$
where the $\prime$ indicates omission of the term $(m,n)=(0,0)$.
For even $k>2$, the corresponding sum
$\sum_{m\in\bf Z} {\sum_{n\in\bf Z}}' (m\tau+n)^{-k}$
converges absolutely and yields modularity of $E_k$.
But for $k=2$, switching the sums yields $\tau^{-2} E_2(1/\tau)$,
which is not the same thing as $E_2(\tau)$!  (But you can still recover the
formula for the difference by carefully keeping track of how
switching $\sum_m$ and $\sum_n$ changes the sum).

A: Alice and Bob play a game in which each flips a fair coin repeatedly until it turns up tails, earning a score equal to the number of times it turns up heads.  (Thus if Alice flips $HHHT$, her score is $3$.)  The high scorer wins, and collects a prize of $4^n$ from the loser, where $n$ is the loser's score.
Let $P(a,b)$ be Alice's payoff when she and Bob earn scores of $a$ and $b$.  Then Alice's expected payoff is
$$\sum_{b=0}^\infty{1\over 2^{b+1}}\sum_{a=0}^\infty {1\over 2^{a+1}}P(a,b)=1/2>0$$
so that Alice, if she's an expected-value maximizer, should certainly agree to play this game.
On the other hand, her expected payoff is also
$$\sum_{a=0}^\infty{1\over 2^{a+1}}\sum_{b=0}^\infty {1\over 2^{b+1}}P(a,b)=-1/2<0$$
so she should certainly refuse to play.
Some further words on the matter (including a reference to a MathOverflow post!) can be found here.


text:
Q: Ошибка Fragment does not have a view по нажатию кнопки Есть Fragment содержащий кнопку, по нажатию на которую вызывается DialogFragment. Он в свою очередь содержит два фрагмента и требуется реализовать ViewPager позволяющий перелистывать эти два фрагмента в диалоге.
После нажатия на кнопку, возвращается ошибка в дебаг режиме
java.lang.IllegalStateException: Fragment does not have a view

Полный стек трейс:
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime: Process: com.rmr.ngusarov.criminalintent, PID: 12467
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime: java.lang.IllegalStateException: Fragment does not have a view
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.Fragment$1.onFindViewById(Fragment.java:2181)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:963)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.BackStackRecord.run(BackStackRecord.java:793)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:562)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.support.v13.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:149)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.View.measure(View.java:18788)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1191)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:606)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-29 22:56:31.469 12467-12467/com.rmr.ngusarov.criminalintent E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Собственно сами классы
1) DialogFragment
package com.rmr.ngusarov.criminalintent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

import java.util.Calendar;
import java.util.Date;

public class DateAndTimePickerDialogFragment extends DialogFragment {

    public static final String EXTRA_DATE = "com.rmr.ngusarov.criminalintent.date";
    public static final int NUM_ITEMS = 2;

    private ViewPager mViewPageFragment;
    private Date mDate;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDate = (Date) getArguments().getSerializable(EXTRA_DATE);

        mViewPageFragment = new ViewPager(getActivity());
        mViewPageFragment.setId(R.id.viewPagerInFragment);

        FragmentManager fm = getChildFragmentManager();
        mViewPageFragment.setAdapter(new MyDateManager(fm));

        return new AlertDialog.Builder(getActivity())
                                    .setView(mViewPageFragment)
                                    .setTitle(R.string.date_picker_title)
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            sendResult(Activity.RESULT_OK);
                                        }
                                    })
                                    .create();
    }

    private void sendResult(int resultCode) {
        if (getTargetFragment() == null)
            return;
        Intent i = new Intent();
        i.putExtra(EXTRA_DATE, mDate);

        getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);
    }

    public static DateAndTimePickerDialogFragment newInstance(Date date) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_DATE, date);
        DateAndTimePickerDialogFragment fragment = new DateAndTimePickerDialogFragment();
        fragment.setArguments(args);

        return fragment;
    }

    class MyDateManager extends FragmentPagerAdapter {
        public MyDateManager(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(mDate);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            Log.d(CrimeListFragment.TAG, "get item num = " + position);
            switch (position) {
                case 0:

                    return DatePickFragment.newInstance(year, month, day);
                case 1:
                    return TimePickFragment.newInstance(hour, minute);
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }
    }
}

2) Fragment содержащийся в DialogFragment
package com.rmr.ngusarov.criminalintent;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import java.util.Date;
import java.util.GregorianCalendar;

public class DatePickFragment extends Fragment{
    public static final String DATE_YEAR_KEY = "date_year";
    public static final String DATE_MONTH_KEY = "date_month";
    public static final String DATE_DAY_KEY = "date_day";

    private int year;
    private int month;
    private int day;
    private Date mDate;
    public View datePick;
    public DatePicker mDatePicker;

    public static DatePickFragment newInstance(int year, int month, int day) {
        DatePickFragment datePickFragment = new DatePickFragment();
        Bundle args = new Bundle();
        args.putInt(DATE_YEAR_KEY, year);
        args.putInt(DATE_MONTH_KEY, month);
        args.putInt(DATE_DAY_KEY, day);
        datePickFragment.setArguments(args);
        Log.d(CrimeListFragment.TAG, "new instance for new DP = OK!");
        return datePickFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(CrimeListFragment.TAG, "onCreate start DP = OK!");
        super.onCreate(savedInstanceState);
        year = getArguments().getInt(DATE_YEAR_KEY);
        month = getArguments().getInt(DATE_MONTH_KEY);
        day = getArguments().getInt(DATE_DAY_KEY);
        Log.d(CrimeListFragment.TAG, "onCreate DP = OK! day = " + day);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(CrimeListFragment.TAG, "before init view  DP = OK!");
        mDatePicker = (DatePicker) datePick.findViewById(R.id.dialog_date_datePiker);
        datePick = inflater.inflate(R.layout.dialog_date, null);

        Log.d(CrimeListFragment.TAG, "after init view  DP = OK!");

        Log.d(CrimeListFragment.TAG, "before init DP = OK!");
        mDatePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mDate = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime();
                getArguments().putSerializable(DateAndTimePickerDialogFragment.EXTRA_DATE, mDate);
            }
        });
        Log.d(CrimeListFragment.TAG, "after init DP = OK!");

        return datePick;
    }
}

3) Класс второго фрагмента аналогичен предыдущему по сему не вижу смысла выкладывать.
Подскажите, пожалуйста, в чем может быть проблема или какой информации стоит добавить для увеличения вероятности помощи?

A: Измени местами строки с:
mDatePicker = (DatePicker)datePick.findViewById(R.id.dialog_date_datePiker);
datePick = inflater.inflate(R.layout.dialog_date, null);

на :
datePick = inflater.inflate(R.layout.dialog_date, null);
mDatePicker = (DatePicker)datePick.findViewById(R.id.dialog_date_datePiker);

A: Здесь вся беда состоит в том, что, когда создаётся дочерний FragmentManager, ему обязательно нужно, чтобы у родительского фрагмента был вид. А поскольку DateAndTimePickerDialogFragment использует onCreateDialog, никакого вида в onCreateView он не создаёт, и в итоге и получается проблема.
Решения тут я вижу два: можно либо создавать диалог через onCreateView, либо реализовать PagerAdapter вручную и не использовать фрагменты внутри диалога. Лично мне второй вариант кажется более предпочтительным, потому что в первом придётся все кнопки и стили делать самостоятельно, что довольно непросто.