Iterated integral over a region by vertical and horizontal cross-sections: what's the conceptual difference?

Question: I have a problem that instructs me to solve an iterated integral over a region, $R$, using vertical and horizontal cross-sections.
I understand that, by Fubini's theorem, the order of integration does not matter for the final answer. However, changing the order of integration may make the problem easier to integrate.
My question is regarding the difference between the concepts of integrating over vertical and horizontal cross-sections of a region: Although they should both produce the same final answer, what is the intuitive difference? For instance, when we integrate over a vertical cross section, we must first integrate with respect to $y$ and then with respect to $x$. When we integrate over a horizontal cross section, we must first integrate with respect to $x$ and then with respect to $y$. Why is there this difference? Conceptually, I do not understand what the difference is between these and why the order of integration is interchanged.
I would greatly appreciate it if people could please take the time to clarify this concept for me.
Answer: Both integrals compute the volume under the graph of a function $z = f(x,y)$. Think of the iterated integrals as an application of the "volume by slices" idea: adding up the volumes of thin slabs (more technically, integrating cross-sectional area).
For the integral $\iint f(x,y) \, dx \, dy$, you are first fixing $y$, and integrating over $x$, computing the cross-sectional area $A(y)$ at that fixed value of $y$. So this integral computes the volume "by slices", by integrating $\int A(y) \, dy$.
Similarly, for $\iint f(x,y) \, dy \, dx$, you are first computing the cross-sectional area $A(x)$ at each fixed value of $x$, and then integrating $A(x)$ to get the volume.
So the difference, conceptually, is the direction of the "slabs" or "slices" that you are using to compute the volume.
Comment: When doing iterated integrals, at each stage, you treat all other variables as constants. For example, if you do $\iint f(x,y) \, dx \, dy$, then the first integral treats $y$ as constant. That is what I mean by "fixed". Geometrically, the result of this first integral gives the function $A(y)$ of $y$ alone, as I mentioned above, and you can image that for each $y$, $A(y)$ is the area under the graph of the cross section of the surface with the plane $y=\mathrm{const}$.
Comment: Thanks for the response. Your post has clarified much of the concept. However, I have a couple of more questions, if it wouldn't be too much trouble: When you say we "fix" $x$ or $y$, how is this represented during this process? How do we represent the "fixed" variables when calculating area?
Answer: Mathematically changing integration over vertical and horizontal cross-sections of a region doesn't different in most cases, and this interchanging between them just easier them for integration. Picture below shows a region between two curves $y=2x^2-1$ and $4y=x^2-6x+1$.

Integrating over this region can be written like
$$\int_0^1\int_1^3 f(x,y)\,\text{dy}\text{dx}+\int_1^2\int_{down_1}^{up_1} f(x,y)\,\text{dy}\text{dx}+\int_2^3\int_{down_2}^{up_2}  f(x,y)\,\text{dy}\text{dx}$$
these might be a little hard to evaluate (for me) but someone can take a horizontal cross-section as shown below

this is better for calculation and I write the integral so
$$\int_1^2\int_0^{3-\sqrt{8-4y}} f(x,y)\,dx\,dy+\int_2^3\int_0^{3-\sqrt{y-2}} f(x,y)\,dx\,dy $$
which makes a little better. For instance if we want to find the area of this region,
take $f=1$ and we write
\begin{eqnarray*}
R &=& \int\!\!\int_R\,dx dy  \\
 &=& \int_1^2\int_0^{3-\sqrt{8-4y}}\,dx\,dy+\int_2^3\int_0^{3-\sqrt{y-2}}\,dx\,dy \\
 &=& \int_1^2(3-\sqrt{8-4y})\,dy+\int_2^3(3-\sqrt{y-2})\,dy\\
 &=& 4
\end{eqnarray*}


Pegar tamanho do ScrollPane quando definido pela ancoragem - JavaFX

Question: Eu tenho um ScrollPane ancorado nos 4 lados de um AnchorPane para que quando redimensionar a tela, o scroll também redimensione. Assim não preciso especificar um tamanho fixo. Até aí funciona como quero.
O problema é que desta forma os métodos getPrefWidth(), getWidth(), getMinWidth(), getMaxWidth() não me retornam o tamanho atual do scroll.
Alguém sabe como pegar o tamanho do ScrollPane defindo seu tamanho pela ancoragem e não pelos sets de definição de tamanho?
Answer: Você pode usar a função getBoundsInParent ou getBoundsInLocal. São funções que calculam as dimensões do nó com base em suas coordenadas. Em seguida usar os métodos getHeight() e getWidth() (Ou outros que julgar apropriados).
Exemplo:
AnchorPane parent = new AnchorPane();
ScrollPane child = new ScrollPane();

AnchorPane.setTopAnchor(child, 10.0);
AnchorPane.setBottomAnchor(child, 10.0);
AnchorPane.setLeftAnchor(child, 10.0);
AnchorPane.setRightAnchor(child, 10.0);

parent.getChildren().add(child);

// Painel principal
Scene scene = new Scene(parent, 200, 200);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();

System.out.println("Height: " + child.getBoundsInParent().getHeight()); // 180
System.out.println("Width: " + child.getBoundsInParent().getWidth()); //180

Referências: Get the Dimension of a Node
Comment: Obrigado, Gustavo! Funcionou bem demais
Answer: Para a barra vertical:
jScrollPane1.getVerticalScrollBar().getMaximum()

ou para a barra horizontal:
jScrollPane1.getHorizontalScrollBar().getMaximum()

Comment: Oi Rocigno. Na verdade os métodos que você sugeriu são para o scroll da biblioteca gráfica swing. No Javafx é diferente :\


Not able to receive emails on Postfix

Question: I installed a mail server with Postfix and Dovecot on Debian. I can send emails without worries to Outlook, Yahoo, ...BUT I can't receive emails from outside.
I use my internet box (free) as a router. I redirected flows comes on 993, 143, 25 and 587.
I use NOIP as DNS. I added the records needed for the MX part.
yacine@mezianeyacine:~$ nslookup -type=mx mezianeyacine.sytes.net
Server:         192.168.1.254
Address:        192.168.1.254#53

Non-authoritative answer:
mezianeyacine.sytes.net mail exchanger = 10 mail.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail exchanger = 20 imap.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail exchanger = 40 pop.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail exchanger = 1 smtp.mezianeyacine.sytes.net.

Authoritative answers can be found from:

yacine@mezianeyacine:~$

I have verified that my server is listening on the port 25 & 587. Also i have managed the firewall to accept incoming and outgoing connection for port 25
I have found a potential solution here:
the issue may that the mail.mezianeyacine.sytes.net don't have any address records:
yacine@mezianeyacine:/etc/apache2/sites-available$ host mezianeyacine.sytes.net
mezianeyacine.sytes.net has address 22.214.171.124
mezianeyacine.sytes.net mail is handled by 20 imap.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail is handled by 40 pop.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail is handled by 1 smtp.mezianeyacine.sytes.net.
mezianeyacine.sytes.net mail is handled by 10 mail.mezianeyacine.sytes.net.

yacine@mezianeyacine:/etc/apache2/sites-available$ host mail.mezianeyacine.sytes.net.
Host mail.mezianeyacine.sytes.net. not found: 3(NXDOMAIN)

yacine@mezianeyacine:/etc/apache2/sites-available$ host smtp.mezianeyacine.sytes.net.
Host smtp.mezianeyacine.sytes.net. not found: 3(NXDOMAIN)
yacine@mezianeyacine:/etc/apache2/sites-available$

Could you help me to solve this please ? I'm not sure to what I can do to solve.
Comment: It seems you don't understand what `MX` records are for.
Comment: May be you can explain to help to solve the issue ?
Comment: An MX record says that a mail responder is listening on a specific named server. What you seem to be missing is the A record which says where that specific mail server lives. Add A records in DNS that map `smtp.mezianeyacine.sytes.net`  and `mail.mezianeyacine.sytes.net` to your server's IP address.
Answer: It would be best to start by learning what a DNS MX record is, which helps to understand how to use them. Your current configuration suggests you would need MX records for IMAP, POP, SMTP and "MAIL", but that's not how it works!
As it seems you are only having one server at mezianeyacine.sytes.net handling the mail and it has SMTP banner configured for the same host name, it might be easiest to forget all the subdomains. Having multiple hostnames pointing to a single server does not increase redundancy at all.
You could simply replace all your MX records with a single record:
mezianeyacine.sytes.net. IN MX 1 mezianeyacine.sytes.net.

Not able to receive emails on Postfix


Is there any book online that shows mathematical procedures relating to perspective drawing?

Question: I am trying to learn comprehensive mathematical analyses (rather than geometrical methods) about perspective drawing projections. Can anyone suggest a good online book to buy that illustrates mathematical analyses in detail relating to perspective drawing? Thanks!
Answer: Viewpoints: Mathematical Perspective and Fractal Geometry in Art by by Marc Frantz and Annalisa Crannell:
http://www.amazon.com/Viewpoints-Mathematical-Perspective-Fractal-Geometry/dp/0691125929


How to run all tests in Bazel from a single java_test() rule?

Question: I am adding tests in Bazel, but I don't want to write a test rule for every single test file. However, each test rule requires a test_class - the test class that is being ran, so there is no easy way to just run all tests with a single java_test rule. Is there a work around for where I wouldn't need to specify a test_class and just run all tests at once?
Answer: In Bazel, we wrote a custom Junit Suite that finds all the Junit classes on the classpath in or under the package of the annotated class. You can find the code here. It's pretty short and straight forward and you can copy it into your project or do something similar.
You can then have your rules like this:
java_library(
    name = "tests",
    testonly = 1,
    srcs = glob(["*.java"])
)

java_test(
   name = "MyTests",
   test_class = "MyTests",
   runtime_deps = [":tests"],
)

and the MyTests.java file should look like this:
import package.ClasspathSuite;

import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
public class MyTests { }

Comment: How do I reference the dependency to get `com.google.devtools.build.lib.testutil.ClasspathSuite`?
Comment: Thanks Irina, this is actually what I was looking for, except that over weekend I came up with even shorted solution for myself. Let me know if there are concerns with the solution I accepted. It works well for me, but I am new to bazel, and maybe overlooked something...
Comment: Thank you Irina, can this solution be part of java_test?
Comment: @Zeitgeist would you care to share?
Comment: @caeus i don't have the code anymore, sorry
Answer: You can write a JUnit test suite class, which will run your other tests. For example, if you have test classes Test1.java and Test2.java, you can do something like this:
AllTests.java
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    Test1.class,
    Test2.class
})
public class AllTests {}

BUILD
java_test(
    name = "AllTests",
    test_class = "AllTests",
    srcs = [
        "AllTests.java",
        "Test1.java",
        "Test2.java",
    ],
)

EDIT in response to comment:
If you don't want to specify the test class names in your test suite, you could do something via reflection. The following example assumes all your tests are in the "com.foo" package and that all the tests are srcs of the java_test rule:
package com.foo;

import java.io.File;
import java.io.IOException;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import junit.framework.JUnit4TestAdapter;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;

