Q: Implementing additional constraints in R's nnls I am using the R interface to the Lawson-Hanson NNLS implementation of an algorithm for non-negative linear least squares that solves ||A x - b||^2 with the constraint that all elements of vector x ≥ 0. This works fine but I would like to add further constrains. Of interest to me are:

*

*Also minimize "energy" of x:
||A x - b||^2 + m*||x||^2

*Minimize "energy in the x derivative"
||A x - b||^2 + m ||H x||^2, where H is the sum of identity and a matrix with -1 on the first off-diagonal

*Most generally, minimize ||A x - b||^2 + m ||H x - f||^2.
Is there are a way to coax nnls to do this by some clever way of restating the problems 1.-3. Above? The reason I have hope for such a thing is that there is a little-throw away comment in a paper by Whitall et al (sorry for the paywall) that claims that "fortunately, NNLS can be adopted from the original form above to accommodate something in problem 3".

A: I take it m is a scalar, right? Consider the simple case m=1; you can generalize for other values of m by letting H* = sqrt(m) H   and f* = sqrt(m) f    and using the solution method given here.
So now you're trying to minimise ||A x - b||^2 + ||H x - f||^2.
Let A* = [A' | H']'   and let b* = [b' | f']'  (i.e. stack up A on top of H and b on top of f) and solve the original problem of
non-negative linear least squares on ||A* x - b*||^2 with the constraint that all elements of vector x ≥ 0 .


Q: Resources for PhD students to guide through the research I am living in a poor country but I have managed to get admission for a PhD program in Western Europe. This was a daunting task for me due to my family background and also social conditions. ( I don't feel like elaborating on this) . Also , I never had much guidance in mathematics and motivation was intristic. What motivated me was that I always liked studying mathematics and wanted to study it more, try problems and work on some problem and do research. I am working on an area of Pure mathematics.

Can you please share with me resources ( books/ blogs/ websites/ videos) about what I should need to know and what will definitely help me to do good research in mathematics ( for PhD and beyond)?

There might be no best answer for this but it will be best for me ( and hopefully future visitors, there might be more people like me with less guidance and fortune) as many resources are mentioned in comments and answers.
I shall be thankful for any guidance/advice received.
Thank you!


Q: How to solve error: you have uncommitted work pending. please commit or rollback before calling out I am receiving this error: you have uncommitted work pending. please commit or rollback before calling out. What do I need to change in below code to resolve this? The error is on bold line in code below.  Thank you!
Here's what I need to do in my code:1) when a lead is inserted, make a post request using the static resource 'EmedCalloutBody' as the body of the request. 2) If successful, that initial request returns a Request Id. 3) i can ONLY make that initial request once, or it can mess up the api endpoint queue- this is the part that is getting me stuck. 4) I need to take that request id and then use it to make a 2nd post request (then that will return json, which i will parse out, but have not done yet in the posted code). I need to keep on posting the 2nd request until I receive a response. I've seen some other posts but don't get how to apply them to my use-case scenario.
In the code below, I make the initial request and assign the returned requestId to a field, and make the update to the lead (last line of the class) on the Lead record as well as to a static string in the code. It's causing this error message you have uncommitted work pending. please commit or rollback before calling out.
TRIGGER
trigger  ReferralCreateContact on Lead (after insert, after update) {

     List<string> leadIds = new List<string>();
    for (lead ref : trigger.new){
        if (ref.Epaces_Checked__c != true && (ref.Emed_Request_Id__c == null || ref.Emed_Request_Id__c == '')){
          lead newl = new lead();
          newl.Id = ref.id;
          leadIds.add(newl.id);
         EMedCalloutsExtension.makePostCallout1(leadIds);
      }
    }

CLASS
public class EMedCalloutsExtension {
    static string EmedrequestId;

     @future(callout = true)
       public static void  makePostCallout1(list<id> refIds) {
   List <Lead> refs =[Select Id, firstname, lastname, gender__c, patient_dob__c, patient_ssn__c, Epaces_Checked__c, Emed_Request_Id__c from Lead where Id in :refIds];
     List<lead> reftoupdate = new list<lead>();
           for (lead ref : refs){

 string reqbody;
     StaticResource r =[Select Id,Body from StaticResource where Name='EMedCalloutBody' limit 1];
      reqBody=r.body.toString();
       HttpRequest req = new HttpRequest();
           req.setHeader('Content-Type', 'application/json');
                req.setMethod('POST');
                req.setBody(reqBody);
                req.setEndpoint('callout:Emed');
                req.setTimeout(2 * 60 * 1000);
                    system.debug('ENDPOINT: ' + req.getendpoint());
                       system.debug('BODY: '+ req.getBody());
         Http http = new Http();
           HttpResponse response = http.send(req);
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            system.debug(response.getstatuscode());
           System.debug(response.getBody());
             string requestId = response.getbody().substringAfter('"request_id": ').substringBefore(',');
            EmedrequestId = requestId;
            if (ref.Emed_Request_Id__c == null || ref.Emed_Request_Id__c == ''){
            ref.Emed_Request_Id__c = requestId;
                reftoupdate.add(ref); }

        }

               if (ref.Emed_Request_Id__c != null){
                   EmedrequestId = ref.Emed_Request_Id__c;

              string reqbodyResp;
              StaticResource r2 =[Select Id,Body from StaticResource where Name='EmedResponseBody' limit 1];
               reqbodyResp=r2.body.toString();
              reqbodyResp=reqbodyResp.replace('{{requestId}}', EmedrequestId);

                  HttpRequest req2 = new HttpRequest();
           req2.setHeader('Content-Type', 'application/json');
                req2.setMethod('POST');
                req2.setBody(reqbodyResp);
                req2.setEndpoint('callout:Emed_Response');
                req2.setTimeout(2 * 60 * 1000);
            system.debug('ENDPOINT2: ' + req2.getendpoint());
            system.debug('BODY2: '+ req2.getBody());
             Http http2 = new Http();
           HttpResponse response2 = http2.send(req2);

        if (response2.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response2.getStatusCode() + ' ' + response2.getStatus());
        } else {
            system.debug(response2.getstatuscode());
           System.debug(response2.getBody());

        }

               }

                      }
           if (!reftoupdate.isempty()){
               update reftoupdate; }
           return;
       }


Q: Zynaddsubfx fails to initialize with error message "Default I/O did not initialize." I am tying to use zynaddsubfx with qjackctl and MIDI. I have it connected, and the configurations are set. This is what I see when I open zynaddsubfx:

Default I/O did not initialize. Defaulting to NULL backend.

What does this mean and how do I fix this?

A: I got this problem fixed by working with jack. Once I got jackctl set up, the problem disappeared. One of the biggest helps I found with qjackctl is this one here Ubuntu wiki How to JACK Configuration.
I think this had to do with the Frames/Period. Basically this is the buffer for qjackctl as explained on the wiki. Working with the settings on this and a few other settings helped tremendously.

A: I can't comment due to low rep.
I had the exact same message "zynaddsubfx default io did not initialize defaulting to NULL backend." right after before installing Qjackctl, when executing zynaddsubfx. So it is not neccesary to have qjackctl installed to have the bug. But there is a "jack" thing that controls midi that probably is that what you are talking about (sorry for being imprecise, midi in linux is difficult)

A: Ubuntu 20.04
I tried a bunch of random things from the web on my Ubuntu 20.04 ZynAddSubFX 3.0.5, one of them worked and I get sounds out of the virtual keyboard, I'm just not sure which:

*

*run as:
zynaddsubfx -O alsa -I alsa

Without -O alsa, I don't get any sounds still, so that option at least is crucial.

*sudo apt install qjackctl
sudo usermod -a -G audio $USER

and log out and log in.
After taking those actions, the error message does not show up anymore even without -O alsa -I alsa. But I get no sound without -O alsa.

A: The message "default I/O did not initialize" is about default audio hardware initialization. It happens in three major cases:

*

*device absent

*access to device blocked

*device capabilities limited

You should check system current default audio hardware by
cat /proc/asound/cards

The first list item is your system default (if any). You can set default device manually in /etc/asound.conf:
defaults.pcm.card 1
defaults.ctl.card 1

Corresponding to list item number discussed upper.
In my case it was enough to disconnect usb midi-keyboard and restart alsa. Because somehow midi-keyboard became default audio.


Q: Terraform and Jenkins Guys I want to automate terraform with Jenkins pipeline
And My terraform is installed on different Vm and Jenkins
Also.
I know there is the Terraform Plugin. But it seems like The Terraform
Has to be installed on the same vm as Jenkins(or on /var/lib/jenkins/workspace)
Is there anyway to get this done?
Please share your suggestions.

A: Yes, the fastest way to have it done is use master/slave setup for you jenkins. So, what you need to do is to add slave to the machine on which your terraform is running.

A: Generally, it's a good idea to keep your Jenkins machine as clean as possible, therefore you should avoid installing extra packages on it like Terraform. A better approach for this problem would be creating a Dockerfile with your Terraform binary and all the plugins that you need already built-in, then all you need to do in your Jenkins pipeline is build and execute your Terraform docker.
This is an example of such Dockerfile:
FROM hashicorp/terraform:0.11.7
RUN apk add --no-cache bash python3 && \
    pip3 install --no-cache-dir awscli

RUN mkdir -p /plugins

# AWS provider
ENV AWS_VERSION=1.16.0
ENV AWS_SHA256SUM=1150a4095f18d02258d1d52e176b0d291274dee3b3f5511a9bc265a0ef65a948

RUN wget https://releases.hashicorp.com/terraform-provider-aws/${AWS_VERSION}/terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip && \
    echo "${AWS_SHA256SUM}  terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip" | sha256sum -c - && \
    unzip *.zip && \
    rm -f *.zip && \
    mv -v terraform-provider-aws_* /plugins/

COPY . /app
WORKDIR /app
ENTRYPOINT []

The Terraform documentation also contains a section on best practices running Terraform in CI:
https://www.terraform.io/guides/running-terraform-in-automation.html

A: I have created a Global Shared Library awesome-jenkins-utils with which you can use different version of terraform simultaneously in same pipeline. Additionally you can easily map build parameters to terraform variables


Q: nginx service is not starting (error = (code=exited, status=150)) i make a service and trying to start it ,but showing following error.my nginx is in active status.
error = (code=exited, status=150)
i had tried-reinstall the nignx and recreate the service.
detailed error is given below.
root@amit-OptiPlex-3050:/# sudo systemctl enable CoreApplication.service
root@amit-OptiPlex-3050:/# sudo systemctl start CoreApplication.service
root@amit-OptiPlex-3050:/# sudo systemctl status CoreApplication.service
● CoreApplication.service - CoreApplication .NET Core App
   Loaded: loaded (/etc/systemd/system/CoreApplication.service; enabled; vendor
   Active: activating (auto-restart) (Result: exit-code) since Thu 2019-01-03 18
  Process: 15432 ExecStart=/usr/bin/dotnet /var/newwebapps/CoreApplication/CoreA
 Main PID: 15432 (code=exited, status=150)
lines 1-5/5 (END)...skipping...
● CoreApplication.service - CoreApplication .NET Core App
   Loaded: loaded (/etc/systemd/system/CoreApplication.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Thu 2019-01-03 18:13:31 IST; 1s ago
  Process: 15432 ExecStart=/usr/bin/dotnet /var/newwebapps/CoreApplication/CoreApplication.dll ***(code=exited, status=150)***
 Main PID: 15432 (code=exited, status=150)

A: I encountered similar error and I ran the command in the service file:
/usr/bin/dotnet /path/to/dotnetcore.dll
The result was:
The specified framework 'Microsoft.AspNetCore.App', version '2.2.6' was not found.
Probably you are missing the correct framework.


Q: Local uniform convergence of integrals involving determinants Assume that $J=J\big(x_1,x_2\big)$ is a locally bounded function from $\mathbb R^2\to \mathbb R$ and $J_n=J_n\big(x_1,x_2\big)$ is a sequence of functions from $\mathbb R^2\to \mathbb R$ that locally uniformly converges to $J$.
Fix $B$ a bounded subsets of $\mathbb R^2$ and $\ell\in\mathbb N$. I want to show that the following convergence holds
\begin{equation}\label{eq:conv_goal}
  \int_{B^\ell} \det\left(\left[J_n\big(x_i,x_j\big)\right]_{1\leq i,j \leq \ell}\right)
  dx_1\dots dx_\ell
  \to
  \int_{B^\ell} \det\left(\left[J\big(x_i,x_j\big)\right]_{1\leq i,j \leq \ell}\right)
  dx_1\dots dx_\ell.
 \end{equation}
We start by fixing $\bar x\in B^\ell$.
Since by assumption $J_n$ locally uniformly converges to $J$ and $J$ is locally bounded, there exists a neighborhood $U_{\bar x}$ of $\bar x$ such that for all $n\in\mathbb N$,
\begin{equation}\label{eq:dom}
  \det\left(\left[J_n\big(x_i,x_j\big)\right]_{1\leq i,j \leq \ell}\right)\leq \prod_{j=1}^\ell \Big(\sum_{i=1}^\ell J_n\big(x_i,x_j)^2\Big)^{1/2}\leq C,  \quad\forall (x_i)_{1\leq i\leq \ell}\in U_{\bar x},
 \end{equation}
where in the first inequality we used Hadamard's inequality.
Now note that since $J_n$ locally uniformly converges to $J$, then for every fixed $(x_i)_{1\leq i\leq \ell}\in B^\ell$,
\begin{equation*}
  \det\left(\left[J_n\big(x_i,x_j\big)\right]_{1\leq i,j \leq \ell}\right)
  \to \det\left(\left[J\big(x_i,x_j\big)\right]_{1\leq i,j \leq \ell}\right)
 \end{equation*}
Now I want to use dominated convergence to conclude but my dominations holds only locally. Any help to conclude the proof?


Q: Einstein–Brillouin–Keller quantization rule, what does it really mean? The Einstein–Brillouin–Keller method is a quantization rule going from classical mechanics to quantum mechanics, according to wikipedia:

I have several question regarding the above description:

*

*what does it mean that a pair $(q_i, p_i)$ describes a closed function or a periodic function in $q_i$.

*what does $\mu_i$ and $b_i$ really mean, how to determine them in different systems.
I hope the answer can be as detailed as possible, better still, explain using different (elementary) examples, for example harmonic oscillator, particle in magnetic field, etc, to illustrate all the basic points of the above formula and question.


Q: Padrão de Projeto Observer no Android Alguém teria como me mostrar uma estrutura Observer dentro do android?
Estava tentando montar uma igual a do java, porém não tive sucesso.
Meu teste foi feito da seguinte forma:

*

*Criei uma class Banco e uma class ClienteObservable;

*No banco eu tenho os métodos de notificação, e de adicionarObserver (que eu passo a bola pro clienteObservable);

*Na class ClienteObservable eu tenho o método update, que vai realizar um ação ao ser notificado.

Essa é a lógica que tenho sobre Padrão de Projeto Observer, porém não sei como estruturar isso no android, alguém poderia desenvolver algo bem básico para me mostrar?
Segue abaixo o Código:
Na Class Banco

Na Class clienteObservable

A: Acredito que seja igual o java.
public class Cliente {
}
public interface ClienteObservable {
    public void update();
}
public class Banco {
    private List<ClienteObservable> observables = new ArrayList<ClienteObservable>();
    public void adicionarObserver(ClienteObservable obs){
       this.observables.add(obs);
    }
}

Mas existe um erro conceitual aqui. Na verdade deveria ser assim:
public interface ClienteObserver {
    public void update(Cliente cliente);
}
public class Banco implements ClienteObserver {
    @Override
    public void update(Cliente cliente) {
        //faz algum calculo para o cliente  ..
    }
}
public class Cliente {
    private String nome;
    private List<ClienteObserver> observers = new ArrayList<ClienteObserver>();

    public void adicionarObserver(ClienteObserver obs) {
        this.observers.add(obs);
    }
    public void setNome(String nome) {
        this.nome = nome;
        this.notifyObservers();
    }
    private void notifyObservers() {
        for (ClienteObserver observer : this.observers) {
            observer.update(this);
        }
    }
}

Pois quem você esta observando é o objeto Cliente.
Quando ele atualizar seu estado deve comunicar os observadores sobre esta modificação.


Q: Git workflow for different versions of a framework We have the following setup: Three apps which are similar to each other with the common code extracted into a framework. Each app is managed in their own git repository and includes the framework as a git submodule.
The problem is that the apps are now developed in parallel with new features being added to the framework that other apps don't need to support right away. Currently we have different branches of the framework for all apps. One app uses the master branch of the framework because most of the time new features were first introduced in this app.
Framework branches

*

*master (used by App A)

*appB

*appC

When a new feature is introduced in appB that needed changes in the framework these changes were made to branch appB. If these changes were later needed in App A, branch appB was merged into master. This means that all changes in appB had to be merged into master.
This system worked but had some flaws

*

*merging a feature from one branch to another meant we had to merge all the changes

*easy to loose track what had been merged already or what is going to be merged when merging one branch into another

*Marking breaking changes was done using commit messages, which made the last point even more important

We are currently searching for a new workflow. I was think about having the following branches

*

*master

*appA

*appB

*appC

So for each app one branch and a master branch that includes all the changes. When new features are developed a feature branch should be created and then applied to master as well as to all app branches the feature is needed right away. Other apps can merge the feature branch when they need the feature later on.
I see the following problems with this

*

*How can I merge a feature branch onto multiple branches and only merge the changes that happened in the branch. I know of "git rebase onto ..." but I am not quite sure if I can use this command multiple times.

*Should I use git cherry-pick for merging features into multiple branches? I would rather not do this, because I can think that this will be error prone when not selecting all changes that were made in a feature branch

*How to keep track of which feature(branch) had been applied to which app. Can I use branch --no-merge or will that only work if the branches have the same ancestor?

Is my purposed way the best way to accomplish this or should I rethink my strategy completely?

A: As explain in "Git & Working on multiple branches", the two practical solutions when applying commits to multiple branches (which is what you would do with your "feature branches" option) are:

*

*merge (which should allow you to keep reusing that feature branch, as it would keep track of what has already been merge to a specific banch): a rebase --interactive might be in order for you to re-order the commits, putting first the ones you want to merge, and then the ones you are nnot ready yet to merge.

*cherry-picking (and it now supports a range of commits), but I always have been wary of cherry-picking.


Q: Is Stream.findAny a short-circuit operation? Consider this code
Object found = collection.stream()
    .filter( s -> myPredicate1(s))
    .filter( s -> myPredicate2(s))
    .findAny()

Will it process entire stream, and call both myPredicate1 and myPredicate2 for all elements of the collection? Or will as many predicates be called as are needed to actually find the value?

A: Yes it is, as the Stream.findAny() documentation states:

This is a short-circuiting terminal operation.

It's a common misconception that objects in stream are "pushed" towards consuming operation. It's actually the other way around - the consuming operation pulls each element.
For sequential streams only as many predicates will be called as are needed to find matching value.
Parallel streams may execute more predicates, but will also stop execution as soon as an element is found.
public class StreamFilterLazyTest {

  static int stI = 0;

  static class T {

    public T() {
      super();
      this.i = ++stI;
    }

    int i;

    int getI() {
      System.err.println("getI: "+i);
      return i;
    }
  }

  public static void main(String[] args) {
    T[] arr = {new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T()};
    Optional<T> found = Arrays.stream(arr).filter(t -> t.getI() == 3).findAny();
    System.out.println("Found: "+found.get().getI());
  }
}

will print:
getI: 1
getI: 2
getI: 3
Found: 3

A: The javadoc for findAny() states:

"This is a short-circuiting terminal operation."
"The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations ..."

This means that findAny() on a sequential stream will only "pull" enough elements to find the first one.  On a parallel stream, it could pull more than enough, depending on the implementation.
The package javadoc also states:

"Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed."

This means that the filter() predicates only occur when the findAny() terminal pulls them.
In short:

Q: Is filter + findAny still a short-circuit operation?

A: Yes.

A: Well it does not matter if sequential or parallel streams are used, they are still going to traverse as many elements as are required to find the first that matches. It might be different if you use findFirst and you have a Stream made of an ordered collection.
findFirst in this case has to preserver the order.
In this case, due to parallelism, the second, then third elements might be processed before the first, but still only the first will be returned.

A: Stream#findAny is a short-circuiting terminal operation. it will visit Predicates to matching & short-circuited one by one since Stream#filter return a new stream each time.

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

As @Holger mentioned in comment that it can makes filters be short-circuited as below:
if(predicate1.test(value) && predicate2.test(value)){
 ....
}

Test
Iterator<Predicate<Integer>> predicates = Stream.<Predicate<Integer>>of(
        it -> false,
        it -> {
            throw new AssertionError("Can't be short-circuited!");
        }
).iterator();

Predicate<Integer> expectsToBeShortCircuited = it -> predicates.next().test(it);

Stream.of(1).filter(expectsToBeShortCircuited).filter(expectsToBeShortCircuited)
      //                                       |
      //                                       |
      //                      here is short-circuited since the stream is empty now
      .findAny();

A: You can use peek to verify this

== Sequential ==
Alpha1 Alpha2 Beta1 Beta2 Gamma1 Gamma2 Dolphin1 Fargo1 Fargo2  Found:
  Fargo Applications: 9
== Parallel ==
  Arnold1 Jim1 Loke1 Alpha1 Mustard1 Lenny1 Mustard2 Mark1 Alpha2 Mark2
  Beta1 Beta2 Gamma1 Fargo1 Gamma2 Dolphin1 Fargo2  Found: Fargo
  Applications: 17

YMMV depending on number of cores etc.
Produced by below
package test.test;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class Snippet {

    static AtomicInteger predicateApplications;

    public static void main(String arr[]) {
        System.out.println("== Sequential == \n");
        sequential();
        System.out.println(" == Parallel == \n");
        parallel();
    }

    private static void sequential() {
        Stream<String> stream = Stream.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark",
                "Jim", "Arnold", "Loke");
        execute(stream);
    }

    private static void parallel() {
        Stream<String> parallelStream = Stream
                .of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke")
                .parallel();
        execute(parallelStream);
    }

    private static void execute(Stream<String> stream) {
        predicateApplications = new AtomicInteger(0);

        Optional<String> findAny = stream.peek(s -> print(s + "1")).filter(s -> s.contains("a"))
                .peek(s -> print(s + "2")).filter(s -> s.startsWith("F")).findAny();

        String found = findAny.orElse("NONE");
        System.out.println("\nFound: " + found);
        System.out.println("Applications: " + predicateApplications.get());
    }

    private static void print(String s) {
        System.out.print(s + " ");
        predicateApplications.incrementAndGet();
    }

}


Q: Dynamic setting the timestamp fields in superset dashboards I'm building few dashboards in Apache superset. All my available timestamp fields are in UTC timezone. (for example fields are, class_start_time & class_end_time).
I want that in the timezone the dashboard is opened all the timestamp fields will be automatically converted.
For example, I'm opening dashboard in Norway , so the UTC data should be converted to CET timezone of Norway.
I have tried to add some value here in Hours offset but its not working.
Can you please guide how we can achieve this.?
Just for reference :
In Kibana dashboards (ELK stack) have feature to automatically convert the timezone into which it is being opened. So I need same thing in Superset.

A: Normally you would be able to set this with environment variables when you start the program or container. In Apache Superset, this is not possible. There is an ongoing discussion on Github about this issue. One GitHub user posts the problem and workaround, which is far from workable:

Daylight savings causes issues where users have to update datasource
timezone offset for each datasource twice per year.

So the only thing you can do is update the hours offset twice a year. To make matters even worse, if you use Postgresql, this may not even be possible due to a bug as described here.


Q: MS Access SQL Left Joins Not Working Can't get this ms JET sql query (querying a 2007 Access database that I didn't write) to work. Error mentions "too few parameters, expects 4". I believe it has to do with my JOINs.
Anyone know what I'm missing?
SELECT TOP 500 [Load Items].[LoadItemsID] AS load_order_line_id,
        lo.[LoadOrderID] AS load_order_id,
        sp.[Description] AS product_description,
        sp.[Common Name] AS product_common_name,
        c.[Bill To Name] AS company_name,
        lp.[Ship Date] AS ship_date,
        al.[Ordered] AS order_quantity,
        al.[Price] AS sell_price,
        a.[Order Date] AS order_date,
        a.[Due Date] AS due_date
        FROM ((((((([Load Items]
            LEFT JOIN [Acknowledgement Lines] AS al
                ON al.[AcknowledgmentLineID] = [Load Items].[AcknowledgmentLineID])
            LEFT JOIN [Product] AS p
                ON p.[ProductID] = al.[ProductID])
            LEFT JOIN [Product Master] AS pm
                ON pm.[ProductMasterID] = p.[ProductMasterID])
            LEFT JOIN [Species] AS sp
                ON sp.[SpeciesID] = pm.[SpeciesID])
            LEFT JOIN [Acknowledgement] AS a
                ON a.[AcknowledgmentID] = al.[AcknowledgmentID])
            LEFT JOIN [Customer] AS c
                ON c.[CustomerID] = a.[CustomerID])
            LEFT JOIN [Load Orders] AS lo
                ON lo.[LoadOrderID] = [Load Items].[LoadOrderID])
            LEFT JOIN [Load Planner] AS lp
                ON lp.[LoadPlannerID] = lo.[LoadPlannerID]
        GROUP BY [Load Items].[LoadItemsID],
            lo.[LoadOrderID],
            sp.[Description],
            sp.[Common Name],
            c.[Bill To Name],
            lp.[Ship Date],
            al.[Ordered],
            al.[Price],
            a.[Order Date],
            a.[Due Date];

A: The most likely cause is typos in field names. Each bracketed field name that doesn't correctly match the field name that you are trying to access in the tables is one missing parameter, as far as the parser is concerned.


Q: Complex query on more than one child in cloud functions Here is the structure of my firebase database:
/UserData
  /DeviceMgmt
      /Counters
          /NumberOfAll:
          /NumberOfSelected
          /TotalDownloaded
        ...
      /Devices
          /pushId1
            /uid
            /signOutTime
            /toSelect=true (optional)
            /downloaded
            /lastDownload

          /pushId2
          /pushId3
           ...

And this is my cloud function:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate( (change) => {

   const changeRef = change.after.ref;
   const deviceMgmtRef = changeRef.parent.parent;   // /UserData/DeviceMgmt

   if (change.after.val() === 0 ) { //NumberOfSelected gets 0 value

        return deviceMgmtRef.once('value')
            .then((snap) => {

                const devicesRef = snap.child('Devices').ref;

                var average;
                var numberOfAllDevices;
                var totalDownloaded;

                numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
                totalDownloaded = snap.child('Counters/TotalDownloaded').val();
                average = Math.round(totalDownloaded/numberOfAllDevices);

                return devicesRef
                        .orderByChild('signOutTime')
                        .equalTo(0)
                        .once('value',(devices) => {
                        return devices.ref
                                .orderByChild('downloaded')
                                .endAt(average)
                                .once('value',(devices) => {
                                    devices.forEach((device) => {
                                        device.child('toSelect').ref.set(true);
                                    });
                        });
                });
            });

   } else {
       return false;
   }

});

The function triggers when the counter NumberOfSelected = 0;
This happens when under any of device pushId there is no child toSelect. Then the query on downloaded child makes all devices with downloaded less than average set toSelect=true.
I wanted to limit the devices only to those which have signOutTime equal 0.
Somehow that query does not work and all devices are considered.
What I did wrong???

A: I would push all async tasks into a promise array and then return them all when all tasks complete:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate((change) => {
  const changeRef = change.after.ref;
  const deviceMgmtRef = changeRef.parent.parent; // /UserData/DeviceMgmt
  if (change.after.val() === 0) { //NumberOfSelected gets 0 value
    return deviceMgmtRef.once('value')
      .then((snap) => {
        const promises = [];
        const devicesRef = snap.child('Devices').ref;
        var average;
        var numberOfAllDevices;
        var totalDownloaded;
        numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
        totalDownloaded = snap.child('Counters/TotalDownloaded').val();
        average = Math.round(totalDownloaded / numberOfAllDevices);
        const dR = devicesRef
          .orderByChild('signOutTime')
          .equalTo(0)
          .once('value', (devices) => {
            const dW = devices.ref
              .orderByChild('downloaded')
              .endAt(average)
              .once('value', (devices) => {
                devices.forEach((device) => {
                  if (device.child("signOutTime").val() === 0){
                    promises.push(device.child('toSelect').ref.set(true));
                  }
                });
              });
              promises.push(dW);
          });
          promises.push(dR);
          return Promise.all(promises);
      });
  } else {
    return false;
  }
});


Q: RoR: How to use *_path in a model? I need to generate a “report” in a model. This “report” has to include links. However, all the *_path functions seems to be unavailable in the model classes (a simple test show me that new_post_path raises an Exception in my models, but works fine in my controllers)
Is there any way to use polymorphic_url or, at least, *_path methods in my models ?

A: if you:
include ActionController::PolymorphicRoutes

In your model:
class SomeModel < ActiveRecord::Base
  include ActionController::PolymorphicRoutes
end

you get polymorphic_path and polymorphic_url.  These can then be used by passing self into the methods if you're generating a route for the current AR object.


Q: Custom post type for text box that appears on every page I want to create a custom post type for an entry that will appear on every page of a website. A few other CMS's have a 'globals' entry type for this. How would I go about this using Wordpress?

A: I think the most popular way to do this is to use a widget in the installation. Or ACF pro provides a global field - but that's a commercial plugin.


Q: At what point should data be sent back to server? A good example would be the stackexchange "rate" button. When a post is upvoted the arrow changes color immediately. However there is a grace period for one to edit one's vote decision (oops! voted by mistake?). Is the upvote action processed immediately or does is only process after a set time period, or when the user leaves the page? How exactly is this rating processed?
What is the standard for handling dynamic page edits (e.g. stackexchange rating, facebook posts?)

A: Generally I would recommend that you make the changes immediately. If there's to be a "grace period", then implement that on the server side (you can do it client side too if it will improve user experience).
So if someone upvotes a post, it is saved immediately via ajas, but then if they change their minds within the grace period, the server undoes the vote. Once the "grace period" is up, the server rejects the change.
A Facebook post would (obviously) be saved when you click "Post", etc. -- but it wouldn't be saved before then.
Something like Blogger or Google Docs is another issue altogether -- where it's automatic saving every x number of seconds. That is purely up to the developer. Generally you want to make it as often as possible without impacting performance or decreasing the user experience.


Q: How to get releases for golang/go with go-github Learning Go and try to get the release list of golang/go with go-github.
Here is my code:
package main

import (
    "github.com/google/go-github/github"
    "fmt"
)

func main() {
    client := github.NewClient(nil)

    opt := &github.ListOptions{Page: 2, PerPage: 10}
    releases, rsp, err := client.Repositories.ListReleases("golang", "go", opt)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("\n%+v\n", releases)
    fmt.Printf("\n%+v\n", rsp)

}

When I run it, the release list is empty (as below):
[]

github.Rate{Limit:60, Remaining:59, Reset:github.Timestamp{2015-12-05 14:47:55 +1100 AEDT}}

I don't know what I am doing wrong.

A: Edit:
Taking a closer look at the Go repository, the releases are actually just tags and not Github releases, that's why it's returning an empty array. Try this:
// https://api.github.com/repos/jp9000/obs-studio/releases
releases, rsp, err := client.Repositories.ListReleases("jp9000", "obs-studio", opt)

This should correctly return all releases for jp9000's obs-studio repository.
Original Answer:
Looking at the docs, the code looks good but this might be an issue with Github's API though. For instance, if you go to https://api.github.com/repos/golang/go/releases you get an empty array, but if you search for the tags using https://api.github.com/repos/golang/go/tags it lists all tasks without any problem.
And if you go to https://api.github.com/repos/golang/go/releases/1 you get a 404. I took these addresses from the Github Developer's page: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository


Q: Cбой операции во время установки NLog.Configuration Cбой во время установки НЛог там говориться что оно уже установлено но как можно включить это в референсес в Visual Studio 2012
Идет попытка разрешить зависимость "NLog (≥ 4.5.8)".
У "NLog" уже есть зависимость, определенная для "NETStandard.Library".


Q: Can't insert any values in Judy I'm getting strange behavior with Judy Array. The documentation just says you can use it like an usual PHP array. But whatever I do it seems to me that it won't store any information.
For example if I do this:
$this->_history = new Judy(Judy::STRING_TO_MIXED);
$this->_history['test'] = 'testString';
echo $this->_history['test']; // output nothing; no warnings no text nothing
var_dump($this->_history); // class Judy#126 (0) { }
$this->_history->getType() // correctly (int) 5
$this->_history->getTypeFoo() // warning no method

Am I doing something wrong? Did I forget something? I tested it both an an Ubuntu and Debian System, both the same.
Also funny is, that when I run the bench-script which is provided in the pecl package and extracted under /usr/share/php/doc/Judy/examples/judy-bench-string_to_int.php the Judy Array works fine.
Here's how I installed it:
sudo aptitude install libjudydebian1 libjudy-dev
sudo pecl install judy

It said installation was succesful and I added extension=judy.so to php.ini.
What should I do to get Judy working?

A: Well it works now. But actually I don't know why. I shouldn't care.
I copied the working code from the bench-*.php file from the /docs into my own file and it worked. Here's the code:
echo "\n-- Judy STRING_TO_INT \n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";

$s=microtime(true);
$judy = new Judy(Judy::STRING_TO_MIXED);
for ($i=0; $i<500; $i++)
    $judy["$i"] = 'test';
var_dump($judy);
unset($judy["102"]);
echo $judy["192"];
var_dump($judy["102"]);
echo "Size: ".$judy->size()."\n";
$e=microtime(true);
echo "Elapsed time: ".($e - $s)." sec.\n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";
echo "\n";

unset($judy);


Q: Associative table many on many with varying level of entity specificity I have the need to associate a message or a group of messages with a display or a group of displays.
A message has a type, and a display has a type and a location ( for example, a city)
I would like to associate a message or all messages of a certain type to a display or all display of a certain type and/or location.
My first idea was to build an associative table many on many, with the foreign keys:

*

*Message_id

*Message_type_id

*Display_id

*Display_location_id

*Display_type_id

And when adding an entry, set a value for the fields i am interested in ( for example message_type and display_location), and null to the others.
However, i was interested in the downsides of this approach, and wondering if there are better methods to handle this kind of problems. After some days searching (in vain) for this kind of pattern when designing a database, i ultimately decided to ask here.
Thanks for the help.

A: The approach is sound.
It occurs to me that you only need Message_id  and Display_id  in the "intersection entity", as the other columns would probably come from the "parent" entity.
Message_type_id
Display_location_id
Display_type_id


Q: Does Apple Catalyst support iPhone There are many resources and tutorials mentioning iPad and/or iOS being compatible with Apple's Catalyst framework,
So, the same source-code runs on Mac OS X as well.
But does Catalyst support iPhone?
(Please tell me your personal experience to clarify this, and not that the name of iPhone operating-system is iOS)

A: Mac Catalyst allows iOS apps to be built for and run on macOS.
So, by definition, Catalyst apps support iOS, and usually the iPhone. The only case in which they wouldn't is if the app was specifically an iPad-only app that runs on Catalyst on the Mac, but was not enabled to run on the iPhone.
More about Catalyst: https://developer.apple.com/mac-catalyst/
You asked for personal experience: I have apps in the App Store for iOS, iPad, and Mac, via both Catalyst and non-Catalyst builds.


Q: Selectize.js destroy() method changes select value I'm using selectize.js in my project. What I need to do is clone part of the form (with selectized elements) and append it to the end of the form.
I've decided to destroy selectized elements before cloning, and after appending new subform initialize selectize again.
Here is a code for destroying selectized elements:
  var selectElements = $(plusButtonElement).parents(".subform_wrapper").first().find("> .subform_fields_wrapper").find("select");
$.each(selectElements, function(index, element){
    console.log(element);
    console.log($(element).val());    //Here we got value "10"
    $(element)[0].selectize.destroy();
    console.log($(element).val());    //Here we got value "A6"
});

It works - elements transform to the regular selects, BUT value of the select elements are changing. Did anyone face with this problem?
I checked selectize.js source and the only thing I can say is that value is changed in this code:
    self.$input
            .html('')
            .append(revertSettings.$children)
            .removeAttr('tabindex')
            .removeClass('selectized')
            .attr({tabindex: revertSettings.tabindex})
            .show();

A: Hi Tamara yes I think this is a bug of the Selectize.js.
I alter the following destroy method in selectize.js
destroy: function() {
        var self = this;
        var selectedValue = self.$input.val();
        var eventNS = self.eventNS;
        var revertSettings = self.revertSettings;

        self.trigger('destroy');
        self.off();
        self.$wrapper.remove();
        self.$dropdown.remove();

        self.$input
            .html('')
            .append(revertSettings.$children)
            .removeAttr('tabindex')
            .removeClass('selectized')
            .attr({tabindex: revertSettings.tabindex})
            .show();

        self.$control_input.removeData('grow');
        self.$input.removeData('selectize');

        $(window).off(eventNS);
        $(document).off(eventNS);
        $(document.body).off(eventNS);

        delete self.$input[0].selectize;

        self.$input.val(selectedValue);
    },

Here you can download my selectize.js file.


Q: Debug Dockerized Flask app in VSCode not breaking on breakpoints I followed this tutorial to set up debug in my VSCode.
My launch.json file is below.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/server/project/views",
                    "remoteRoot": "/server/project/views"
                }
            ]
        }
    ]
}