@RunWith(org.junit.runners.AllTests.class)
public class AllTests {
  public static TestSuite suite() throws IOException {
    TestSuite suite = new TestSuite();
    URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    // The first entry on the classpath contains the srcs from java_test
    findClassesInJar(new File(classLoader.getURLs()[0].getPath()))
        .stream()
        .map(c -> {
          try {
            return Class.forName(c);
          } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
          }
        })
        .filter(clazz -> !clazz.equals(AllTests.class))
        .map(JUnit4TestAdapter::new)
        .forEach(suite::addTest);
    return suite;
  }

  private static Set<String> findClassesInJar(File jarFile) {
    Set<String> classNames = new TreeSet<>();
    try {
      try (ZipFile zipFile = new ZipFile(jarFile)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
          String entryName = entries.nextElement().getName();
          if (entryName.startsWith("com/foo") && entryName.endsWith(".class")) {
            int classNameEnd = entryName.length() - ".class".length();
            classNames.add(entryName.substring(0, classNameEnd).replace('/', '.'));
          }
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return classNames;
  }
}

Comment: Thanks Adam, I actually have tried this, and while this works, I was trying to avoid having extra java classes and solve this purely with Bazel. I was also looking to not have to add the test classes individually. Basically, I want my test classes to be picked up automatically without me having to explicitly specify them. I may have to go with this approach if I don't find anything better.
Comment: You could make AllTests use reflection to find your tests. I'm not aware of anything that does it by default, but I'll edit my answer with a possible example
Comment: Ended up using this solution because my own solution was not generating merged coverage.
Answer: Here is a solution that doesn't require using Suite.
Keep in mind, it will generate coverage reports .dat files individually for each class.
.bzl macro to handle all tests:
def run_tests(name, srcs, package, deps):
  for src in srcs:
    src_name = src[:-5]
    native.java_test(name=src_name, test_class=package + "." + src_name, srcs=srcs, deps=deps, size="small")

Calling that macro from the test files location:
run_tests(
    name = "test",
    srcs = glob(["*Test.java"]),
    package = "pkg",
    deps = [
        ":src_lib",
    ]
)

Answer: The Gerrit project contains a Starlark function called junit_tests.  It takes a list of srcs and generates an AllTestsTestSuite.java file that runs tests in each Java class.  It also generates a java_test target that includes the generated java file and all of the specified sources, deps, etc.  Here is how to set it up.
First add these lines to your WORKSPACE file:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

# Re-usable building blocks for Bazel build tool
# https://gerrit.googlesource.com/bazlets/
# https://gerrit.googlesource.com/bazlets/+/968b97fa03a9d2afd760f2e8ede3d5643da390d2
git_repository(
    name = "com_googlesource_gerrit_bazlets",
    remote = "https://gerrit.googlesource.com/bazlets",
    commit = "968b97fa03a9d2afd760f2e8ede3d5643da390d2",
)
# We cannot use the tar.gz provided over HTTP because it contains timestamps and each download has a
# different hash.
#http_archive(
#    name = "com_googlesource_gerrit_bazlets",
#    sha256 = "...",
#    urls = [
#        "https://gerrit.googlesource.com/bazlets/+archive/968b97fa03a9d2afd760f2e8ede3d5643da390d2.tar.gz",
#    ],
#)
# This provides these useful imports:
# load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", "maven_jar")
# load("@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests")

Now add this to your BUILD file:
load("@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests")

junit_tests(
    name = "AllTests",
    srcs = glob(["*.java"]),
    deps = [
        "//java/com/company/a_package",
        "@maven//:junit_junit",
        "@maven//:org_hamcrest_hamcrest",
    ],
)

If your BUILD file is at $WORKSPACE_ROOT/javatests/com/company/a_package/BUILD then you can run these specific tests with:
bazel test //javatests/com/company/a_package:AllTests

You can run all of your java tests like this:
bazel test //javatests/...

If your directory contains a .java file that has no tests, the AllTests target will fail with "No runnable methods".  The workaround is to add an empty test to the file:
/** Workaround for https://github.com/bazelbuild/bazel/issues/2539 */
@Test
public void emptyTest() {}

This is working for me with Bazel 2.0.0 on MacOS.  I can also run the tests inside IntelliJ 2019.2 with the Bazel plugin.


Is it true equation written on C #?

Question: The equation is:

Is it true I have written?
Double x = 14.26
Double y = -1.22
Double z = 3.5 * Math.Pow(10.0, -2)
Double t;

t = ( 2 * Math.Cos( x - Math.PI / 6 ) ) / ( 0.5 + Math.Pow( Math.Sin( y ), 2 ) ) * ( (1 + Math.Pow( z, 2 ) ) / ( 3 - Math.Pow( z, 2 ) / 5 ) );

Because the result does not coincide with the above desired result -- t = 0,188451240697501, and I need to t deduced 0.564849.
Comment: I suggest computing the numerators and denominators separately to make your expression easier to understand.
Comment: What about `y`? Is this in degrees or radians?
Comment: @GhostBasenji sorry but I think that Ofiris answer contains an error.. he does 1 + (Math.Pow(z, 2) and then divide all for (3-Math.Pow(z, 2)/5).. but this is an error if you see the algebric expression you posted, because you have add 1 to (Math.Pow(z, 2) / (3-Math.Pow(z, 2)/5)). The whole your previous part of expression is correct
Comment: @Dai excuse me, but it is you to have changed the confirmation about this question, please?
Comment: @CiroCorvino I don't understand.
Comment: @Dai nothing.. I just only asking if you had been you to have removed the confirmation on my answer because I had seen that the question was edited by you. But then I saw that you had edited the question on november... sorry
Answer: Double x = 14.26, y = -1.22, z = 3.5 * Math.Pow(10.0, -2), t;
    t = (2*Math.Cos(x-Math.PI/6))/(0.5+Math.Pow(Math.Sin(y), 2)) * ( 1 + (Math.Pow(z, 2)) / (3-Math.Pow(z, 2)/5));

    Console.WriteLine(t); // 0.5648...

You have parenthesis issue, change ((1 + Math.Pow(z, 2)) to (1 + (Math.Pow(z, 2)), the addition of 1 should be calculated after the division.
Also, consider computing the numerators and denominators separately.
Comment: This answer contains an obvious calculation error compared to the algebraic form of the expression given in the question. Because "1" is added to "(Math.pow (z, 2))" and then divided by "(3 - (Math.pow (z, 2) / 5))". While the correct calculation consists of the sum of "1" with the result of division between "(Math.pow (z, 2)) and (3 - (Math.pow (z, 2) / 5))".
Answer: I think that one error it is here:
((1 + Math.Pow(z, 2)) / (3-Math.Pow(z, 2)/5))

you should do:
(1 + (Math.Pow(z, 2) / (3-Math.Pow(z, 2)/5)))

Is it true equation written on C #?


Appeal play after a pitching change

Question: Is it possible to appeal a tag-up play at a base after a pitching change?  If so, how does it affect the pitchers' statistics?
For a concrete example, suppose P1 is pitching, runner R3 at third, one out.  Batter B hits a fly ball which is caught by the left fielder (two out).  Runner R3 advances to home.  Now pitcher P1 is removed and replaced with P2.  After the pitching change, but before P2 pitches to the next batter, the defense realizes that R3 left third before the fly ball was caught.  P2 throws to third to appeal.

Will R3 be called out, or is it too late to appeal?
If R3 is out, who is credited with the corresponding 1/3 inning pitched?  P1 or P2?
Suppose this is the last out of the game in a save situation.  Who gets the save?

Assume current MLB rules.  References to authoritative sources would be preferred if possible.  I couldn't find this situation addressed in the Official Rules.
Answer: I do not believe this is explicitly discussed anywhere.  However, I think the rules are sufficiently clear:
MLB Rules, 5.09(c):

Any appeal under this rule must be made before the next pitch, or any
  play or attempted play. If the violation occurs during a play which
  ends a half-inning, the appeal must be made before the defensive team
  leaves the field

I would argue that suggests that the appeal play is permitted after the substitution assuming no pitch or play had occurred in the intervening time period.  (And I think warmup tosses are permitted.)
I do think this would be, at least, frowned upon by the umpires, though, as there's no reason to do this (I guess, the team might have been tipped off in the intervening time that the runner left early and they didn't realize it earlier as you say, but really they should just appeal if there's any possibility - no cost to an appeal, as opposed to a review).
Comment: @Nij No, managers communicate with players on the field all the time.
Comment: But if they were tipped off, this is a rule infraction, I believe? Something about assisting or communicating with players during an innings if they're already on the field?
Comment: Assuming the appeal is allowed, what is the status of P2? Is the fact that he threw the ball enough to establish an appearance, or is he "ghost-throwing" the ball to 3rd on behalf of P1?
Comment: He would be officially in the game, if that's what you mean (he would have to pitch to the next batter, I believe).  If it were the third out, I'm not sure if he'd be allowed to be changed out between innings.
Comment: I realize I don't really answer the rest of the questions, and that's because I don't entirely know.  But one interesting detail: technically when you double off someone for not tagging, it is an appeal play, even in the normal sequence of events (i.e., catch the ball in the outfield, then toss to 1st base to double up the player - that is an appeal play).  So that may give weight to P2 being the pitcher of record for those outs.

Appeal play after a pitching change


Problema com calculo no valor total Javascript

Question: Estou com problema pra recalcular o valor do campo OUTROS com o valor TOTAL.
Preciso somar o valor colocado no campo outros na primeira vez, se eu mudar o valor preciso recalcular e somar a diferença: Por exemplo o valor total é 29,00 se eu colocar valor de outros 10,00 fica 39,00 mas se eu mudar pra 20,00 calcular a diferença e chegar no resultado 49,00.
Atualmente meu problema é que está sempre incrementando quando altero o valor do campo outros e somando no total, se eu coloco 10,00 e altero o foco, calcula correto, mas se eu mudo pra 20,00 soma 10,00 + 20,00.
Segue imagem de ilustração e código:

let total  = 0;
$('#valout').on('change', function(){
    let valout = $(this).val();
    let subtot = replaceNumber($('#totalpedido').val());

    if(isNaN(valout)) valout = 0;
    if(isNaN(subtot)) subtot = 0;

    if(valout > 0) {
        $('#valout').data('val-default', valout);
        total   = subtot + valout;
    } else {
        let def = $('#valout').data('val-default');
        total   = subtot - def;
    }

    $('#totalpedido').val(replaceDecimal(total));
});

Comment: Tenta explicar melhor esse problema, divide ele em itens, fiquei bem confuso ao ler.
Comment: Na minha opinião você deveria executar o cálculo em uma função separada, isolar o comportamento de cálculo e após determinada ação você executar essa função, assim tanto na saída do focus quanto no change sempre teriam o mesmo comportamento de executar a mesma função, que sempre estaria fazendo o cálculo desde o início.
Comment: Verifique se essa [resposta](https://pt.stackoverflow.com/questions/357973/erro-ao-atualizar-campos-de-valores-com-jquery/357996#357996) lhe ajuda. Conforme o @FelippeTadeu comentou, seria melhor você separar a função do calculo e chamar conforme os eventos que necessita.
Comment: Editei aqui coloquei um gif, reparem no valor total
Comment: Mas seu gif está tão pequeno e desfocado que nem dá pra ver nada.
Answer: O problema é que você declarou a variável total fora da função. Assim ela sempre irá somar com novos valores ao chamar o evento change. O correto é declarar ela dentro da função para sempre começar com o valor 0 para fazer novos cálculos:
$('#valout').on('change', function(){

    let total  = 0; // DECLARE AQUI

    let valout = $(this).val();
    let subtot = replaceNumber($('#totalpedido').val());

    if(isNaN(valout)) valout = 0;
    if(isNaN(subtot)) subtot = 0;

    if(valout > 0) {
        $('#valout').data('val-default', valout);
        total   = subtot + valout;
    } else {
        let def = $('#valout').data('val-default');
        total   = subtot - def;
    }

    $('#totalpedido').val(replaceDecimal(total));
});

Ou se você quer ela global, declare fora da função mas altere o valor para 0 dentro da função:
let total; // DECLARE AQUI
$('#valout').on('change', function(){

    total = 0; // Altera o valor

    let valout = $(this).val();
    let subtot = replaceNumber($('#totalpedido').val());

    if(isNaN(valout)) valout = 0;
    if(isNaN(subtot)) subtot = 0;

    if(valout > 0) {
        $('#valout').data('val-default', valout);
        total   = subtot + valout;
    } else {
        let def = $('#valout').data('val-default');
        total   = subtot - def;
    }

    $('#totalpedido').val(replaceDecimal(total));
});

Comment: Ainda não consegui resolver isso, tentei fazer dessa forma mas nao obtive sucesso, neste [Link](https://media.giphy.com/media/1esqek5Knxu0vNuGjr/giphy.gif) mostra o problema melhor, sempre que eu colocar m valor no campo outros ele deve zerar e calcular novamente o valor atual ao invés de incrementar


Why is $\beta: \Bbb{C} \to \Bbb{C}$ continuous?

Question: Let $a \in [0, \infty[$. Define
$$\beta: \Bbb{C}\to \Bbb{C}: z \mapsto \begin{cases}z, &|z| \leq a \\  a \operatorname{sign}(z), &|z| > a\end{cases}$$
Why is $\beta$ continuous?
Attempt:
If $a= 0$, then $\beta(z) = 0$, so we may assume $a \neq 0$. Note that if $|z| = a$ we have $a \operatorname{sign}(z) = a z/|z| = z$, so by the pasting lemma it suffices to check that
$$\beta\vert_{\{|z| \geq a\}}, \beta\vert_{\{|z| \leq a\}}$$ are continuous. However, this is trivial. Hence, $\beta$ is continuous.
Is the above correct?
Comment: @mjw (1) It is fairly standard: See Axler's book on measure theory, Donald Cohn's measure theory book, (2) How? (3) https://en.wikipedia.org/wiki/Pasting_lemma
Comment: What is $\mathrm{sign}(z)$ ? Is it $z/|z|$ ?
Comment: @TheSilverDoe Yes, and $0$ if $z = 0$.
Comment: 1.  That's an interesting use of the function "$\text{sign }z$.  2.  Just use the definition of continuity.  Your function satisfies it.  3.  Where is pasting lemma defined?
Comment: Your answer is fine now, and so I have deleted mine.
Comment: @JoséCarlosSantos I do like alternative answers. You can undelete it so I can upvote it :)
Comment: I have undeleted it.
Answer: What you did is fine. Here's an alternative approach.
If $a=0$, then $\beta$ is the null function, which is continuous everywhere.
Assume now that $a\ne0$. Then $\beta$ is continuous at $0$ since, near $0$, $\beta(z)=z$. And, if $z_0\ne0$, $\beta$ is continuous at $z_0$, since $\beta(z)=az|z|^{-1}$ which, outside $0$, is the product of continuous functions. In particular, $\beta$ is continuous at $z_0$.
Comment: But is my approach correct as well?
Comment: No. What do $z\geqslant a$ and $z\leqslant a$ mean?
Comment: The modulus was missing. Edited.
Answer: Your approach is a good one, although I wouldn't say: "However, this is trivial" at the place that you did. The reason is that your presentation is a bit unclear, i.e. you didn't explain what's the point of checking that $z = a\operatorname{sign}{z}$ for $|z| = a$.
What I would add is that it shows that the formula $\beta(z) = a\operatorname{sign}{z}$ is valid even for $|z|\geq a$, and not just $|z|>a$. Also, I would add why these restrictions are continuous: the identity is obvious, while the other restriction is a product of continuous functions.
Finally, $\mathbb C$ is the union of the two closed subsets on which $\beta$ is continuous when restricted to and therefore, the pasting lemma applies.
Comment: Thank you for this perfect response!


Exclude methods from code coverage with Cobertura

Question: Is there a way to exclude code from inclusion into Cobertura coverage reports? We have some methods that should not be included in the coverage report and therefore not drive down the coverage numbers.
I know that Clover has such a functionality, but I have not found anything similar for Cobertura.
Comment: Hopefully, it's coming soon. Issue: http://sourceforge.net/tracker/?func=detail&atid=720017&aid=3010530&group_id=130558 and conversation about a release to include this http://sourceforge.net/mailarchive/forum.php?thread_name=0F4966F4B6F55240A08C5F9AD979B3BE07E7EFB3%40MERCMBX16D.na.SAS.com&forum_name=cobertura-devel
Comment: See [this post](http://stackoverflow.com/questions/8848585/excluding-java-files-in-sonar-report-through-jenkins/13003357#13003357), This is a option for exclude code of cobertura with sonar and jenkins but I hope that its answer can apply for non jenkins projects
Answer: You can exclude classes from instrumentation. Then they should not appear on reports. See exclude statements below.
You can also ignore calls to some methods. See ignore statement below.
If you are using maven, see maven plugin manual.
    <configuration>
      <instrumentation>
        <ignores>
          <ignore>com.example.boringcode.*</ignore>
        </ignores>
        <excludes>
          <exclude>com/example/dullcode/**/*.class</exclude>
          <exclude>com/example/**/*Test.class</exclude>
        </excludes>
      </instrumentation>
    </configuration>

And for ant see this.
<cobertura-instrument todir="${instrumented.dir}">
  <ignore regex="org.apache.log4j.*" />
  <fileset dir="${classes.dir}">
    <include name="**/*.class" />
    <exclude name="**/*Test.class" />
  </fileset>
  <fileset dir="${jars.dir}">
    <include name="my-simple-plugin.jar" />
  </fileset>
</cobertura-instrument>

Comment: Has anyone confirmed whether the instructions on the plugin actually work?  I tried a few different settings and I couldn't get the exclusions to work correctly.
Comment: Thanks. Is there anything that can be added to the code to exclude a method? Would be easier than a long long list in ANT. Any annotation support?
Comment: I made a very quick search to Cobertura docs, but I couldn't find anyting about Cobertura's annotations. So it seems you need to work on your unit-tests or package structure to make your exclude lists shorter ;)
Comment: Ok, that confirms, that I have not missed anything. Hope for a hidden feature... well, maybe we get one sooner or later. Thanks!
Comment: Anywhere, is there a reference , to how the regulare expressions need to be deviced??Basically , any reference on how different regular expressions will behave
Comment: There's a bug in the exclusion of classes. See here: http://jira.codehaus.org/browse/MCOBERTURA-52
Comment: The answer is really helpful, but you should edit the post in order to say that the maven part goes in the plugin section and no reporting. I did not check the link until I read this answer http://stackoverflow.com/a/6815777/3294286
Answer: This has been breaking my head for some time now.
My problem was that I had the cobertura maven plugin setup in the reporting section instead of the build section.
The instrumentation settings, and hence the excluding of classes or packages, won't be applied if you don't set it up on build section, so watch out for this.
Comment: can you provide an example?
Comment: This is the right answer!  I was banging my head against this too putting it in the  section of a Maven 3.0.4 pom.
Answer: Remember to exclude inner classes too.
<exclude>path/to/class/MyClass*.class</exclude>

It took me ages to notice I was missing an asterisk!
Comment: Found this to be the most useful answer! Apparently the star before the dot is essential for this to work. Thanks!
Answer: Cobertura doesn't currently provide such a feature, and neither does Emma (which we use) although it is listed as a forthcoming enhancement - although in the form of an extension to the exclusion rules I believe rather than as an annotation.
Would be handy to cover off those few inaccessible corners cleanly so that you can strive for 100% without being ridiculous.
I think annotations would probably be a friendlier way to do it, but they ought to be fairly explicitly named and based on a list of acceptable scenarios as I fear otherwise something like '@ExcludeFromCoverage' would get added over generously.
Comment: actually the question is about excluding methods, not classes, and this answer is correct that its impossible right now.
Comment: -1 because it is incorrect to write "cobertura doesn't currently provide such a feature". It does, according to the accepted answer.
Comment: @Jason, see my answer, maybe you are doing the same mistake I was.
Comment: Edited the question title to avoid the confusion. This answer is correct btw,as @MateuszChromiński said
Answer: Since 2.0 you can write your own @CoverageIgnore annotation.
It will be recognized by Cobertura, which will avoid considering annotated methods (does not work on classes as far as I know).

Create an empty annotation:

public @interface CoverageIgnore {}

Then annotate the methods you want to exclude from the reports:

public class SomeClass {
    @CoverageIgnore
    public void foo(String baz) {
        // useless stuff
    }
}

Source: https://github.com/cobertura/cobertura/wiki/Coverage-Annotations
Comment: Missing one critical piece: adding the annotation to the cobertura-instrument task:


Update varios registros de uma vez laravel

Question: Olá,
Tenho uma tabela com os seguintes campos:KEY, VALUE , ALIAS, CLIENT_ID.
Em determinado processo do sistema eu preciso fazer o update do Key e o Value.
Para fazer o update em apensa um registro eu não tenho problemas, o problema é que quando eu preciso alterar duas KEYS e dois VALUES de um client ID eu estou usando a função update do laravel/repositories, então o codigo ficou assim:
 public function update(Request $request, $id)
 {
    $this->client->update($request->all(), $id);
 }

O problema é que com esse metodo se eu tiver 2 values e 2 keys, ele sobrepõe a primeira então o que eu recebo é apenas
request = [ key => 'segundo valor do form', value => 'segundo valor do form'];

Eu preciso que venham as 2 keys e os 2 values. Alguem pode ajudar?
Comment: Tá usando Repository?  2 values e 2 keys vindas do input? só se for com `array`. Assim `key[] =1&key[]=2`
Comment: Fiz com repository porque é o unico jeito que eu sei fazer, mas se tiver outro modo, sem usar o repository, eu posso/consigo usar.
Comment: Eu só uso o Laravel sem Repository. Respository é para algo bem específico, como por exemplo, a necessidade de mudar o seu Orm. Acho que o ORM do Laravel já é bastante potente.
Comment: Como ficaria o update usando o ORM ?
Comment: Esse método na verdade é do Controller, né? Porque tá passando `Request`. Na verdade, você precisa explicar como vai vir dois valores em Keys e Values. Isso vem do formulário?
Comment: O update normal do ORM é `Cliente::where(['id' => $id])->update(['nome' => 'Nome', ' endereco' => 'Rua blablala'])`.
Comment: O formulario esta construido assim: {!! Form::open(array('method'=>'put', 'url' => url())) !!}                                                                        @foreach()

{!! Form::hidden('key', $key) !!}
 {!! Form::text('value', '')) !!}
 submit
 @endforeach
{!! Form::close() !!}
Comment: @IvanMoreira você pode nos explicar melhor o seu problema? você quer atualizar várias linhas do seu banco de dados certo? então você está recebendo mais de um id ou eu entendi o problema errado? adicione mais detalhes e código por favor.
Comment: @RafaelBerro O problema ja foi solucionado, eu utilizei a reposta abaixo e fiz um foreach no controller para receber 1 ou mais chaves.
Comment: @IvanMoreira Ótimo, você deve seleciona-la como a solução para a sua questão.
Answer: Para você enviar um formulário com múltiplos valores, você precisa escrevê-lo da seguinte forma, para facilitar a alocação dos dados:
{!! Form::open(array('method'=>'put', 'url' => url())) !!}

 @foreach($array as $key)
        {!! Form::text("clientes[$key][nome]", '')) !!}
        {!! Form::text("clientes[$key][endereco]", '')) !!}
        {!! Form::submit('Submit') !!}
 @endforeach
{!! Form::close() !

!}
No método responsável pelo salvamento dos dados, você poderia fazer assim:
foreach  ($request->clientes as $id_key => $dados) {
    Cliente::where(['id' => $id_key])->update($dados);
}

Note que a forma que eu declarei o name dos inputs acima, fará com que o PHP gere um array assim:
[
    1 => ['nome' => 'Padaria Xodó', 'endereco' => 'Av Um - 155'],
    2 => ['nome' => 'Locadora Zezé', 'endereco' => 'Av Dois - 300']
]

Assim, internamente, no foreach, você sempre atualizará os dados de acordo com o id, que é o índice do nosso array.
Comment: Desse jeito, ele diz que o ->update($dados) é uma string e ele tem que receber um array
Comment: Eu particularmente selecionaria todos os clientes em uma única querie. Por exemplo, Cliente::whereIn('id', array_keys($request->get('clientes')));.


Using Jabber to send network messages

Question: We have a requirement to send desktop alerts to various users (compliance, production) across a network when other users have submitted content online for a report.
At present we are using NET SEND but this has no guarantee of delivery and has proved unreliable from both client and server perspective (and I gather will be unsupported in later versions of Windows; we are currently running XP).
We are considering a Jabber-based solution but has anyone used a Jabber client to pop up alert messages on the screen like NET SEND does, as opposed to just bringing a chat window to the front or displaying a temporary 'toast' message near the system tray.
We need the alert message to be persistent and only dismissed by the user, indicating they have seen it. Toast-style pop-ups would be fine as long as it was not only for a limited time and again had to be dismissed by the user.
Any solutions?
Answer: We have something similar in house.  We use the Miranda IM client with the notifyanything and popup plugins.
Notifyanything allows the client to receive udp messages on a specified port.
Popup does just that, displays the message in the window at the top of the users screen.
In our case, everything is on the internal network, so loss of UPD packets is not a concern.
Here is an example of the python script we run to send the udp messages from the servers to the users:
<code>#!/usr/bin/python

import socket, sys

hosts = (
  ('10.0.0.1',  15000),
  ('10.0.0.2',  15000),
  ('10.0.0.3',  15000),
)

def send(txt):
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  for h,p in hosts:
    s.sendto(txt, 0, (h,p))
  del s

if len(sys.argv) > 1:
  s = "\n".join(sys.argv[-2:])
  send(s)
</code>
Comment: I'm going to accept this answer as it looks like Miranda might have the features we need, without too much additional development time. Thanks.
Answer: I came across this exact issue. The goal was to deliver each alert along an escalation pathway - sending the alert to the next person in the list if it was not acknowledged in a given timeframe. We determined that Jabber was the best solution, but that to do it right we had to extend the protocol or investigate more clients. (The protocol lends itself very well to extension and there are countless clients available). This catch was because it was frequently desirable to acknowledge some alerts but not others.
For example. An alert's ultimate path:

Send to admin A via Jabber.
No acknowledgement after 5 minutes, sent to admin B via Jabber.
No acknowledgement after 5 minutes, sent to admin A via SMS.
No acknowledgement after 5 minutes, sent to admin B via SMS.
No acknowledgement after 5 minutes, sent to admin A and B's manager via Jabber.
No acknowledgement after 5 minutes, sent to admin A and B's manager via SMS.
Manager evaluates the alert, acknowledge it or phones admin A or B.

The catch is that if a second alert is generated in the middle of this process, admin A or B may wish to acknowledge it, but not acknowledge the first alert. For example, if they're busy with a separate issue that generated the other alert, or if they're not near a computer, know that the second alert is not serious, but that the first alert needs to be handled by someone near a computer and the escalation mechanism is the most efficient way to find the right person.
There were two types of message delivery in Jabber. (I believe called normal vs chat) It's possible that one of the two types allowed a differentiation in which message was responded to. Unfortunately, the messaging type that might have allowed for this caused extreme inconvenience with the clients we tested if a large flood of messages were received. (Also I'm not sure whether the people testing determined whether it was possible to indeed differentiate what was being responded to, due to this issue overwhelming the testing).
As it was exploratory and we didn't really have time to implement a full solution, we didn't determine whether the problem was just choosing a better client or whether extensions to the protocol were necessary. I still think Jabber is the best method to deliver alerts. For any alert delivery/escalation system, a person who acknowledges an alert should take ownership of the alert, and there should be repercussions for everyone failing to acknowledge an alert. This has to work with the system understanding the best way to reach a person, an on-call rotation, the risk of alert floods, the issue of alerts created by a person who is currently out of the rotation, and any political considerations caused by an alerting system that accidentally creates accountability if the existing system has none.
Answer: I'm sorry this isn't an exact answer to your question (about Jabber), but you might want to check out ReachAlert.
http://www.tekalign.com/
This would stop people from corrupting your jabber implementation since they could decide to use it for something else (chatting, sending messages to other users).
I also agree about net send. It's going away and is common practice to disable it since it was abused for spamming.
Let me know what you think and how it goes ;-)
Comment: Thanks for that; Jabber was only our initial thought and this might be another solution worth considering. Will speak to the developers and report back. Cheers.
Answer: This may be a better question to ask over at Stackoverflow, but it does look like there are python and perl libraries for Jabber, so this should be possible.
http://jabberpy.sourceforge.net/
http://search.cpan.org/~reatmon/Net-Jabber-2.0/lib/Net/Jabber.pm
Comment: Good idea, have done so:

http://stackoverflow.com/questions/950371/using-jabber-to-send-network-messages/952760
Answer: Have used PSI jabber client. It has popup notifications along with sound notifications.
Same goes for JAJC jabber client.
Answer: I think this can achieved trought a monitoring solution like ZAbbix, you can trigger an action upon any remote events by remote scripting, once the action has been triggered Zabbix can do escalations. Actions can be running remote script, sending email or alerts via jabber until the trigger is acknoledged.

Using Jabber to send network messages


Organic Groups "create post" content link needed with posting content type specific to group

Question: Organic groups  7.x-2.6
Entity reference prepopulate    7.x-1.5
Hello, I am trying to create custom "create posting" link for my organic groups. Each Organic Group has its own content posting content types, so when a user visits the panel page for that group the add posting link should be specific to that group.
I have 2 groups: Amigo group, and Authenticated group
I read that target bundles are globally defined for Groups Audience, so I read that you have to add an extra group audience to the Posting content type for your group.  You are then supposed to set the target bundle on the 2nd to match the group content type.
My problem is that when I try to set the "Content Create Links" section in my panel it wants to only set one group audience field, and I have 2 created, one for each group's posting content type.
I recorded images of each part of this problem for ease of understanding.
Here is my Amigo group's posting content type called "Amigo Group Post".
Notice the extra Group's Audience field added to the bottom of the content type. Clicking edit on this allows us to change the settings on this field

Clicking on group audience for Amigo Post takes us to that group audiences configuration page.  Here I am choosing to prepopulate the entity reference.

Here is my panel  for the Organic Groups group. Lets go to the Content Create Links setting page.

Here you can set ONE of the 2 posting content types to be the content type used for new group postings, but I need it to just choose the posting content type by the type of Organic Group. I chose one because I could only choose one.

Looking at the Amigo group page we can see that the create post section is not even showing up.

This is the Authenticated group page.  When viewing this page we do see the create post section, because we had to set one field name for the "content create links" section in the Panel.

Does anyone have any idea how to have the panel choose the content creation link type based on the current group?
Answer: I solved this problem. I am not sure if this is the best way. If a better way exists, please do inform me.
To solve this problem I create 2 "Content Create Links" panels within the page.  Each added panel references the group audience specific for the Group Posting content type for the group.
At first both will probably show up, but you have to go to the global "OG Permissions Overview" and for each group type make sure that create content for that Groups posting content type is checked.  For all other type on the page you should not have "Create ____ Content" checked otherwise that content type (a posting type) will also show up as a "Content Create Links" for the wrong posting type for that group.
Do that for each Group type you have created, allowing "Create__(groups post content type) Content" and not having the "Create__(other groups post content type)__ content" for all other group posting content types for the other groups.
Now when I open up "Amigos" groups, I only get "Amigo Group Post" as the posting content type, and NOT "Authenticated Group Post" as well.
If this is too "hacky" I welcome other suggestions on how to configure this properly.
Answer: You can also build these custom links yourself, and use an argument, context or php to fill in the group id.
The url would be like Post content of type to group.
This way you can create those content urls everywhere, in blocks, pages, content, views, etc. If you do not hardcode the groupid, but fetch it from context (which is added to grouppages) you can have those kind of links on all your group subpages.
Comment: Hello, my solution that I posted does not seem to be working. Can you elaborate more on how to get just the content type for the particular group that is being shown in the panel?  I'm working in a panel and adding custom content to the panel content which allows me to manually create a link like you showed, but I'm not sure how to get the groupid...I'm assuming through the panel context, but I'm very new with panels and would value a walkthrough.
Comment: Turns out my solution does work, but if you are logged in as an administrator it shows all of the Content create links and does not filter based on the current group.  I'm still interested in experimenting with your solution...
Answer: If you are not using panels module, then install og_extras since it will create a block with all the correct links for posting content. All you need to then do is also enable the block. To quote from og_extras module page:

Extra functions, blocks, and views for Organic Groups 7.2. In
  particular, this module adds views and blocks needed by sites that are
  not using Panels, although it also may be useful to sites that do use
  Panels. This module is for Organic Groups 7.2. It will not work with
  Organic Groups 7.1.


Find critical points & bifurcation points of ODE

Question: I'm trying to find the critical points & bifurcation point to the ODE:
$$ \dot{x} = f(x;\beta)=2-\beta e^{-x^2}$$
By letting $f(x;\beta) = 0$, I found the critical points are at $x=\pm\sqrt{-ln\frac{2}{\beta}}$  (Also, I'm unsure if $x=0$ is a critical point.
Since the bifurcation point will be found when $f'(x;\beta)$ is also $0$, I'm trying to substitute x into $f'(x;\beta)$ to find $\beta$, yet I always end up with 4 = 0 which is absurd.
Can anyone help me with this? Thank you!
Answer: First of all: I don't see an ODE. Note that for $\beta < 2$ you have no (real) critical points, if $\beta = 2$ you have one and for $\beta >2$ you have two critical points. Thus, your bifurcation point might be $(x_0,\beta_0) = (0,2)$.
Now check that $\frac{\partial}{\partial x}f(0,2)=0$, $\frac{\partial}{\partial \beta}f(0,2) \neq 0$ and $\frac{\partial^2}{\partial x^2}f(0,2) \neq 0$.
Having this checked, you know that your vector field undergoes a saddle node bifurcation and the bifurcation point is $(0,2)$.
EDIT: Your critical set is a bit strange. $x=0$ can't be a critical point, you have to look for pairs $(x_0, \beta_0)$. As said before, $x=0$ is no critical point, but $(0,2)$ is. So your critical set is given by
$\{(x,\beta) \in \mathbb R^2~|~ x= \pm\sqrt{-\ln\frac{2}{\beta}} \}$.


How to debug nodejs.ECONNRESETError: socket hang up

Question: when I send a form with large amount of data file, socket will be abruptly closed by remote server. That's maybe why I got an error of ECONNRESET. How to solve it?
my nodejs code:
Promise((resolve, reject) => {
  let sendOption = {
    method: 'post',
    host: host,
    port: port,
    path: path,
    headers: form.getHeaders(),
    timeout: options.maxTimeout ? 1 * 60 * 60 * 1000 : 2 * 60 * 1000,
  }
  if (options.userName && options.passWord) {
    let auth = new Buffer(options.userName + ':' + options.passWord).toString('base64');
    sendOption.Authorization = 'Basic ' + auth;
  }
  let request = http.request(sendOption, (res) => {
    let body = ''
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end', () => {
      resolve(JSON.parse(body))
    })
  });
  request.on('error', (err) => reject(err));
  request.write(form.getBuffer());
  request.end();
})

Full error:
2020-02-17 19:09:25,570 ERROR 18664 [-/::1/-/14867ms POST /thirdPartUpload] nodejs.ECONNRESETError: socket hang up
    at connResetException (internal/errors.js:570:14)
    at Socket.socketOnEnd (_http_client.js:440:23)
    at Socket.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
code: "ECONNRESET"
name: "ECONNRESETError"
pid: 18664
hostname: PC-HZ20139584
    enter code here

Comment: check if this helps https://stackoverflow.com/questions/16995184/nodejs-what-does-socket-hang-up-actually-mean
Comment: @properchels I tried all methods Error is still there.
Answer: POST requests need Content-Length: headers declaring the length of their bodies. In your case you send your POST's body with request.write(form.getBuffer());
An absent or wrong Content-Length: header can look to a server like an attempt to exploit a vulnerability. So servers slam the door (abruptly close the connection) on those requests, which shows up in your client as ECONNRESET.
Try something like this.
const buff = form.getBuffer();
request.setHeader('Content-Length', buff.length);
request.write(buff);


Como contar itens iguais de 5 colunas diferentes?

Question: Tenho uma tabela assim. A tabela guarda o registro de presenças ( P) e faltas ( F). Preciso contar, por exemplo, quantas presenças e quantas faltas um determinado código tem.
Comment: Você passou também o idUsuario em questão? Você poderia fazer assim oh... presenca -> id, idUsuario, dia, presenca ... dessa forma, cada vez que tiver presença confirmada, registra no banco de dados, e você apenas faz um group by idUsuario e um where presenca = 1 (presente) 2 (faltou) e consegue saber a quantidade...
Comment: Esta tabela monitora apenas usa semana? de cinco dias? ou você quer monitorar o mes todo?
Answer: Eu faria da seguinte forma:
Estrutura da tabela.
CREATE TABLE IF NOT EXISTS `frequencia` (
  `idFrequencia` int(10) NOT NULL AUTO_INCREMENT,
  `idUsuario` int(10) NOT NULL,
  `diaSemana` int(10) NOT NULL,
  `presenca` int(10) NOT NULL,
  PRIMARY KEY (`idFrequencia`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `frequencia`
(`idFrequencia`, `idUsuario`, `diaSemana`, `presenca`)
VALUES
(1, 1, 1, 1),
(2, 1, 2, 1),
(3, 1, 3, 2),
(4, 1, 4, 2),
(5, 1, 5, 1);

E então faria um SQL:
SELECT count(idFrequencia) as qtdFalta FROM frequencia WHERE idUSuario = '1' GROUP BY presenca = '2';

Para conseguir saber os resultados. É uma opção!


WP8 create xml file c#

Question: I am trying to create xml file like below
        <IMEI>ABCD</IMEI>
        <Manufacturer>Nokia</Manufacturer>
        <Model>Lumia 525</Model>
        <Items>
           <Item>
                <Name>Contact</Name>
                <Size>
                    <Value>123</Value>
                    <Type>KB</Type>
                </Size>
                <MD5>78sd8f6sd6fsdf8sdbs5f78svbfsd576s</ MD5>
                <Desc>Contact is added</ Desc >
           </Item>
        </Items>

I have tried something like this
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));

doc.Add(new XElement(("IMEI"), "ABCD"));
doc.Add(new XElement("Manufacturer"), "Nokia");
doc.Add(new XElement("Model"), "Lumia 525");
var contactsElement = new XElement("Item",
                        new XElement("Name", "Contact"),
                        new XElement("Size",
                            new XElement("Value", "123"),
                            new XElement("Type", "KB")),
                       new XElement("MD5", "78sd8f6sd6fsdf8sdbs5f78svbfsd576s"),
                       new XElement("Desc", "Contact File"));
var mainNode = new XElement("Items", new XElement(contactsElement));
doc.Root.Add(mainNode);

But not getting correct file. I also want to append new Item in Items node. How can I append when I get new item?
Answer:
Your XML is invalid as posted. It should have single root element to be a valid XML.
The way your code adds new element is wrong. It will add two nodes instead of one : one empty xml element node, and a text node.

You can try this way to generate correctly formatted XML :
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                                        new XElement("Root"));
doc.Root.Add(new XElement("IMEI", "ABCD"));
doc.Root.Add(new XElement("Manufacturer", "Nokia"));
doc.Root.Add(new XElement("Model", "Lumia 525"));
var contactsElement = new XElement("Item",
                                    new XElement("Name", "Contact"),
                                    new XElement("Size",
                                        new XElement("Value", "123"),
                                        new XElement("Type", "KB")),
                                    new XElement("MD5", "78sd8f6sd6fsdf8sdbs5f78svbfsd576s"),
                                    new XElement("Desc", "Contact File"));