My code does break on raised and user uncaught exceptions but it does not break on the breakpoints that I set. The code is reaching the breakpoints and I checked it using print statements, but my breakpoints are not working. VSCode debugger does seem to listen to my docker app (seen in the logs in screenshot) but not sure why it is not breaking at my breakpoints. However, it does give an error saying:

pydev debugger: unable to find translation for:
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/utils/assessments.py"
in ["/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views/",
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views"]
(please revise your path mappings).

Kindly help!

A: Make sure your local and remote paths are correct. You can check your remote path by logging into the container's terminal. There you can find the absolute path of your "app".
I also cannot tell where you ${workspaceFolder} is actually is. Could be DTNetworkRepos or ip2m-metrr. You will need to make sure you clarify the path.
Also it would help if you posted up your folder stucture, Docker file for the server project and docker compose for all your container projects. Docker file will explain your path on the remote server. Dockerfile & Docker-compose file will ensure us that you have the right cmd or entrypoint for your environment. It may not line up with the tutorial that you set up.


Q: how to use geometry manager grid inside . which already has slaves managed by pack I found the code below on the net, and I tried to adapt it to my personal needs in my code but I have as error: tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack.
Here is the code I found on the net that allows to display large images by clicking on small images :
import tkinter as tk

nb_rows = 10
images = (
    ("images/small_images/small_image1.png", "images/big_images/big_image1.png"),
    ("images/small_images/small_image2.png", "images/big_images/big_image2.png"),
    ("images/small_images/small_image3.png", "images/big_images/big_image3.png"),
    ("images/small_images/small_image4.png", "images/big_images/big_image4.png"),
    # ...
)

def visualize(event):
    event.widget.unbind("<Button-1>")
    window = tk.Toplevel(event.widget)
    window._image = tk.PhotoImage(file=event.widget._filenames[1])
    tk.Label(window, image=window._image).pack()
    window.protocol("WM_DELETE_WINDOW", lambda: on_close(window))

def on_close(window):
    window.master.bind("<Button-1>", visualize)
    window.destroy()

root = tk.Tk()

labels, row, column = [], 0, -1
for index, filenames in enumerate(images):
    label = tk.Label(root)
    label["image"] = label._image = tk.PhotoImage(file=filenames[0])
    label._filenames = filenames
    label.bind("<Button-1>", visualize)
    if not index % nb_rows:
        column, row = 0, row + 1
    label.grid(column=column, row=row)
    row += 1
    labels.append(label)

root.mainloop()

here is part of my code that works correctly, and I want to integrate the code above on the left side (Text left) and adapt it to be functional :
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from tkinter import *

root=Tk()
root.iconbitmap(r'images/cev.ico')

text_part1_loc35R="\n===============================\n"
text_part2_loc35R="Emetteur Directif 1 :\n"
text_part3_loc35R="===============================\n"+\
"Puissance directe (P+BL)   : 4.47 w\n"+\
"Puissance reflechie (P+BL) : 0.13  w\n"+\
"Puissance directe (BLS)    : 0.09  w\n"+\
"Puissance reflechie (BLS)  : 0.00  w\n"+\
"===============================\n"

text_part4_loc35R="Emetteur Clearance 1 :\n"
text_part5_loc35R="===============================\n"+\
"Puissance directe (P+BL)   : 0.55 w\n"+\
"Puissance reflechie (P+BL) : 0.09  w\n"+\
"Puissance directe (BLS)    : N/A w\n"+\
"Puissance reflechie (BLS)  : N/A w\n"+\
"###############################\n\n"

generalites = Frame(root,bg="powder blue",width=750,height=250)
generalites.pack()
##########################################
#les sous frames de generalites(top,bottom):
generalites_top=Frame(generalites,relief=RIDGE,bd=18,bg='cadet blue')
generalites_top.pack(side=TOP,fill=X)

titre_generalites_top=Label(generalites_top,text='Generalites Techniques LOC 35R',font=('arial',22,'bold'),bg='cadet blue',padx=120)
titre_generalites_top.pack()

###############################################
generalites_bottom=Frame(generalites,bg='powder blue',width=750,height=270)
generalites_bottom.pack(side=BOTTOM)

#################################################
generalites_bottom_left=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_left.pack(side=LEFT)

generalites_bottom_right=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_right.pack(side=LEFT)

##################################################

T_generalites_left = Text(generalites_bottom_left,padx=20, height=26, width=30)
s_generalites_left = Scrollbar(generalites_bottom_left, command=T_generalites_left.yview)
T_generalites_left.configure(yscrollcommand=s_generalites_left.set)

T_generalites_left.tag_configure('style_loc35R',font=('arial',12,'bold'),foreground='blue',justify='center')

photo1=PhotoImage(file='images/test/image1.png')
photo2=PhotoImage(file='images/test/image2.png')
photo3=PhotoImage(file='images/test/image3.png')
photo4=PhotoImage(file='images/test/image4.png')
photo5=PhotoImage(file='images/test/image5.png')

for (j,k) in [('\nphoto 1\n',photo1),('\n\nphoto 2\n',photo2),('\n\nphoto 3\n',photo3),('\n\nphoto 4\n',photo4),('\n\nphoto 5\n',photo5)]:
    T_generalites_left.insert(END,j,'style_loc35R')
    T_generalites_left.image_create(END, image=k)

T_generalites_left.insert(END,'\n\n')
T_generalites_left.pack(side=LEFT,anchor=NW)
s_generalites_left.pack(side=LEFT, fill=Y)

T_generalites_right = Text(generalites_bottom_right, bg='powder blue',font=('arial',14,'bold'),padx=15, height=18, width=52)
s_generalites_right = Scrollbar(generalites_bottom_right, command=T_generalites_right.yview)
T_generalites_right.configure(yscrollcommand=s_generalites_right.set)

T_generalites_right.tag_configure('style_loc35R', foreground='blue',justify='center',font=('arial', 12, 'bold'))

T_generalites_right.insert(END,text_part1_loc35R)
T_generalites_right.insert(END,text_part2_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part3_loc35R)
T_generalites_right.insert(END,text_part4_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part5_loc35R)
T_generalites_right.pack(side=LEFT)
s_generalites_right.pack(side=RIGHT, fill=Y)

root.mainloop()

Thanks for help


Q: Assigning colors to a d3.js bar chart? I'm trying to create a color-coded bar chart using d3. I am SO CLOSE. Here's my bl.ocks chart:
http://bl.ocks.org/sconnors37/b99070b055f125c9dff1/1cb53954be3f20e3c4492066eccd749b5cf04bbe
What I'm trying to do is assign color values based on the "teams" field in my .tsv file. So grey for Mercedes, red for Ferrari, etc. I have the teams in the var color domain and the colors in the var color range, and I'm pulling var color into the bar attrib.
For some reason though, the entire chart is just taking on the first item in the range - I changed it from grey to red just to see if that was what was going on, and it is.
So! How do I get the rest of my colors to pull through onto the bar chart? Help me, stackoverflow, you're my only hope.

A: In your .tsv file the last column team is not separated from the previous column by a tab, but rather through two spaces. If you look at the data passed to the d3.tsv callback I think you will find that you have one date  team column instead of a date and team column.
This means that the field d.team is undefined and ordinal(undefined) will just return the first value from the range.


Q: Material-UI CardContent has a 3px Bottom Padding Note: I already looked into this question: Cant remove padding-bottom from Card Content in Material UI
But the accepted answer did not fix my issue.
I am using the Material UI React Library attempting to recreate the below image:

I am completely new to using the Material UI, so most of my code will likely not be optimized and probably does not follow best practices. Indeed, I'd be interested to hear how it could be made better.
Here is my code thus far:
<Card className={classes.card}>
  <CardActionArea containerStyle={{ paddingBottom: 0 }}>
    <CardMedia
      className={classes.media}
      title="Contemplative Reptile"
      image="none"
    >

        <AccessAlarmIcon className={classes.icon}/>
        <Typography className={classes.mainText} variant="h5" component="h2">Delayed</Typography>
        <Typography className={classes.subText} variant="subtitle1" component="h5">9:30pm Departure</Typography>

    </CardMedia>
    <CardContent className={classes.content}>

    </CardContent>
  </CardActionArea>
</Card>

With these styles:
const styles = {
  card: {
    maxWidth: 300,
  },
  media: {
    height: 60,
    backgroundColor: "#FF1547",
    padding: 16
  },
  icon: {
    color: "white",
    fontSize: 25,
    marginRight: 10
  },
  mainText: {
    color: "white",
    display: "inline-block",
    position: "relative",
    top: -3
  },
  subText: {
    color: "white",
    marginLeft: 36,
  },
  heading: {
    padding: 0
  },
  mainPic: {
    width: 300,
    height: 200,
    marginBottom: 0,
    padding: 0
  },
  content: {
    padding: "0 !important",
    '&:last-child': {
      paddingBottom: "0 !important",
    },
  }
};

This is what it looks like when rendered:

Notice the bottom padding. The Chrome Developer Tools show a 3px bottom padding under the User Agent Stylesheet. I imported a CSS Reset which did not help.
Again, I'm sure that my styles and JSX could be made better, but efficiency, optimization, and elegance were not of my concern.
Thanks,
Jamie

A: That padding at the bottom is actually caused by the box-shadow styling tied to the "elevation" property of Paper (which Card is based on). Setting the elevation to 0 gets rid of it:
<Card className={classes.card} elevation={0}>

However that also gets rid of the raised look of the card. The correct way to deal with this is to specify the image in a CardMedia element rather than using a separate img tag inside a CardContent element.
<CardMedia
          className={classes.mainPic}
          image="http://images1.fanpop.com/images/image_uploads/Golden-Gate-Bridge-san-francisco-1020074_1024_768.jpg"
        />

Here's a CodeSandbox showing this:

You can also see this approach used in this demo:
https://material-ui.com/demos/cards/#ui-controls

A: See if this is what you want. I changed  mainPic and content.
This syntax containerStyle={{ paddingBottom: 0 }} does not seem correct even gets the alert in the browser. Maybe you want to change the styleor classes={{root}} of the api CardActionArea.
mainPic: {
  width: 300,
  marginBottom: 0,
  padding: 0,
  borderRadius: '0 0 4px 4px',

},
content: {
  height: 225,
  padding: "0 !important",
  '&:last-child': {
    paddingBottom: "0 !important",
  },
}


Q: Exception when adding new method in a working Service using gRPC-Web and protobuf-net I am getting the following exception:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The type initializer for 'DefaultProxyCache1' threw an exception. System.TypeInitializationException: The type initializer for 'DefaultProxyCache1' threw an exception. ---> System.ArgumentException: Invalid generic arguments
Parameter name: typeArguments
at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.MakeGenericMethod_impl(System.Reflection.RuntimeMethodInfo,System.Type[])
at System.Reflection.RuntimeMethodInfo.MakeGenericMethod (System.Type[] methodInstantiation) <0x342def8 + 0x000d6> in :0
at ProtoBuf.Grpc.Internal.ContractOperation.TryGetClientHelper () [0x0001b] in //src/protobuf-net.Grpc/Internal/ContractOperation.cs:291
at ProtoBuf.Grpc.Internal.ProxyEmitter.EmitFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x00477] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:238
at ProtoBuf.Grpc.Internal.ProxyEmitter.CreateFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x0006d] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:123
at ProtoBuf.Grpc.Configuration.ClientFactory+DefaultProxyCache`1[TService]..cctor () [0x00000] in //src/protobuf-net.Grpc/Configuration/ClientFactory.cs:81

My project uses gRPC-Web, Blazor web assembly and protobuf-net
This is my service contract:
[ServiceContract(Name = "Services.Customer")]
public interface ICustomerService
{
    ValueTask<Customer> CreateCustomer(Customer customerDTO);

    ValueTask<CustomerResultSet> GetCustomers();
}

The implementation is:
public class CustomerService : ICustomerService
{
    private readonly CustomerUseCases customerLogic;

    public CustomerService(CustomerUseCases customerLogic)
    {
        this.customerLogic = customerLogic;
    }

    public async ValueTask<Customer> CreateCustomer(Customer customerDTO)
    {
        var result = await customerLogic.CreateCustomer(customerDTO);

        return customerDTO;
    }

    public async ValueTask<CustomerResultSet> GetCustomers()
    {
        CustomerResultSet result = new CustomerResultSet { Customers = await customerLogic.GetCustomer() };
        return result;
    }
}

As for the Datacontracts:
[DataContract]
public class CustomerResultSet
{
    [DataMember(Order = 1)]
    public IEnumerable<Customer> Customers { get; set; }
}

And,
[DataContract]
public partial class Customer
{
    [DataMember(Order = 1)]
    public int CustomerId { get; set; }
    [DataMember(Order = 2)]
    public string CustomerName { get; set; }
}

Before I was returning a List of customers in the service but I realize I needed a class to model the message in order to protobuf-net be able to serialize that is why CustomerResultSet. Still, it is not working.
Any help much appreciated

A: That is... odd. I can't repro it here, so I'm guessing it is something specific to Blazor. I've checked what the code does in the "regular" frameworks, and at least for me it seems to do the right things - using UnaryValueTaskAsync<Customer, Customer>() and UnaryValueTaskAsync<Empty, CustomerResultSet>(), which is what I would expect. I've improved the exception handling in that code path, to at least give us a clue what it is trying to do, so my suggestion is:

*

*update to protobuf-net.Grpc version >= 1.0.119 (I'll get it deployed as soon as CI finishes)

*retry, and let me know exactly what it says now
Alternatively, if you have a minimal repro including the blazor bits on, say, a GitHub repo, I can happily take a look there.
(tip: I try to keep an eye on both Stack Overflow and GitHub, but GitHub is probably more appropriate for this kind of question - I'd happily say that this is a bug, so: https://github.com/protobuf-net/protobuf-net.Grpc/issues)

A: I was having a similar problem.
System.InvalidOperationException: Error obtaining client-helper 'UnaryValueTaskAsync' (from: 'System.Guid', to: 'Test.DTO.OpResult'): Invalid generic arguments
My entire ServiceContract on that service stopped working. This happened after I added
ValueTask ChangeCompany(Guid companyGuid);
I changed it to
ValueTask ChangeCompany(string companyGuid);
And that got it working again. The error was a bit confusing since i wasn't using ChangeCompany, but like a said, not calls were working.


Q: What is the input data structure for HERMES toolbox for EEG connectivity analysis? I wanted to use HERMES for connectivity analysis of my EEG dataset which includes 32 subjects and 40 trials for each subject. There are two conditions/classes. I do not know how my data should be defined to be known by HERMES!
Could you please kindly tell me what should the structure of input to HERMES be?
Or is there a better alternative like Brainstorm to use in my MATLAB scripts (I mean without using its GUI manually and do my connectivity analysis automatically by using loops instead)?
Any help in this regards is greatly appreciated.
HERMES toolbox
Brainstorm toolbox

A: HERMES accepts MAT files (*.mat) and Fieldtrip structures.
MAT files should consist on one single matrix with as many columns as channels and as many rows as temporal points (and, in the case of event-related data, the third dimension will be for the different trials).
For example, for one subject and condition: a matrix of (30 channels x 1000 samples (x 50 trials)).
Therefore, to be able to load your data easily, you'll need to obtain your MAT files as described above.
Thanks to Guiomar Niso for providing this answer.


Q: Error installing PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56 on Magento 1.9.2.4 I'm getting the following error and have no idea why. All my extensions are properly installed to not effect any code code.
Any ideas?
sudo sh ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 25: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 0: not found
Checking if patch can be applied/reverted successfully...
-e ERROR: Patch can't be applied/reverted successfully.

checking file app/code/core/Mage/Admin/Model/Session.php
checking file app/code/core/Mage/Adminhtml/Block/Checkout/Formkey.php
checking file app/code/core/Mage/Adminhtml/Block/Notification/Symlink.php
checking file app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
checking file app/code/core/Mage/Adminhtml/Model/Config/Data.php
checking file app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php
checking file app/code/core/Mage/Checkout/controllers/MultishippingController.php
checking file app/code/core/Mage/Checkout/controllers/OnepageController.php
Hunk #1 succeeded at 350 (offset 1 line).
Hunk #2 succeeded at 370 (offset 1 line).
Hunk #3 succeeded at 417 (offset 1 line).
Hunk #4 succeeded at 446 (offset 1 line).
Hunk #5 succeeded at 485 (offset 1 line).
checking file app/code/core/Mage/Checkout/etc/system.xml
checking file app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php
Hunk #1 succeeded at 282 (offset -1 lines).
checking file app/code/core/Mage/Core/Controller/Front/Action.php
checking file app/code/core/Mage/Core/Controller/Request/Http.php
checking file app/code/core/Mage/Core/Model/File/Validator/Image.php
checking file app/code/core/Mage/Core/etc/system.xml
checking file app/code/core/Mage/Customer/Model/Session.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Adapter/Zend/Cache.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
checking file app/code/core/Mage/ImportExport/Model/Import/Uploader.php
checking file app/code/core/Mage/Sales/Model/Quote/Item.php
checking file app/code/core/Mage/Widget/Model/Widget/Instance.php
checking file app/code/core/Mage/XmlConnect/Helper/Image.php
checking file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
checking file app/design/adminhtml/default/default/layout/main.xml
checking file app/design/adminhtml/default/default/template/notification/formkey.phtml
checking file app/design/adminhtml/default/default/template/notification/symlink.phtml
checking file app/design/adminhtml/default/default/template/page/head.phtml
checking file app/design/frontend/base/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/billing.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 35 (offset -1 lines).
checking file app/design/frontend/base/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/shipping_method.phtml
checking file app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml
checking file app/design/frontend/rwd/default/layout/page.xml
checking file app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/rwd/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 36 (offset -1 lines).
checking file app/design/frontend/rwd/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml
checking file app/etc/config.xml
checking file app/locale/en_US/Mage_Adminhtml.csv
Hunk #1 succeeded at 1281 (offset -4 lines).
checking file app/locale/en_US/Mage_Core.csv
Hunk #1 succeeded at 406 (offset -1 lines).
checking file app/locale/en_US/Mage_Dataflow.csv
checking file app/locale/en_US/Mage_XmlConnect.csv
checking file downloader/Maged/Connect.php
Reversed (or previously applied) patch detected!  Assume -R? [n]
Apply anyway? [n]
Skipping patch.
3 out of 3 hunks ignored
checking file downloader/Maged/Controller.php
Reversed (or previously applied) patch detected!  Assume -R? [n]
Apply anyway? [n]
Skipping patch.
2 out of 2 hunks ignored
checking file downloader/Maged/Model/Session.php
Hunk #1 succeeded at 96 with fuzz 2 (offset 14 lines).
Hunk #2 succeeded at 302 with fuzz 2 (offset 29 lines).
checking file js/lib/jquery/jquery-1.12.0.js
checking file js/lib/jquery/jquery-1.12.0.min.js
checking file js/lib/jquery/jquery-1.12.0.min.map
checking file js/varien/payment.js
checking file skin/frontend/base/default/js/opcheckout.js
Hunk #1 succeeded at 711 (offset 27 lines).

A: The hunk error normally came because it will not match the file lines. In this case you can do 2 things.

*

*Replace those mention error files with new same version Magento setup and then try to install the patch using SSH.

*Install the patch manually.

In this patch in front end only form key is added in checkout and cart files so you can do it manually.
Thanks.

A: I had a similar issue.
The solution for me was next:

*

*Check if you have 'downloader' folder in your project, if not (usually it is not under git) - download it (better from the current project, versions can be different);

*Revert the previous version of this patch (description of the patch - "Note that you must revert SUPEE-9767 version 1 before deploying version 2.")
($ bash ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh -R)
and after that try to patch 2nd version.


Q: Tools to determine video orientation I receive videos from different devices and want to encode them using the correct orientation.
I've seen some of examples of how to determine the orientation of a video from a iPhone.
With exiftool and mediainfo I can indeed tell if an iPhone video has to be rotated.
However, for android videos, both portrait and landscape videos have the same rotation and matrix structure as each other.
Maybe this is just with my phone, I'm trying to find videos taken from newer droid phones.
My question however is whether there's other tools or a different way to determine the orientation that'll work with all devices.
EDIT:
I just checked a video from a Samsung Galaxy S II, and I can get the orientation from exiftool. So it's not a problem with all android phones.
My android phone is a HTC Desire running on android 2.2.
And actually (I didn't even notice before) a portrait video will not be correctly oriented even when playing on the phone. So I guess it's not about the tools, the orientation data just doesn't seem to be correct at all.

A: Some phones include the rotation information, some phone don't, but the best way to know on videos that include this information is with mediainfo:
mediainfo --Inform="Video;%Rotation%"


Q: assign process id to an asynchronous request tornado I would like to create consistent logs so that I can compute statistics on each tornado request, I have a request as below:
@tornado.web.asynchronous
    def post(self):
    try:
        process_id = uuid.uuid4()
        logging.info("Incoming request (process_id: %s) to %s" % (str(process_id), self.__class__.__name__))

which would print some info when a request comes in, but the request gets completed in tornado code, which would only print this:
[I 150331 10:55:09 web:1728] 200 POST /transform (127.0.0.1) 3017.19ms

Is there a way to pass my process id to tornado (or make it create one), so that I can connect the first and the last log events of a request?
thanks,

A: In general, the best way to record something like this is to attach it to the RequestHandler instance. For logging, you can override Application.log_request, which has access to the handler. You may need to pass either the request ID or the RequestHandler instance around to other parts of your code if you need to use this in multiple places.
It is possible but tricky to use StackContext as something like a threading.Local if you really need this to be pervasive, but explicitly passing it around is probably best.


Q: executing samtools in terminal: "command not found", but it is installed I have samtools installed, and I have used it before on my computer. I am trying to get it to work now, but when I type in samtools in terminal (mac os), it returns "command not found". I have navigated into my samtools folder too and it is still not working. Am i missing something? Thank you for your help


Q: Как сохранить записи в таблице при перемещении её между приложениями Django? Есть модель Document в одном из аппов, я её перемещаю в другой апп и называю Contract. Как мне не потерять записи при перемещении? Как грамотно написать кастомную миграцию?

A: Записи хранятся в sqlite3 или в подключённой вами базе данных.
Если вы хотите получить данные из sqlite3:
1. Делаете dump текущих данных (получаете *.json):
python manage.py dumpdata > projectdata.json
2. Подключаете необходимую вам БД в настройках вашего проекта.
3. Переходите в dbshell
python manage.py dbshell
=> TRUNCATE django_content_type CASCADE;
4. Загружаете дамп в проект:
python manage.py loaddata projectdata.json
Если вы хотите получить данные из другой подключенной базы данных - воспользуйтесь встроенными средствами этой базы данных.

A: Решено. Достаточно провести подобную миграцию перед удалением таблицы Document
from django.db import migration

def migrate_existing_rows(apps, schema_editor):
    document = apps.get_model("accounts", "Document")
    contract = apps.get_model("contracts", "Contract")
    alias = schema_editor.connection.alias

    for doc in document.objects.all():
        contract.objects.using(alias).create(
            title = doc.title,
            file = doc.file,
            tenant = doc.renter,
            object = doc.object
        )

class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0025_add_issue_create_date"),
        ("contracts", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(migrate_existing_rows)
    ]


Q: Strange behaviour in Material datepicker I'm trying to use materialize date picker (http://materializecss.com/forms.html). With that, I want to popup the date picker when I click on an icon. I have implemented two implementations where the only difference between the two is putting an alert('clicked') with the code.
without the alert('clicked'): http://jsfiddle.net/1bnnkhbw/
with the alert('clicked'): http://jsfiddle.net/1bnnkhbw/1/
The second one works while the first one doesn't.. (in chrome)!!!
Anybody knows the reason for this behavior?
And a way to make the 1st one work?

A: I think I found a solution for you man check this out:
<i id="icon">click</i>
<input class="datepicker" style="display:none;" value="click"></input>

$('.datepicker').pickadate({
    selectMonths: true,
    selectYears: 15
  });

$('#icon').click(function(event){
    event.stopPropagation();
    $(".datepicker").first().pickadate("picker").open();
    console.log("test1");
});

Fiddle: http://jsfiddle.net/k2qtzp7p/1/
Code taken from here and here


Q: QEMU frequency mismatch on Kubuntu I have the following message on my Kubuntu 17.10 - I googled the message but unfortunately hits are way too technical for me to find a solution:
Emulator: qemu-system-i386: warning: TSC frequency mismatch between VM
(2394456 kHz) and host (2394457 kHz), and TSC scaling unavailable

With the following symptom:

At first launch everything worked well in this regard, so I don't know what caused the issue and how to solve it.

A: I have the solution via a workaround!
tl;dr version: -use-system-libs option with the emulator is a temporary workaround.
longer version:
Googling TSC frequency mismatch gave no ideas as to what might cause the issue. Disabling HW acceleration was one possible fix, but the result is a slow emulation. I gave it some rest but then I figured this should be a kernel related issue, since it was KVM that seemed to cause the issue.
I tried disabling intel microcode driver (no help) and a kernel update (no help), but after the latter, at least I got little less cryptic error messages like:
21:31   Emulator: libGL error: unable to load driver: i965_dri.so
21:31   Emulator: libGL error: driver pointer missing
21:31   Emulator: libGL error: failed to load driver: i965
21:31   Emulator: libGL error: unable to load driver: i965_dri.so
21:31   Emulator: libGL error: driver pointer missing
21:31   Emulator: libGL error: failed to load driver: i965
21:31   Emulator: libGL error: unable to load driver: swrast_dri.so
21:31   Emulator: libGL error: failed to load driver: swrast
21:31   Emulator: X Error of failed request:  BadValue (integer parameter out of range for operation)
21:31   Emulator: Major opcode of failed request:  155 (GLX)
21:31   Emulator: Minor opcode of failed request:  24 (X_GLXCreateNewContext)
21:31   Emulator: Value in failed request:  0x0
21:31   Emulator: Serial number of failed request:  64
21:31   Emulator: Current serial number in output stream:  65
21:31   Emulator: Process finished with exit code 1

So this must be a driver issue! Googling the first error message gave me this hit, using  -use-system-libs with the emulator. It's working now! But, how to make it permanent? This page also pointed me to the right direction: use a wrapper script to launch the emulator. Now everything works like a charm.
So, step-by-step solution:

*

*in terminal: /home/$user/Android/Sdk/emulator/emulator -list-avds to find your AVD-s - the names might differ from those apparent in Android Studio. Find the name of the AVD you have trouble with. Note that the emulator path might differ as well, based on the path you have specified during AStudio installation.

*test if the following works for you as a manual workaround:  /home/$user/Android/Sdk/emulator/emulator -avd your_emulator_name_here -use-system-libs

*if (2) works for you, rename the original emulator file and launch it from a shell script for permanent option flag launch (your path and text editor might differ):
$ cd /home/$user/Android/Sdk/emulator/
 $ mv emulator emulator.0
 $ touch emulator
 $ chmod +x emulator
 $ kate emulator
insert the following and save:
#!/bin/sh
set -ex
$0.0 $@ -use-system-libs

Now every time the emulator is called it is done so with the system libs through the shell script named emulator, and it should give no errors from now on.

A: Go to AVD Manager, click the AVD that is causing this issue, and select Wipe Data from the options.

A: I had the same problem due to some updates, I opened my Android Virtual Device Manager from Android Studio (Tools->AVD Manager) then matched the emulator where the problem occurred. I clicked the dropdown icon from Actions column and selected the Wipe Data option.


Q: VBA define property in a variable I am new to the forum, and also new to VBA (only started learning it a week ago).
Is it possible to define a property in a variable? I have a line that looks kind of like this:
Cells(i, j).Formula = "=" & .Cells(i, j).Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)

I have to write several cells, so I end up having many of these lines; if possible, I would like to do something like:
dim prop as string

prop = "Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)"

Cells(i, j).Formula = "=" & .Cells(i, j).prop

Can something like this be done?

A: You mean like this?
Function MyProp(ByVal r as Range) as String
    MyProp = r.Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)
End Function

...
Cells(i,j).Formula = "="& MyProp( Cells(i,j) )

This of course makes a cell reference itself, which is generally a bad idea and may lead to circular references. Best if you describe more on what you are trying to do in order to get better answers.

A: As mentioned in the comments this cannot be done in the way you describe.  There are two alternatives:

*

*Write a Private Function that you call with your input and expected output (more complicated)

*Write a loop with the code only appearing once. (less code)

To write a loop for all cells from A1 to Last used row, last used column:
Dim LastRow As Long, LastCol As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

For i = 1 To LastRow
    For j = 1 to LastCol
        `Do your stuff here
    Next j
Next i

Edit:
I'm going to assume you need to invest in the Range.Offset() method found here because right now, you are setting the cell's formula as equal to itself...


Q: How to build lighter version of opencv_java3 for android? I'm following these lines to build OpenCV's libraries for Android.
Usage Linux:
$ export ANDROID_NDK=/absolute/path/to/the/android-ndk
$ mkdir build && cd build
$ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake ..
$ make -j8

The built libopencv_java3.so file for one architecture (armeabi-v7a) is 8.3MB large.
Is there a way to omit some unused modules on build to get lighter libraries ?


Q: Outlook + Perl + Win32::Ole: How do you select calendar entries sorted by date? Current code opens up an Outlook Calendar database as follow:
my $outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application', 'Quit');

my $namespace = $outlook->GetNamespace("MAPI");

## only fetch entries from Jan 1, 2007 onwards
my $restrictDates = "[Start] >= '01/01/2007'";

A: Since you don't show the code that gets the date of your object, this question is impossible to answer without some knowledge of the Outlook object you are trying to access.
If you have an array of objects you can sort them by date and filter ones prior to a certain one.
my $sub = sub {
       my $ad = $a->date_string_accessor;
       my $bd = $b->date_string_accessor;
       $ad =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
       $bd =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
       return $ad cmp $bd;
};