var mainNode = new XElement("Items", new XElement(contactsElement));
doc.Root.Add(mainNode);

And for adding new Item within Items element later :
//get existing <Items> element
var items = doc.Root.Element("Items");
//add new <Item> to <Items>
items.Add(XElement.Parse(newContactsElement));
//then save the XDocument back replacing previously saved XML

Comment: Thank you for reply. Is it not possible to add data with out `Root` node?
Comment: Not possible. As mentioned above, that will results an invalid XML markup. Invalid XML can't be loaded to most XML abstraction classes (such as `XDocument`, `XmlDocument`, `XElement`, etc.). You'll end up treating the "XML" as plain string, which is painful.

WP8 create xml file c#


Interpretation of Coefficients in linear regression using 'fitlm'

Question: I require help with regards to the interpretation of linear regression results (I'm using the Matlab 'fitlm' function).
My data has 8 features, and when each feature is plotted against the response variable there are some obvious relationships (see figure below).

From looking at this plot I would expect features x4, x5, x6, and x7 to all have negative coefficients, and probably x8 to have a positive coefficient.
When I execute the following code:
mdl = fitlm(features,y,'linear','RobustOpts','on')

I get the following output:
                  Estimate        SE        tStat        pValue
(Intercept)         3.1936    0.038772      82.368    3.9862e-95
x1             -0.021465    0.040015    -0.53643       0.59283
x2              0.012444    0.018055     0.68919       0.49227
x3              0.014156    0.031247     0.45305       0.65148
x4               0.25286     0.09546      2.6488     0.0093614
x5                 2.378      1.2857      1.8496      0.067274
x6               -2.0413     0.25464     -8.0164     1.882e-12
x7               -1.7374      1.0649     -1.6314       0.10588
x8              -0.17522    0.031894      -5.494    2.9021e-07

which seems a bit counter-intuitive, since the coefficients of some of the features (i.e. the gradients of x4 and x5) are positive when I would expect them to be negative.
The model reports a low RMSE and a very high R-squared of 0.969, which suggests a very good fit. The pValues are quite low as well, which suggests that the features with the unusual gradients are statistically significant.
I'm wondering why this is the case and how can I interpret these results?
Answer: This could happen if there is correlation among the X variables. For instance, if X4 and X6 are highly correlated, then perhaps the effect of X4 on the response after adjusting for X6 is positive, even if the correlation between X4 and Y is negative.
I believe you can use something like
plotAdded(mdl,'x4')

to look at the relationship between X4 and Y after adjusting for the other predictors.


AWS event for S3 bucket creation

Question: How do I run a lambda upon new bucket creation? I looked at supported S3 event types but couldn't find one for BucketCreated or equivalent.
Can CloudWatch help in this case?
Comment: Note that you may be going in a bad design direction if you have a need for an event on bucket creation.  [*"Amazon S3 is focused on get, put, list, and delete operations. Because bucket operations work against a centralized, global resource space, it is not appropriate to create or delete buckets on the high-availability code path of your application. It is better to create or delete buckets in a separate initialization or setup routine that you run less often."*](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html)
Comment: @Michael-sqlbot the consumption of the event is not in a critical functional path; it is for security monitoring and enforcement purposes
Answer: You can combine CloudTrail with CloudWatch to create an Event when a new S3 bucket is created. This example describes exactly that: CloudWatch Event Examples (down the bottom under Events for Services Not Listed).
Hope that helps :)
Comment: Thanks. I'll give this a spin shortly and confirm.

AWS event for S3 bucket creation


Countable vs Uncountable Intersection

Question: I have a specific question regarding the difference between countable and uncountable intersection. Specifically, let $B(x,r)$ be the open ball centered at $x\in \mathbb{C}$ of radius $r>0$. It is clear that
$$\bigcap_{\theta\in \mathbb{R}}B(e^{2\pi i\theta},1.5)=B(0,0.5).$$
However, does
$$\bigcap_{\theta\in \mathbb{Q}}B(e^{2\pi i\theta},1.5)=B(0,0.5)?$$
Comment: This is not _really_ about the difference between countable and uncountable, but rather about dense versus everywhere.
Comment: @Arthur Fair enough, I see that.
Comment: This is not about convex analysis.
Answer: Consider the point $0.5e^{2\pi i\sqrt{1/2}}$. In the intersection $$\bigcap_{\theta\in \mathbb{R}}B(e^{2\pi i\theta},1.5).$$This point lies outside $B(e^{-2\pi i\sqrt{1/2}})$, and thus is not contained in the intersection. This is exactly as you say, as that point lies on the boundary of the open ball $B(0,0.5)$.
However, which open ball would exclude it from $$\bigcap_{\theta\in \mathbb{Q}}B(e^{2\pi i\theta},1.5)?$$The answer is, there is no such ball.
The end result for the $\Bbb Q$-intersection is, you get $B(0,0.5)$, along with any point on the boundary with irrational-multiple-of-$\pi$ argument (technically any point on the boundary opposite an irrational-multiple-of-$\pi$, which in this case is the same thing, but for other dense sets the distinction might matter).
As a similar example, to illustrate better that this isn't about countability, if you instead intersect over $\theta\in(\Bbb R\setminus\Bbb Q)$, then what you get is $B(0,0.5)$ along with all rational points on the boundary.