my @sorted = sort $sub @unsorted;

print join("\n", @sorted);

But it would seem to me that you should use the application itself to do this -- presumably Outlook has some sort of query/sort functionality.


Q: How to compress a size of 1024*1024*1024*4 sparse array I have a sparse array which is size of 1024 * 1024 * 1024 * 4.  This array's item is byte. So the memory for the array is 4G. It is a sparse array, that is, non-zero item only about 600M. Hopefully, a storage structure can be proposed to compress the sparse array (compressed to 2 ~ 3G), and have good access speed.

A: The suitable representation depends on what operations is desired on the sparse array. The general approach is to store the locations of non-zero items and their values in a data structure.
One option is to use a hash table.
enum {NumDimensons = 4};
struct ArrayLocation {
  int16_t location[NumDimensions];
};

typedef uint8_t ArrayValue;

// Hash Table with key as ArrayLocation and value as ArrayValue

With hash table operations like get() and put() are straightforward, but iteration is not. If iteration is important, one option is to use a binary search tree.


Q: HTTP to HTTPS redirect with Exchange 2013 OWA I'm trying to set up an automatic redirect from http://webmail.domain.com to https://webmail.domain.com/owa of our Exchange Server 2013 CU1 using the IIS interface.
The old trick to just redirect the Default Web Site or the iisstart.htm redirect only works with https://webmail.domain.com (note that we need to specifiy https). Using only http:// will end up in a 403 Forbidden page for IIS.
The question is: how to setup this correctly so our users can connect in webmail.domain.com and it automatically redirects to https://webmail.domain.com/owa
Thanks,