Countable vs Uncountable Intersection


Cant Balance A motor bike In unity

Question: I want to balance a motorbike with unity physics. We can balance balance bike by freezing rotation on z axis but doesnot seem good .So far i tried this .This method balances bike for few second but some reason bike start jumping in air or sometime flips over .I am open to any suggestions.I have made some 2d non physics games but unity physics is new to me.
enter image description here
enter image description here
enter image description here
Comment: Sorry but stackoverflow isn't intended to solve game logic issues. Perhaps this is appropriate for https://gamedev.stackexchange.com/

Also, please copy/paste your code instead of using image links as it's much more difficult to follow.

If you have a specific syntax error or technical issue that is reproducible then please update with details. Thank you
Comment: Did you find an answer to this question? If mine was helpful, please consider [accepting it](https://meta.stackexchange.com/a/5235/405359) to give me some reputation points and help others browsing the search panel that there is a helpful answer here.
Answer: First, I would stop changing the bike's center of mass.
Then, I would use the bike's up to calculate a torque to apply. Explanation in comments:
<code>float adjustFactor = 0.5f; // this value requires tuning

// physics actions should occur in FixedUpdate in most cases
void FixedUpdate()
{
    // project the bike's local up to the plane perpendicular to the bike's forward
    Vector3 projectedUp = transform.up - Vector3.Dot(transform.forward, _transform.up);

    // find the angle from that projection to global up, around bike forward
    float upOffset = Vector3.SignedAngle(projectedUp, Vector3.up, transform.forward);

    // use angle difference to calculate an adjustment
    float adjustment = upOffset * adjustFactor;

    // maybe do something else like adjustment = log(adjustment) or adjustment^2
    //   to change easing of adjustment force. Requires some trial and error
    //   and further tuning of adjustFactor.

    // Apply adjustment as vector around rb's forward
    _rigidbody.AddRelativeTorque(new Vector3(0f, 0f, adjustment));
}
</code>
Related answer: Stabilize hovercraft rigidbody upright using torque

Cant Balance A motor bike In unity


socket communication between two device under sub-Lan

Question: For two device both has public IP address, we can use socket IP and port to setup socket communication.
If both device do not has public IP but connect to sub-Lan then access public network through router (no port mapping in router), how can this two device setup socket connection?

For example in above diagram, how can machine A communicate with machine C?
Answer: Assuming that you have not set up a VPN tunnel between the two routers that connects both branches of the 192.168.1.0/24 network then the answer is: you can't.
If you set up a VPN tunnel then each side of the 192.168.1.0/24 network will be able to see the other side. Please note that the routers will need to be able to do ARP spoofing, i.e. the router for A & B will need to be able to spoof the MAC for C, i.e. intercept IP packages for C on their LAN and forward them through to the VPN to the other network half where they are delivered to C.
If you set up at least one port forwarding on one router, then you'll have other options, e.g. an SSH tunnel on C that connects to the port forward on either A & B. You can then use the -L option on C to setup port forwarding through the SSH tunnel to the other half of the network.


Approximate / Standardize value in certain range

Question: I have table with numeric values like
<code>-1       0       1
0,7     0,19    0,11
0,06    0,15    0,79
0,17    0,18    0,65
0,15    0,48    0,37
0,04    0,28    0,58
0,57    0,02    0,41
0,17    0,69    0,14
</code>
Suppose values are the probability of occurence of the specific class, hence, in first row the -1 class is likely to occur while other two won't.
Each row has one major number in one column (that basically indicates what class is likely to occur. -1 for first row, 1 for second, 1 for third etc.). What I want to get is get one single number normalized across row and approximated to the column header. Like, the higher the number in column the closer it to column header.
Basically, if major number is in the first column, there must be negative number closer to -1, in second - closer to +1, in last - closer to 0.
Example of resulted column:
<code> -1      0       1        result
0,7     0,19    0,11       -0.68
0,06    0,15    0,79        0.75
0,17    0,18    0,65        0.58
0,15    0,48    0,37        0.25
0,04    0,28    0,58        0.42
0,57    0,02    0,41       -0.41
0,17    0,69    0,14        0.15
</code>
I tried to do row-wise normalization but it obviously does not approximates the number to the column header.
Answer: Looks like you might want a weighted mean, the column names are the values, the probabilities are the weights.
<code>df=read.table(text="
-1       0       1
0,7     0,19    0,11
0,06    0,15    0,79
0,17    0,18    0,65
0,15    0,48    0,37
0,04    0,28    0,58
0,57    0,02    0,41
0,17    0,69    0,14",h=T,dec=",")

apply(df,1,function(x){
  weighted.mean(c(-1,0,1),x)
})

[1] -0.59  0.73  0.48  0.22  0.60 -0.16 -0.03
</code>


mysql - linha para colunas gravity forms

Question: Boa tarde,
Sou bem iniciante em banco de dados e programação, mas gosto de mexer quando é necessário. Tenho uma tabela no banco de dados com respostas de um formulário feito no wordpress pelo gravity forms que apresenta as respostas em linha de tal modo que:

id  lead_id field_number    value
1   1       1               título1
2   1       2               descrição1
3   1       3               movimento1
4   1       4               status1
5   1       5               lat1
6   1       6               long1
7   1       7               nome1
8   1       8               email1
9   2       1               titulo2
10  2       2               descrição2
11  2       3               movimento2
12  2       4               status2
13  2       5               lat2
14  2       6               long2
13  2       7               nome2
14  2       8               email2

Sendo que lead_id é o identificador das respostas do formulário feita por cada usuário, field_number o identificador de cada pergunta em cada formulário e value é a resposta dada a cada pergunta.
Tentei já transformar as respostas para do formulário em uma nova tabela, mas quando elas fossem editadas no wordpress as respostas não seriam atualizadas. Quero minha visualização final dentro do banco de dados em uma nova tabela que será em colunas ao invés de linhas, dessa maneira:

lead_id titulo  descricao   movimento   status  lat     long    nome    email
1       titulo1 descricao1  movimento1  status1 lat1    long1   nome1   email1
2       titulo2 descricao2  movimento2  status2 lat2    long2   nome2   email2

Tentei diversas respostas aqui com tópicos semelhantes, mas não consigo ir muito longe, sempre dando erro. Vale lembrar que a nova tabela precisa ser dinâmica, já que a tabela do formulário irá crescer conforme as respostas. Alguma boa alma poderia ajudar?
Obrigado.
Answer: Consegui resolver a partir dessa pergunta feita na plataforma em inglês.
https://stackoverflow.com/questions/19007699/mysql-rows-to-columns/37828455#37828455
no meu caso adaptei para o seguinte código

SELECT lead_id,
MAX(CASE WHEN field_number =1 THEN value END )  titulo,
MAX(CASE WHEN field_number =2 THEN value END )  descricao,
MAX(CASE WHEN field_number =3 THEN value END )  movimento,
MAX(CASE WHEN field_number =4 THEN value END )  status,
MAX(CASE WHEN field_number =5 THEN value END )  lat,
MAX(CASE WHEN field_number =6 THEN value END )  long,
MAX(CASE WHEN field_number =7 THEN value END )  nome,
MAX(CASE WHEN field_number =8 THEN value END )  email
FROM or1_rg_lead_detail
GROUP BY lead_id


Deep level recursion with Elixir

Question: I am working on a file system seaweedfs. and we have saved files on it with proper directory structures as server/camera_id/snapshots/recordings/year
I am trying to delete the empty folders beneath years.
def clean do
  cameras =
    Camera
    |> preload(:owner)
    |> order_by(desc: :created_at)
    |> Evercam.Repo.all()

  years = ["2015", "2016", "2017", "2018", "2019"]
  servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.each(cameras, fn camera ->
    Enum.each(servers, fn server ->
      type = seaweefs_type(server)
      attribute = seaweedfs_attribute(server)
      url = server <> "/#{camera.exid}/snapshots/recordings/"

      Enum.each(years, fn year ->
        final_url = url <> year <> "/"
        request_from_seaweedfs(final_url, type, attribute)
      end)
    end)
  end)
end

when the final request goes for a year in request_from_seaweedfs(final_url, type, attribute)
it either gives a list like this, ["01", "02", "03"] or it gives []
in case of [] I am just deleting the full tree as
url = server/gaol-yard/snapshots/recordings/2016/?recursive=true
hackney = [pool: :seaweedfs_download_pool, recv_timeout: 30_000]
HTTPoison.delete!("#{url}?recursive=true", [], hackney: hackney)

But I want to go deeper than that, if the result is not [], then I want to go into months such as
months = ["01", "02", "03"]
final_url = url <> year <> "/" <> "{moth value from the list}"
for each month, there are consecutive days, and then for days there are hours,
I want to check all this with recursion, such as delete a tree if the last level or any level is empty,
Such as if a camera has, year, months, days and hours but in the last level if the hour gives [] delete the whole tree.
This could be achievable with Enum.each that each time if I don't get [] just again loop through and go till the last level, and where it says [] delete that, but can it be possible through more programmatical way? in recursion instead of so many eachs? any help would be helpful thanks
Comment: @ZubairNabi check answer from Jose :)
Comment: That nested calls to `Enum.each/2` can be replaced with `for` macro with better readability.
Comment: I would prefer to
1) write functions for each step separately with case statement about what to do otherwise
2) and then pattern match each function when list is not empty
Answer: Edit: misunderstood question
So if you want to generate the combinations using recursion, I suppose you could pass your arguments(cameras, servers, years) as a nested list and recursively construct the combinations(consume the first list(cameras), and construct a list by passing the rest of the lists(servers and years) etc.).
This does have the advantage that you can pass an arbitrary number of items or lists and it will construct the combinations instead of adding one more level of Enum.each when you want to add another level in the url.

defmodule Test do

  def perm(input, acc \\ [])
  def perm([], acc), do: acc
  def perm([first_arr | rest_arr], acc) do
    first_arr
    |> Enum.map(fn val ->
      perm(rest_arr, [val | acc])
    end)
  end

  def flat([fst | rst]) when is_list(fst) do
    case fst do
      [fst1 | _rst1] when is_list(fst1) -> flat(fst ++ rst)
      _ -> [fst] ++ flat(rst)
    end
  end
  def flat(other), do: other
end

cameras = ["gaol-yard", "gaol-yard-1", "gaol-yard-2"]
years =   ["2015", "2016", "2017", "2018", "2019"]
servers = ["seaweedfs_new", "seaweedfs_old", "seaweedfs_oldest"]
# input = [[1,2,3], [:a,:b,:c], [5.0, 6.0, 7.0]]

[cameras, years, servers] \
|> Test.perm() \
|> Test.flat \
|> Enum.map(&Enum.reverse/1)

This should generate something like
[
  ["gaol-yard", "2015", "seaweedfs_new"],
  ["gaol-yard", "2015", "seaweedfs_old"],
  ["gaol-yard", "2015", "seaweedfs_oldest"],
  ["gaol-yard", "2016", "seaweedfs_new"],
  ["gaol-yard", "2016", "seaweedfs_old"],
  ["gaol-yard", "2016", "seaweedfs_oldest"],
...
  "gaol-yard-1", "2015", "seaweedfs_old"],
  ["gaol-yard-1", "2015", "seaweedfs_oldest"],
  ["gaol-yard-1", "2016", "seaweedfs_new"],