A: I was able to solve my own problem using IIS Rewrite Mod. I was little confused when found this, since Rewrite Mod is well know in Unix world with the Apache Web Server.
Anyway, just downloaded and installed the IIS Rewrite Mod from here: http://www.microsoft.com/en-us/download/details.aspx?id=7435
And then modify web.config in wwwroot with this XML code:
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="HTTPS Redirect" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                </conditions>
                <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>
</configuration>
With this approach I was able to redirect HTTP to HTTPS in Exchange 2013.
And don't forget to disable the "Require SSL" option in the Default Web Site on IIS Control Panel or you'll get and 403 Unauthorised error page.

A: I like to require SSL and bounce the 403.4 error to https://domain/owa on the root and OWA applications.

A: Good deal glad to see you found another way of doing this.
The way I have been doing this is by using the redirect to force a redirect to SSL by clicking  the HTTP redirect on the default site. From there type in the absolute path like https://mail.domain.com/owa and then checking the "only redirect requests to content in this directory" checkbox. Turn off require SSL in the SSL settings and poof, you have your redirect with no rewrite mod required.
P.S. This article mentions an extra step to editing permission for downloading of the offline address book.
http://technet.microsoft.com/en-us/library/aa998359(v=exchg.150).aspx

A: I know, for a fact, that simply redirecting default web page to https://mail.server.net/owa works perfectly fine with exch13.  You must uncheck require ssl, but this is known.  I have had this setup since inception and it works fine.  You do NOT redirect the backend, only the default website.