...
  ["gaol-yard-2", "2019", "seaweedfs_new"],
  ["gaol-yard-2", "2019", "seaweedfs_old"],
  ["gaol-yard-2", "2019", "seaweedfs_oldest"]
]

which you can join into one string each
Comment: you didnt get the question actually :)
Comment: Damn.. :), so if the bottom-most directory is empty, delete the whole directory from top?
Comment: Yes its not actual directory as well :) its just HTTP Urls, and its a file system with REST features.
Comment: the delete part which I am showing is deleting the full tree.
Comment: Have updated the answer, hope I got it this time :D
Comment: Naah :D Still didn't get it :P
Comment: The question is: run `request_from_seaweedfs(final_url, type, attribute)` this method until the result is `[]`
Answer: Here is one approach. Change the current function to call recursive_delete with the known years:
Enum.each(cameras, fn camera ->
  Enum.each(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = server <> "/#{camera.exid}/snapshots/recordings/"
    recursive_delete(years, url, type, attribute)
  end)
end)

And then:
def recursive_delete([], _, _, _), do: :done

def recursive_delete(entries, url, type, attribute) do
  Enum.each(entries, fn entry ->
    entry_url = url <> entry <> "/"

    entry_url
    |> request_from_seaweedfs(type, attribute)
    |> recursive_delete(entry_url, type, attribute)
  end)
end

Comment: can we also spawn it in some way? for each camera? using `Task.start` or something?

Deep level recursion with Elixir


Generating totally random numbers without random function?

Question:
Possible Duplicate:
True random number generator

I was talking to a friend the other day and we were trying to figure out if it is possible to generate completely random numbers without the help of a random function? In C for example "rand" generates pseudo-random numbers.  Or we can use something like "srand( time( NULL ) );"  This will allow the computer to read numbers from its clock as seed values.  So if I understand everything I have read so far right, then I am pretty sure that no random function actually produces truely random numbers.  How would one write a program that generates numbers that are completely random and what would code look like?
Comment: See [Wikipedia](http://en.wikipedia.org/wiki/Pseudorandom_number_generator), which sayeth: Robert R. Coveyou of Oak Ridge National Laboratory once titled an article, "The generation of random numbers is too important to be left to chance." As John von Neumann joked, "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin."
Comment: See: http://en.wikipedia.org/wiki/Yarrow_algorithm and http://en.wikipedia.org/wiki/Fortuna_%28PRNG%29
Answer: Check out this question:
True random number generator
Also, from wikipedia's entry on pseudorandom numbers

As John von Neumann joked, "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin."
Comment: Ty...looked through everything didn't see that one.
Answer: The excellent random.org website provides hardware-based random numbers as well as a number of software interfaces to retrieve these.
This can be used e.g. for genuinely unpredictable seeds or for 'true' random numbers. Being a web service, there are limits on the number of draws you can make, so don't try to use this for your graduate school monte carlo simulation.
FWIW, I wrapped one of those interface in the R package random.
Comment: Random.org has a lot of good info.  +1 for Dirk.  http://www.random.org/randomness/
Answer: It would look like:
<code>int random = CallHardwareRandomGenerator();
</code>
Even with hardware, randomness is tricky. There are things which are physically random (atomic decay is random, but with predictable average amounts, so that can be used as a source of random information) there are things that are physically random enough to make prediction impractical (this is how casinos make money).
There are things that are largely indeterminate (mix up information from key-stroke rate, mouse-movements, and a few things like that), which are a good-enough source of "randomness" for many uses.
Mathematically, we cannot produce randomness, but we can improve distribution and make something harder to predict. Cryptographic PRNGs do a stronger job at this than most, but are more expensive in terms of resources.
Answer: This is more of a physics question I think. If you think about it nothing is random, it just occurs due to events the complexity of which make them unpredictable to us. A computer is a subsystem just like any other in the universe and by giving it unpredictable external inputs (RTC, I/O garbage) we can get the same kind of randomness that that a roulette wheel gets from varying friction, air resistance, initial impulse and millions of factors that I can't wrap my head around.
Answer: There's room for a fair amount of philosophical debate about what "truly random" really even means. From a practical viewpoint, even sources we know aren't truly random can be used in ways that produce what are probably close enough for almost any practical purpose though (in particular, that at least with current technology, full knowledge of the previously produced bitstream appears to be insufficient to predict the next bit accurately). Most of those do involve a bit of extra hardware though -- for example, it's pretty easy to put a source together from a little bit of Americium out of a smoke detector.
There are quite a few more sources as well, though they're mostly pretty low bandwidth (e.g., collect one bit for each keystroke, based on whether the interval between keystrokes was an even or odd number of CPU clocks -- assuming the CPU clock and keyboard clock are derived from separate crystals). OTOH, you have to be really careful with this -- a fair number of security holes (e.g., in Netscape around v. 4.0 or so) have stemmed from people believing that such sources were a lot more random than they really were.
While there are a number of web sites that produce random numbers from hardware sources, most of them are useless from a viewpoint of encryption. Even at best, you're just trusting your SSL (or TLS) connection to be secure so nobody captured the data you got from the site.


Can we deduce whether $f \in \mathcal{L}^2$ given these conditions on $f$?

Question:
If we assume that $f$ is a real-valued and continously differentiable. Let's also assume that $f(x) = f(x+2\pi) \forall x \in \mathbb{R}$. Can we then deduce something about the following statements:

$f \in \mathcal{L^2}(-\pi, \pi)$
$f' \in \mathcal{L^2}(-\pi, \pi)$
$\langle f , f' \rangle$

My attempt:
If $f$ is continously differentiable, then both $f$ and $f'$ are continous on the reals. If $f$ is continous on a bounded interval $[-\pi, \pi]$, then it attains a maximum $M_f$ and likewise $M_{f'}$ for $f'$.
From the definition of $\mathcal{L^2}(-\pi, \pi)$, we can bound both $f$ and $f'$ such that:
$$\int_{-pi}^\pi |f|^2 \leq 2 M_f^2 \pi $$
and correspondingly with $f'$. So both of them must be in $\mathcal{L^2}(-\pi, \pi)$.
For the last statement, we use the definition:
$\langle f , f' \rangle := \int_{-\pi}^\pi f f' dx$
Since $f'$ and $f$ are continous, $f'f$ is also continous on $[-\pi, \pi]$, which means that we can deduce that this integral is finite.
Is this a correct way of thinking about these problems? Thank you in advance.
Comment: You don't need it since your integrals are only over a period.
Comment: Yes, correct. You could as well deduce 3 from 1 and 2.
Comment: @AnneBauval Thank you for your comment. I just came to realization that it was included that the function is periodic in the problem. It seems like I'm missing something, since I didn't use that fact anywhere.
Comment: What do you mean in (3)? It isn't a statement as written...
Comment: You can say something more about the integral in 3 if you use the periodicity. Hint: integration by parts.
Comment: @MPW Sorry, I understand my formulation caused some confusion for (3). I really meant: what can you deduce about $\langle f, f' \rangle$ for the given conditions.
Comment: @MaoWao I'll test that :)
Answer: Minor: you have to pick $M_f$ as maximum of $|f|$.
As to (3): we have $(f^2)' = 2ff'$, so
$$
\int_{-\pi}^\pi ff' \ dx = \frac12( f(\pi)^2 - f(-\pi)^2) = 0
$$
because of periodicity.


Import images from RSS with Feeds module without Feeds Image Grabber

Question: I'm passing all the sites from D7 to D8 and so far so good. But one of my sites gives me a couple of problems.
I was populating the RSS site in Drupal 7 using Feeds Image Grabber. Now, Feeds Image Grabber for Drupal 8 is not there. So how do I get RSS images then?
I read that maybe you can do it with the Feeds extensible parsers module.
Any advice?
Comment: My advice would be to simply try it out yourself in some local development environment.
Answer: RSS feeds are XML files, so you could indeed use the XML parser from Feeds extensible parsers to extract data from it. This parser works with XPath queries. XPath is a query language to select data from a XML file. So to select the image from the RSS feed, you'll need to figure out how to select that data with the right XPath query.
It would be a good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.


2-transitively, formula

Question: Let $G$ be a finite group and let $X$ with $|X| \ge 2$ be a set on which $G$ acts. Then $G$ acts on $X \times X$ via $g \cdot (x, y) = (g \cdot x, g \cdot y)$. The action of $G$ on $X$ is called $2$-transitive if the $G$ action on $X \times X$ is transitive on the set of pairs of distinct elements of $X$.
For each $g \in G$ let $r_g$ be the number of fixed points of $g$ acting on $X$. Prove that if $G$ acts $2$-transitively on $X$ then $${1\over{|G|}}\sum_{g \in G} r_g^2 = 2.$$
Answer: If $G$ acts $2$-transitively, for any pair $(x, y) \in X \times X$ with $x \neq y$, it can be sent to any other pair $(z, w)$ with $z \neq w$. So all these pairs form an orbit of $X \times X$. The remaining elements of the set $X \times X$ are the diagonal $\Delta = \{(x, x) \in X \times X\}$. These form an orbit also since for any $x, y \in X$, there must be $g \in G$ with $g \cdot x = y$ $($there exists $g$ such that $g \cdot (x, y) = (y, x)$, so $g \cdot x = y)$. Thus $g \cdot (x, x) = (y, y)$, so $X \times X$ has exactly $2$ orbits. By Burnside's lemma, we have$${1\over{|G|}} \sum_{g \in G} r_g^2 = 2,$$since $r_g^2 =\,$# of fixed points of $g$ acting on $X \times X$.