A: You can simply force redirection on default web site to - https://owa.domain.com/owa and remove "require SSL" in SSL Settings.

A: Works perfectly. I would recommend this if you're using different URL's so you can keep using them instead of redirecting to one specific URL. We have about 10 different URLs for different companies (mail.company.com, mail.companyb.com, mail.companyc.com, etc.) and this works perfectly to preserve the URL.


Q: GCDWebServer always aborts on options check I started using GCDWebServer version 3.1 in an app last year, and this line in the addHandlerWithMatchBlock method of GCDWebServer.m always caused the system to abort immediately:
GWS_DCHECK(_options == nil);

I ended up just changing it to this to avoid the problem:
GWS_DCHECK(_options != nil);

Now I'm updating to the latest version 3.3.2 and see the same problem. My hack still works here, but I would like to know what a real solution would be. Can someone explain?

A: See docs in header:

Addling handlers while the server is running is not allowed.

Attempting to do this will result in undefined behavior.


Q: Sql Group by datetime I have a MySql table :
+--------------------+----------------+
| datetime           | energy         |
+--------------------+----------------+
| 2010-06-15 10:00:00|               1|
| 2010-06-15 10:15:00|               3|
| 2010-06-15 10:30:00|               6|
| 2010-06-15 10:45:00|               7|
| 2010-06-15 11:00:00|               9|
| 2010-06-15 11:15:00|              12|
| 2010-06-15 11:30:00|              15|
| 2010-06-15 11:45:00|              28|
| 2010-06-15 12:00:00|              52|
| 2010-06-15 12:15:00|              75|
| 2010-06-15 12:30:00|              88|
| 2010-06-15 12:45:00|             102|
| 2010-06-15 13:00:00|             150|
| 2010-06-15 13:15:00|             189|
| 2010-06-15 13:30:00|             200|
| 2010-06-15 13:45:00|             205|
| 2010-06-15 14:00:00|             209|
| 2010-06-15 14:15:00|             400|
| 2010-06-15 14:30:00|             450|
| 2010-06-15 14:45:00|             480|
| 2010-06-15 15:00:00|             500|
+--------------------+----------------+

I would obtain the production of every hour as difference between max and min of every hour:
example:
production of hour 10 is given by prod. of hour 11 (value = 9)  less production of hour 10 (value = 1)  -> result = 8
Expected result
+--------------+----------------+
| datetime     | energy         |
+--------------+----------------+
| 2010-06-15 10|               8|
| 2010-06-15 11|              43|
| 2010-06-15 12|              98|
| 2010-06-15 13|              69|
| 2010-06-15 14|             291|
+--------------+----------------+

select max(energy) - min(energy)
FROM tableA
group by hour(datetime)

this query doesn't work because make the difference between 10:45 and 10:00 ( not 11:00 and 10:00)
Any advice ?

A: To get the difference between each hour, use a self-join that relates times that are an hour apart.
SELECT a.datetime, b.energy - a.energy AS energy
FROM tableA AS a
JOIN TableA AS b ON a.datetime = DATE_SUB(b.datetime, INTERVAL 1 HOUR)
WHERE MINUTE(a.datetime) = 0

DEMO

A: EXAMPLE WITH MISSING DATA
+--------------------+----------------+
| datetime           | energy         |
+--------------------+----------------+
| 2010-06-15 10:00:00|               1|
| 2010-06-15 10:45:00|               7|
| 2010-06-15 11:00:00|               9|
| 2010-06-15 11:15:00|              12|
| 2010-06-15 11:30:00|              15|
| 2010-06-15 11:45:00|              28|
| 2010-06-15 12:15:00|              75|
| 2010-06-15 12:30:00|              88|
| 2010-06-15 12:45:00|             102|
| 2010-06-15 13:00:00|             150|
| 2010-06-15 13:15:00|             189|
| 2010-06-15 13:30:00|             200|
| 2010-06-15 13:45:00|             205|
| 2010-06-15 14:00:00|             209|
| 2010-06-15 14:15:00|             400|
| 2010-06-15 14:30:00|             450|
| 2010-06-15 14:45:00|             480|
| 2010-06-15 15:00:00|             500|
+--------------------+----------------+
In this example some samples are missing.
Expected result:
+--------------+----------------+
| datetime     | energy         |
+--------------+----------------+
| 2010-06-15 10|               8|  11:00 to 10:00
| 2010-06-15 11|              17|  11:45 to 11:00
| 2010-06-15 12|             150|  13:00 to 12:15
| 2010-06-15 13|              69|  13:00 to 14:00
| 2010-06-15 14|             291|  14:00 to 15:00
+--------------+----------------+
I always want to group by a complete hour:
From 10:00 to 11:00 included
From 11:00 to 12:00 included
From 12:00 to 13:00 included
ecc....
immagine


Q: Dyamically Assign JSON Property by Depth I would like to assign a variable on a json object by layers of depth.
For Example:
veryDeepTree[branch][branch][branch][branch] = value

would be achieved by executing the function:
assignByDepth(4, value, branch)

A: One way you can do this is by using a recursive function. Where each iteration of the function goes 1 level deeper until it reaches the desired level to set the value. This is a basic version assuming objects exists with correct depth before calling the function. As it is now, there can be multiple errors if used incorrectly, should be amended to add more error checks.

var veryDeepTree = {
    branch : {
       branch : {
          branch : {
          }
       }
    }
};

function assignByDepth(subTree, currentTreeDepth, objProperty, value){
   if(currentTreeDepth == 1){
      subTree[objProperty] = value;
   }else{
      assignByDepth(subTree[objProperty], --currentTreeDepth, objProperty, value);
   }
}

assignByDepth(veryDeepTree, 3, "branch", {branch:10});
console.log(veryDeepTree);

assignByDepth(veryDeepTree, 4, "branch", 5555);
console.log(veryDeepTree);


Q: Error Eclipse Project library see my screen :
http://it.tinypic.com/r/xpa240/8
I can not fix these errors. It seems that it does not generate the class R.
I've tried everything!
Clean the project,
Install all tools
help me thanks

A: The R class is generated automatically by the Android Eclipse plugin when it can. Here, I can see a red cross on your "res" folder so I think you should have some errors on your resources naming or type or something else : just look what your IDE is telling you !
Fix all errors that are not "R class missing" related and this class will be generated.

A: try this :
1 - File->Import (android-sdk\extras\android\support\v7). Choose "appcompat"
2 - Project-> properties->Android. In the section library "Add" and choose "appCompat"
3 - That is all!


Q: Integer array of resource ids returns 0 I have a set of resource ids stored in an array. This is accessed inside the recycler view to populate an image view. The problem is when I access the array, all values returned is 0.
// arrays.xml
<array name="array_category_icons">
    <item>@drawable/autumn</item>
    <item>@drawable/backpack</item>
</array>

// inside recycler view adapter
int[] myIcons = getActivity().getResources().getIntArray(R.array.array_category_icons);

myIcons[i] always returns 0.

The drawables are in the hdpi folder only.

A: Do this:
TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
    int id = ta.getResourceId(i, 0);
    if (id != 0) {
        icons[i] = ContextCompat.getDrawable(this, id);
    }
}
ta.recycle();


Q: Restricting Dates Using Custom Options - Input Type Date I'm looking to add in an estimated delivery date field on to the product pages of my magento store - I'm currently using a custom option within the product to control this with the date input type.
Is there anyway to stop a user from entering a date that has already passed and remove any dates that aren't available such as weekends and holidays?
I'm currently running Magento 1.8 should it make any difference


Q: Property of polynomials proof Let$$P(z)=\sum_{k=0}^n a_kz^k=a_0+a_1z+...+a_nz^n$$ be an N-th degree polynomial of a complex variable z, where the $a_k$ are complex constants. Now,$$\vert a_0\vert-\vert a_1\vert x-...-\vert a_n\vert x^n=0$$Has exactly one root, $r$, for $x \in [0,\infty)$. Given this, how could one prove that $$P(z)\neq 0 \ \text{for} \ \vert z\vert \lt r$$

A: Triangle inequality:  $$|P(z)| \ge |a_0| - |a_1| |z| - \ldots - |a_n| |z|^n$$

A: Using both sides of triangular inequality you have :
$$|P(z)|\geq |a_0|-|a_1z+...a_nz^n|\geq |a_0|-(|a_1||z|+...|a_n||z|^n) $$
Hence if :
$$f(x):=|a_0|-|a_1|x-...-|a_n|x^n $$
You will have that :
$$|P(z)|\geq f(|z|) $$
Now you just have to find a way to justify that $f(x)>0$ for $x\in (0,r)$.


Q: Saving the current data before updating the form in Django I would like to create a history of changes in one of my models. That every time I will update it, the current data will be saved to a different table and at the same time, the new data enters to another table. How will I be able to do that? I saw examples and they are based from the admin. But I still don't get the idea of it. This maybe a noob question but I'm still learning Django.
models.py
class tblTicket(models.Model): #new data will be entered here
    remarks = models.TextField("Action Taken", max_length=500,default='')
class LogChanges(models.Model): #table to save the changes
    prevRemarks = models.CharField(max_length=500,default='')

forms.py
class troubleTicket(ModelForm):
    class Meta:
        model = tblTicket
        fields = '__all__'

class history(ModelForm):
    class Meta:
        model = LogChanges
        fields = '__all__'

views.py
def updateTicket(request, ticket_id):
    ticketDetails=tblTicket.objects.get(id=ticket_id)
    updateTicketForm = troubleTicket(request.POST or None,instance=ticketDetails)
    if updateTicketForm.is_valid():
        updateTicketForm.save()
        return HttpResponseRedirect('/ticket/')
    return render(request,'updateTicket.html', {'updateTicketForm':updateTicketForm,'ticketDetails':ticketDetails,'ticket_id':ticket_id})

I am using django 1.8.3

UPDATE:
I found a link related to my question. But it gives me an error NameError: name 'tblTicket' is not defined
def make_copy(sender, **kwargs):
    obj = kwargs['instance']
    try:
        orig_obj = tblTicket.objects.get(pk=obj.pk)
    except: #If it is a new object
        orig_obj = None

pre_save.connect(make_copy, sender=tblTicket) <- this is where the error leads me

To my understanding, in this link, the Country there is the model. So I switched it to my model which is tblTicket. I don't understand why it isn't defined.

A: cIt sounds like you want to override the save method of your tblTicket model so that it creates a new LogChanges object. Like this..
class tblTicket(models.Model):
    ...

    def save(self):
        super(tblTicket, self).save()
        LogChanges.objects.create(prevRemarks=self.remarks)