2-transitively, formula


Hangfire recurring job next execution time is empty

Question: This question may seem pretty dumb, so sorry about that. I'm new to Hangfire.
I'm using hangfire(with MongoDB) in my .net core app and things are good!
But yesterday I got the following errors for my recurring jobs using.
<code>System.InvalidOperationException:
Recurring job can't be scheduled, see inner exception for details.
---> Hangfire.Common.JobLoadException: Could not load the job. See inner exception for the details.
---> System.TypeLoadException:
Could not load type 'AirQualityControl.Core.Models.Domain.AirMonitoringStation' from assembly 'AirQualityControl.Core, Version=220.127.116.11, Culture=neutral, PublicKeyToken=null'.   at System.Reflection.RuntimeAssembly.GetType(QCallAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext)   at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)   at System.TypeNameParser.ResolveType(Assembly assembly, String[] names, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)   at System.TypeNameParser.ConstructType(Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)   at System.TypeNameParser.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)   at System.Type.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError)   at Hangfire.Common.TypeHelper.DefaultTypeResolver(String typeName)   at System.Linq.Enumerable.SelectArrayIterator`2.ToArray()   at Hangfire.Storage.InvocationData.DeserializeJob()   --- End of inner exception stack trace ---   at Hangfire.Storage.InvocationData.DeserializeJob()   at Hangfire.RecurringJobEntity..ctor(String recurringJobId, IDictionary`2 recurringJob, ITimeZoneResolver timeZoneResolver, DateTime now)   --- End of inner exception stack trace ---   at Hangfire.Server.RecurringJobScheduler.ScheduleRecurringJob(BackgroundProcessContext context, IStorageConnection connection, String recurringJobId, RecurringJobEntity recurringJob, DateTime now)
enter code here
</code>
This is completely my fault ♀ , 'cause I accidentally change the type namespace.
I revert those changes to previous state.
But I'm worried about current state of jobs:

As you might see the next execution is empty.
Usually it contains date and time when job will be triggered next time.

So I guess that they will not be lunch according to CRON expression?
Do I need to somehow manually tweak these jobs?
Or they will run today at 7PM again according to CRON expression?
Thank you so much for your help and have a nice day!
Comment: What is the configuration for max retry attempt in `hangfire` before the job is set to failed?
Comment: @NikhilPatil I'm not override this setting. So I believe it has a default value which  is 10, according to the source code.
https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/AutomaticRetryAttribute.cs
Comment: I am not sure why next execution time is empty, because your job has failed only 5 times. From where are you fetching the next execution time? I cannot see any field in DB that stores this value. Do you have access to `hangfire` dashboard? Maybe you can check there?
Comment: @NikhilPatil I'v updated question with more details, to be more precise. Hope you will find it useful
Comment: Up. still have the same issue
Comment: @CherryBlossom, I've posted an answer that tries to describe an answer in details.
Hope you will find it useful
Answer: Update: For those who are new to Hangfire and facing the same issue.
Every job in Hangfire has a certain number of retries attempts. It might be a global setting or could be changed using the AutomaticRetry attribute per job.
By default every job has 10 retries attempt.

If retry attempts exceeded their maximum, the job will be move to the
Failed state (with an error log message), and you will be able to
retry it manually.

Also, it's important to note that we might see hangfire with it's jobs as a finite-state machine.

This image has an illustrational purpose only. This is not an accurate list of hangfire job's states
That means that every job should have a certain state. Some of them are terminal and some of them are not.
Here you could find a complete list of hangfire's job states.
According to the documentation

Failed - Defines the intermediate state of a background job when its
processing was interrupted by an exception and it is a developer's
responsibility to decide what to do with it next.

That means that job would not be triggered automatically and you should run it manually or get rid of it.


AngularJS: Parent scope not updated in directive (with isolated scope) two way binding

Question: I have the following code, which can also be fiddled on http://jsfiddle.net/garukun/u69PT/.
View:

        {{pkey}}

JS:
var testApp = angular.module('testApp', []);

testApp.directive('testDirective', function ($timeout) {
    return {
        scope: {
            key: '=parentItem',
            parentUpdate: '&'
        },
        replace: true,
        template: '

{{key}}
' +
            '<button data-ng-click="lock()">Lock</button>' +
            '
',
        controller: function ($scope, $element, $attrs) {
            $scope.lock = function () {
                $scope.key = 'D+' + $scope.key;
                console.log('DIR :', $scope.key);

                // Expecting $scope.$parent.pkey to have also been
                // updated before invoking the next line.
                $scope.parentUpdate();
                // $timeout($scope.parentUpdate); // would work.
            };
        }
    };
});

testApp.controller('testCtrl', function ($scope) {
    $scope.pkey = 'golden';
    $scope.update = function (k) {
        // Expecting local variable k, or $scope.pkey to have been
        // updated by calls in the directive's scope.
        console.log('CTRL:', $scope.pkey, k);
        $scope.pkey = 'C+' + k;
        console.log('CTRL:', $scope.pkey);
    };
});

Basically, I'm setting up the directive with an isolated scope, in which I'm two-way binding a property (key) from the parent scope (pkey), and also delegating a method (parentUpdate) to be called in the context of the parent scope.
Now, during a ng-click event handler in the directive, I want to invoke the parentUpdate method and do something within. When I'm invoking that method, I'm expecting my parent scope's model to have been updated. But in reality, it is not, and this is what's puzzling me.
It's probably because of some missing $digest cycles in the middle, since wrapping the parentUpdate call with $timeout would work as expected.
Could someone shed some light on what's missing? Or how to properly invoked parentUpdate?
Comment: OK, so targeting a bit here... you're wondering why `$scope.key = 'D+' + $scope.key;` from the `lock()` function doesn't seem to have any effect, right?
Answer: OK, I'm going to take a crack at this one...   It seems you're changing both the isolated child AND parent variables before a $digest cycle where the bi-direction logic syncs the two.   Here's the details:

First your lock() function is executed by clicking on the button.  This updates the isolated $scope.key variable. NOTE: This does NOT immediately update the parent $scope.pKey; that would normally happen at the next $digest cycle but does not in this case.  Read on...
Within lock() you are calling parentUpdate() which updates the parent's $scope.pKey variable.
THEN the $digest cycle executes.  When it loops it's way to the parent scope a change to $scope.pKey is correctly detected.
The change to $scope.pKey triggers a watch() that was created by the bi-directional binding in the isolated scope.  These lines are the critical ones..
The watch() created by the isolated scope checks whether it's value for the bi-directional binding is in sync with the parent's value.  If it isn't (and it's not in this scenario) the parent's value is copied to the isolated scope even though the isolated scope's value has changed also and in fact was changed first.

Misko's famous post on Angular data-binding describes the benefits of the $digest cycle approach.   What you're seeing here is a conscious side-effect of the $digest's approach to change coalesence wherein, as the source code comment says, parent changed and it has precedence... and that means your isolated scope's change loses.
The $timeout() approach you noted above avoids this issue by changing only the isolated scope's value in the first $digest cycle which allows it to be copied to the parent scope successfully and THEN calling parentUpdate()
The $compile documentation says:

Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

This means, at step #2 you could pass in your value for pkey via an object map like this:
parentUpdate({pkey: 'D+' + $scope.key })

Here's the updated fiddle: http://jsfiddle.net/KbYcr/
Comment: Thanks for the explanation, it's really helpful! While I understand that it's due to the design of the $digest cycles. I'm seeking a way to have the properties of the isolated scope build on top of parent scope's property without having to invoke timeout function. And in this case, since we are already in a digest cycle, we cannot invoke anymore $digest or $apply. Ideally, I would like to invoke evalAsync, but that doesn't seem to work either. If there could be one trick in the angular's sleeves that can bypass this design, it would be awesome.
Comment: I think there is just such a trick :-)  I just updated my answer above with the details and a new jsFiddle with a minor change demonstrating it.
Answer: Using $scope.$apply() instead of $scope.$digest() works too. This will also trigger the digest on the rootScope.


How to disallow spam in tag field

Question: We are a a job site where we allow visitors to post Jobs / Events through various forms. However it looks like that spammers are using this process to put spam in tag fields. This has resulted into tag cloud being spammers paradise.
How can I restrict that?
Comment: Have a look at [Mollom](http://mollom.com/)
Comment: @Clive  Does it work for tag spam?  I don't think I have ever tried it for that.
Comment: @MPD I'm not entirely sure, I know they analyse content as a whole so I thought it worth a look
Answer: If you add something like
reCAPTCHA
to your form, that should stop the spammers in their tracks.
If the form is auto-populated by a bot, it should prevent adding spam content in any of the form fields as they won't be able to submit the form without passing the challenge.

How to disallow spam in tag field


Passing through RDMA network devices to docker containers

Question: I'm wanting to passthrough infiniband to a docker container so that I can run some high performance apps over ipoib and use rdma.
Currently, I'm doing this with xen virtual machines.  Now I'm looking into using CoreOS and docker as a much lighter weight and easier to manage alternative.
I have an IPoIB device ib0 with a static IP assigned to it of 10.10.10.10.
I've managed to get that exposed inside a docker container with the following:

docker run --net=host --device=/dev/infiniband/uverbs0
  --device=/dev/infiniband/rdma_cm -t -i ubuntu:14.04 /bin/bash

Great, that works.  ib0 is available inside the docker container.
Now lets suppose I have a dual port HCA.  On the host these appear as ib0 & ib1 and have two ip's assigned.  10.10.10.10/ib0  and 10.10.10.11/ib1
And now I want to pass ib0 to the first container and ib1 to the second.  Using the method above both will appear in both containers because of the --net=host option.  However, not specifying it means the devices do not appear at all.
Another scenario is I have a lot of machines that using SR-IOV to passthrough infiniband devices to xen virtual machines.  How could I pass instead a virtual function infiniband device to a docker container and have that appear?
Note: pipework doesn't work in this situation but if I understand it better it might be able to be hacked to do what I want.  I just don't quite understand what it's doing... yet.
Comment: Just to clarify, you want to specify an interface on the host to be used by a Docker container and you want to be able to individually specify this per container? Are you trying to use it solely or as a secondary interface?
Comment: @theterribletrivium - correct in the first question.  The ultimate goal would be to have normal docker behaviour + an extra ib device inside each docker container.  I can't seem to do that without some sort of special scripting but I don't understand docker enough to implement it yet.
Answer: And now I can answer my own question on how to do this.
Use pipework which I have just patched to work with Infiniband or RDMA IPoIB devices.
You run it like this.
<code>~ $ docker run --device=/dev/infiniband/uverbs0 --device=/dev/infiniband/rdma_cm -d container
~ $ pipework ib0 container-id ip/netmask
</code>
Because IPoIB devices do not support bridging, the whole ib0 device is hidden from the host after the command is issued.  i.e. It is moved to the network namespace of the container.
To get bridge-like functionality without bridging use SR-IOV and pass the virtual function through via pipework.
The latest incarnation uses virtual IPoIB which is similar to macvlan. Therefore the real ib0 remains visible in the host.  It works very similarly to the ethernet version.