Repast: how to count the total number of agents satisfying the specific condition

Question: Each agent has a private boolean variable "Happy?". how to count the agents with [Happy? = True]?
Is there a direct method available in repast? Or I have iterate through all agents and count them individually?
Update:
I have tried the global scheduling method: https://repast.github.io/docs/RepastReference/RepastReference.html#schedule-global
It's not working when I put below code using the @ScheduledMethods in the ContextBuilder.
grid.moveTo(this_girl, group_x,group_y);
            }
        }
        return context;
    }

    @ScheduledMethod(start = 1, interval = 1, shuffle=true)
    public void step () {
        Context<Object> context = ContextUtils.getContext(this);
        Query<Object> query = new PropertyEquals<Object>(context, "happy", true);
        int end_count = 0;
        System.out.println(end_count);
        for (Object o : query.query()) {
           if (o instanceof Boy) {
               end_count ++;
           }
           if (o instanceof Girl) {
               end_count ++;
           }
        }
        System.out.println(end_count);
        if (end_count == 70) {
            RunEnvironment.getInstance().endRun();
        }
    }
}

It's working if I put above code in either boy agent or girl agent actions.
@ScheduledMethod(start = 1, interval = 1,shuffle=true)
    public void step() {
        relocation();
        update_happiness();
        endRun();

    }

    public void endRun( ) {
        Context<Object> context = ContextUtils.getContext(this);
        Query<Object> query = new PropertyEquals<Object>(context, "happy", true);
        int end_count = 0;
        System.out.println(end_count);
        for (Object o : query.query()) {
           if (o instanceof Boy) {
               end_count ++;
           }
           if (o instanceof Girl) {
               end_count ++;
           }
        }
        System.out.println(end_count);
        if (end_count == 70) {
            RunEnvironment.getInstance().endRun();
        }
    }

Answer: You can use a Query for this -- see the query answer to this question:
Repast: how to get a particular agent set based on the specific conditions?
You could also use the query method in a Context where you pass it a predicate where the predicate returns true if happy.
In both of these cases, you'll need an accessor method for the private boolean happy field -- e.g.
public boolean isHappy() {
   return happy;
}

Also in both cases, the queries return an iterable over all the agents where happy is true, rather than a collection where you could take the size to get the count. So, you'll have to iterate through that and increment a counter.
Update:
Your current problem is with the scheduling. You can't easily schedule a method on the ConetextBuilder as its not really part of the model, but rather used to initialize it. The easiest way to schedule what you want is to schedule it explicitly in the ContextBuilder with something like:
RunEnvironment.getInstance().getCurrentSchedule().schedule(ScheduleParameters.createRepeating(1, 1, ScheduleParameters.LAST_PRIORITY), () -> {
            Query<Object> query = new PropertyEquals<Object>(context, "happy", true);
            int end_count = 0;
            System.out.println(end_count);
            for (Object o : query.query()) {
                if (o instanceof Boy) {
                    end_count++;
                }
                if (o instanceof Girl) {
                    end_count++;
                }
            }
            System.out.println(end_count);
            if (end_count == 70) {
                RunEnvironment.getInstance().endRun();
            }
    });

The LAST_PRIORITY should insure that all the agent behavior will have taken place before the happiness count is polled.
Comment: Hi I actually want to know how to schedule a global action method/procedure that is outside of each type of agent's method. Like this one, I have two types of agents (boys and girls). I want to count the total number of persons who are happy and this method does not need to iterate through every boy and girl agent, but to be performed at the global level right after all agents have made an action.
Comment: thanks it's working. But this is not modular in my eyes. Is there more structural way to schedule the global behavior using method()? Eventually, I want a structure with some methods() for particular agents and some methods for global behaviors and all of them follows a particular execution sequence. How to achieve this? thanks
Comment: I haven't done this in a while, but I think it should work. Create a custom context by extending DefaultContext and in your ContextBuilder ignore the passed in Context, create, fill and return yours. Use the schedule annotations on methods in your custom context for the global behavior. You could also move the "happy" code above to a separate class that implements IAction and schedule that manually as above.
Comment: would you mind if I open a new question specifically addressing this issue? this is quite important for me to build my agent-based model.


Toda função anônima é uma closure?

Question: Toda função anônima é considerada uma closure ou são consideradas apenas aquelas que referenciam o contexto onde foram criadas?
Gostaria de saber isso para distingui-las corretamente. Eu conheço os conceitos e as funcionalidades, mas a impressão é que muitos tratam ambas como se fossem iguais.
Answer: Não, são mecanismos totalmente independentes. Embora tecnicamente seja possível ter um mecanismo de clausura em uma função que não seja anônima, só conheço implementações de closure em funções anônimas. Mas uma função anônima não tem obrigação de ter uma closure. Então na teoria não há necessidade de vinculação de ambas nos dois sentidos e na prática o que ocorre é haver vinculação em um sentido apenas.
O mecanismo da clausura é só capturar um valor contido em outro escopo para o escopo da função anônima ampliando seu tempo de vida. Então se você não capturar esse valor dessa forma em uma função anônima não incluiu o mecanismo de enclausuramento.
Cada tecnologia pode implementar isso da forma que quiser internamente. Então pode ser que uma determinada linguagem faça com que todas as funções anônimas paguem o preço de poder ter uma clausura mesmo sem a captura de um valor. Isso não quer dizer que tem uma closure ali, apenas que tem a capacidade de ter. Mas reforço que é detalhe de implementação e só vale a pena saber por questões de otimização.
De fato as pessoas tendem achar que é a mesma coisa, mas não é. Existem diferenças sutis para os termos lambda, funções de primeira classe ou de alta ordem.
Algumas tecnologias podem chamar do mesmo nome, por exemplo dizer que uma função anônima simples é uma closure, mas estritamente isso é errado. A linguagem que faz isso normalmente passa uma imagem de ignorância, ou arrogância ou ambos.
Uma função anônima pode ser implementada de forma muito simples só com um ponteiro para provocar indireção e poder armazenar em alguns lugares. Uma closure precisa de um objeto um pouco mais complexo para manter os valores ou referências para as variáveis capturadas.
Pode ver mais em:

Qual a diferença entre uma expressão lambda, um closure e um delegate?
Como funcionam Closures em JavaScript?
O que caracteriza a programação imperativa e funcional?
Linguagem imperativa incorporando elementos funcionais
Diferença entre closures e functions

Coloquei no GitHub para referência futura.
Comment: "*só conheço implementações de closure em funções anônimas*", os decoradores no Python, em teoria, podem definir uma *closure* com funções nomeadas quando o decorador retorna uma função que é definida pelo contexto do próprio decorador.

Toda função anônima é uma closure?


Multi-step and multipage Registration Form with Field_group module

Question: My drupal is 7 .
I use field_group module For grouping field and multipage registration form.
When I Add multipages to account fields only 2 groups of these fieldgroups work and other field groups show on bottom of first step.
I set field group and multipage group and multipage widget on field settings.
For content type everythings is work correctly but for user registration Form Some steps ignored.
Have anybody same problem?
Have any idea for multistep registration form with Drupal.?
Answer: You can have a look at these modules:
https://drupal.org/project/ctools
https://drupal.org/project/mforms
Make sure to go through their documentation for more information on how to create the multistep registration page.
You may also want to take a look at this tutorial:
http://www.grasmash.com/article/building-multistep-registration-form-drupal-7-using-ctools
And you might also have a look at this module:
https://www.drupal.org/project/step
Regards,
Comment: mforms module need some codes and is very complex.STEP module needs Profile2 module and i don't like use profile2.i want create forms with fields API.unfortunately Field_group is not working for registration form correctly.thank you for your response...IS ANY Idea for use field group?
Answer: I reinstall My drupal site and use field_group module for secound time , this time everything is normal and steps are added to forms.
Thank you for responses.


find the number of seven letter "words" that start with a or do not contain a

Question: Find the number of seven letter "words" that start with a or do not contain a. For this problem, I'm not really sure what method I can use. I tried to subtract the "words" that start with a from 657800 (26 choose 7)
Comment: I have solved your problem but you need to show some thoughts/efforts before I share the solution, please do so.
Comment: Re Deepak's comment, please edit your query to show all of your work.  Please do **not** respond with a comment.
Comment: What have you tried?
Comment: As you have edited with a line about what you've tried, I've shown my solution.
Answer: So, answer should be as follows:

Here we have $7$ spaces.
The total number of words that start with a are :
$1 \cdot 26^6$ ($1$ is representing a here and $26$ representing rest of letters)
And the words that don't contain a are:
$25^7$ (all words other than a).
See there is no intersection between two cases.
Like you can't have a word that start with a and do not contain a. Right?
So, answer will be $26^6+25^7$.
Thanks, hope it helps.
Comment: "Let me know if I am wrong" : you are correct, +1, you can remove that phrase now.
Comment: Thank you.........
Comment: This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: "Words" here should be taken to mean arrangements of letters, not actual dictionary words.
The first case is having an "a" at the start. Which means that the remaining six postions can contain any letter (including "a"). This gives $1\cdot 26^6 = 26^6$ possibilities.
The second case is not containing an "a" at all. Which means all seven positions must be filled with one of the remaining $25$ letters in the alphabet. That gives $25^7$ possibilities.
Note that the two cases are mutually exclusive.
Therefore the total number is $26^6 + 25^7 =6412431401$.
EDIT: Addressing your attempted answer, note that $\binom {26}7$ would only be relevant if you're choosing $7$ (unique, non-repeated) letters out of the alphabet to fill the $7$ positions without regard to order. This is not a relevant consideration here.


Using Squid as a maven repository

Question: Does someone know how to use Squid to proxify maven repositories ?
What are the configuration files for that ?
The main problem is that maven client issue HTTP request with headers which control the cache behavior (and I want to bypass that).
Here is a typical request :
GET /maven/proxy/jboss-public/org/richfaces/richfaces-bom/4.2.0.Final/richfaces-bom-4.2.0.Final.pom HTTP/1.1
Cache-control: no-cache
Cache-store: no-store
Pragma: no-cache
Expires: 0
Accept-Encoding: gzip
User-Agent: Apache-Maven/3.0.4 (Java 1.6.0_26; Linux 2.6.32-38-generic)
Host: 192.168.2.171
Connection: Keep-Alive

I'm already using Apache HTTPD (and disk_cache proxy_http modules enabled) for that, but I'm creating a mirror, not a proxy.
Here is the configuration (based on that site) :
<Proxy *>
Order deny,allow
Allow from all
</Proxy>

# central
ProxyPass /maven/proxy/central http://repo1.maven.org/maven2
ProxyPassReverse /maven/proxy/central http://repo1.maven.org/maven2
CacheEnable disk /maven/proxy/central

# jboss-public-repository-group
ProxyPass /maven/proxy/jboss-public http://repository.jboss.org/nexus/content/groups/public
ProxyPassReverse /maven/proxy/jboss-public http://repository.jboss.org/nexus/content/groups/public
ProxyPassReverseCookiePath /nexus /maven/proxy/jboss-public
CacheEnable disk /maven/proxy/jboss-public

# codehaus
ProxyPass /maven/proxy/codehaus http://repository.codehaus.org/
ProxyPassReverse /maven/proxy/codehaus http://repository.codehaus.org/
CacheEnable disk /maven/proxy/codehaus

CacheDirLength 2
CacheDirLevels 3

# Override default cache expiration and control
CacheDefaultExpire 2419200
CacheMaxExpire 2419200

# Ignore requests to not serve from cache. Maven data never changes.
CacheIgnoreCacheControl On
CacheIgnoreNoLastMod On
CacheStoreNoStore On

# Default max file size is 64K. Set to 1GB.
CacheMaxFileSize 1073741824

Comment: If you want perfomance, make more sense use a internal artifactory repository like artifactory, nexus or apache archiva. Every time you want a new module they will download from internet and store on your local network, if someone in your network needs this same module, there is no need do go to internet make the download again. Saving bandwidth and without care about Cachesize.
Comment: Have you considered using nexus instead?
Comment: Of course I've considered it. I've also tested others. But nothing was as fast as Apache in proxy mode. That's why I wanted to use a real proxy and use Squid to perhaps obtain even more performances.
Comment: I agree with @JoaoVitorino - using a pull through cache of artifactory is probably the best option.
Answer: I would recommend using a proper repository like Nexus which will enable much more flexibility such as combining central maven with your own local artifact into one repository, caching of artifacts downloaded from central upon first request (so you don't need to host all artifacts, only those you need), protects you from artifacts deletion in central (think NPM leftpad fiasco), enables you to prevent usage of certain artifacts (say there is a broken artifact that has a security flaw, you can block all users from using it).
And, above all that, your users don't have to waste time setting up proxy configurations for Maven/Gradle/etc. which can be tricky at times...
But if you must do it in Squid:
Put allowed domains in /etc/squid/mavendomains.list.
In squid.conf (or if you have include files...):
acl maven-domains dstdomain "/etc/squid/mavendomains.list"
acl allowed-networks src x.x.x.x/x
http_access allow allowed-networks maven-domains

Using Squid as a maven repository


Android Material Design widget parent for Switch

Question: Does anyone know what the widget parent is for a Material Design Switch?  For example, the Material Design widget parent for Seekbar is:

Answer: You should include the appcompat v7 library, this is the xml code you use to define such a Switch
<android.support.v7.widget.SwitchCompat
android:id="@+id/dev_switch_show_dev_only"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

I didn't found any parent name, so you can add the custom style to your view by using android:style
Comment: I have tried to use SwitchCompat but when I do, no widget is displayed.  And yes, I do have 'com.android.support:appcompat-v7:22.2.0' in my build gradle file.
Comment: @PerryHoekstra There is an update available for the appcompat v7: use  'com.android.support:appcompat-v7:23.0.0'
Comment: Yes, that is true.  However, when I tried to upgrade to v7:23.0.0, I receive a: Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 3 on the latest version of Android Studio v 1.3.1  So, for now, I am not moving off of v7:22.2.1
Comment: What version of build tools are you using?
Comment: buildToolsVersion "22.0.1"
Comment: Try updating the Java JDK to version 1.8.0_25. You are using an outdated version of java
Comment: Ummm, no. JDK 220.127.116.11 is the latest/greatest of the JDK 7 line so it is not outdated and in addition, the Android Studio installation docs have not changed their sentence: "JDK 7 is required when developing for Android 5.0 and higher." and I am not going to introduce possible problems to solve this issue by moving to Java 8 at this time.
Comment: @PerryHoekstra I think that that might solve the issue. But I'm using version 1.8.0_25, so there is a newer version available. http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html


Generate identically distributed dependent normal random numbers with prespecified sum

Question: How do I generate $n$ identically distributed but not independent normal random numbers such that their sum falls within a prespecified interval $[a,b]$ with probability $p$?
(This question is motivated by generating a random walk that ends up at a prespecified point: Random process not so random after all (deterministic). Since a continuous random variable has zero probability of reaching an exact number, we do the second best thing and ask for an entire interval to end up in.)

EDIT: Generating samples from singular Gaussian distribution has been proposed as a duplicate, which in turn is closed as a duplicate of Generate normally distributed random numbers with non positive-definite covariance matrix. I agree that both of these are helpful. However, the point of the current question (more specifically, of the answer) is to first figure out that we can use a multivariate normal distribution to address the question, and second, what kind of covariance matrix works. How to sample from a distribution with that covariance is a third step, where the linked threads are helpful.
Comment: also see the literature on [Brownian bridges](https://en.wikipedia.org/wiki/Brownian_bridge) ?
Comment: (Sorry, of course I mean "BB-BB".)
Comment: Possible duplicate of [Generating samples from singular Gaussian distribution](https://stats.stackexchange.com/questions/159313/generating-samples-from-singular-gaussian-distribution)
Comment: @BenBolker: that sounds like a much better idea than mine. Would you be interested in writing up an answer?
Comment: maybe I'll get to it, but anyone else who is reading this should feel free to jump in and write up an answer.  I don't mind.
Comment: FWIW Brownian bridges are a more specific case - the sum is deterministically, exactly equal to a specified value $T_1$, not "within a given range with a given probability" ... arguably a better answer to the original question, but not to your generalization ...
Comment: @BenBolker: would it make sense to nominate the original question for reopening so you can post your BB there?
Comment: Sure.  Again, I may or may not be able to get to answering quickly ...
Comment: @BenBolker: I have nominated the original question for reopening, and also flagged it for the mods, in case my explanatory comment disappears in the sea of comments. Looking forward to your answer!
Comment: @BenBolker, I've reopened the thread. Please provide your answer at your convenience.
Comment: done. .........
Comment: Change the basis to one that includes the sum.  The resulting distribution is still multivariate Normal. [Sample the sum  from the truncated (univariate) Normal distribution.](https://stats.stackexchange.com/questions/238602/sampling-from-truncated-normal)  Invert the change of basis.
Answer: We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$.
As a common mean, we choose
$$ \mu_1 = \dots = \mu_n = \frac{a+b}{2n}. $$
In order that $Z\in[a,b]$ with probability $p$, its standard deviation should fulfill
$$ \sigma_Z = \frac{b-a}{q_\alpha}, $$
where $q_\alpha$ is the standard normal quantile to the level $\alpha$, here $\alpha=1-\frac{1-p}{2}$.
We now need to specify $\Sigma$. We have a lot of leeway here. Let us assume that we want each $X_i$'s variance to be $\sigma^2$ and the covariance be $\text{cov}(X_i,X_j)=\tau$ for $i\neq j$. The key to creating a "good" $\Sigma$ is this previous answer by probabilityislogic. It yields that the sum of our $X_i$s has variance
$$ n\sigma^2 + n(n-1)\tau $$
so we need that
$$ n\sigma^2 + n(n-1)\tau = \frac{b-a}{q_\alpha}.$$
We also need to ensure that $\Sigma$ is positive definite, but this is not overly hard. The easiest way to do this is to ensure that all entries in $\Sigma$ are positive, e.g., by setting
$$ \sigma^2 := \frac{\sigma_Z^2}{2n}, \quad \tau := \frac{\sigma_Z^2}{2n(n-1)}, $$
but this gives very small values and very boring cumulative sums and trajectories:

Less boring is to set
$$ \sigma^2 := 1, \quad \tau := \frac{1}{n-1}\big(\frac{\sigma_Z^2}{n}-\sigma^2\big), $$
which yields much more interesting trajectories:

Note that setting this does indeed yield a valid covariance matrix, because $\Sigma$ is then of the form $\Sigma_{ij} = m(i-j)$, namely
$$ m(0) = \sigma^2, \quad m(j) = \tau\text{ for }j>0, $$
and we have that
$$ \sum_{j>0} |m(j)| = (n-1)|\tau| = \big|\frac{\sigma_Z^2}{n}-\sigma^2\big| = \big|\frac{\sigma_Z^2}{n}-1\big| < 1 = \sigma^2 = m(0), $$
which is a sufficient condition for $\Sigma$ to be strictly positive definite by Wikipedia (Point 7 under "Further Properties").
R code below, but first, please go and upvote probabilityislogic's answer.
<code>n_steps <- 1000
target_min <- 1.99
target_max <- 2.01
target_prob <- 0.99

target_mean <- mean(c(target_min,target_max))
target_sd <- (target_max-target_mean)/qnorm(p=1-(1-target_prob)/2)

mm <- rep(target_mean/n_steps,n_steps)

# boring setting:
# sigma_sq <- target_sd^2/(2*n_steps)
# tau <- target_sd^2/(2*n_steps*(n_steps-1))

sigma_sq <- 1
tau <- (target_sd^2/n_steps-sigma_sq)/(n_steps-1)

CC <- matrix(tau,nrow=n_steps,ncol=n_steps)
diag(CC) <- sigma_sq

library(MASS)
foo <- mvrnorm(1,mu=mm,Sigma=CC)
sum(foo)

plot(cumsum(foo),type="l",xlab="",ylab="")
abline(h=target_mean,lty=2)
</code>


Cant figure out how to properly pull keys from config

Question: I've been trying to implement a config file for a very basic EntityDeathEvent script in order to allow for a reload command to be implemented to be able to add to my config and reload the file rather than restarting the server. The current code I'm using returns zero errors so I'm quite lost at this point. I'm 5 days into tinkering with Java so there are probably a bajillion things missing from my code but this is what i have so far.
main.java:
package com.mk7smp.LukesMobEffects;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

public class Main extends JavaPlugin implements Listener {

  @Override
  public void onEnable() {
    this.saveDefaultConfig();
    this.getServer().getPluginManager().registerEvents(this, this);
  }

  @Override
  public void onDisable() {

  }

  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (label.equalsIgnoreCase("mobeffects")) {
      if (!sender.hasPermission("mobeffects.reload")) {
        sender.sendMessage(ChatColor.RED + "Nope, big admin guys only.");
        return true;
      }
      if (args.length == 0) {
        // /mobeffects
        sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&bmk7 Mob Effects&f] &aUsage: /mobeffects reload"));
        return true;
      }
      if (args.length > 0) {
        // /mobeffects reload
        if (args[0].equalsIgnoreCase("reload")) {
          for (String msg: this.getConfig().getStringList("reload.message")) {
            sender.sendMessage(ChatColor.translateAlternateColorCodes('&',
              msg));
          }
          this.reloadConfig();
        }
      }
    }
    return false;
  }

  @EventHandler
  public void mobDeath(EntityDeathEvent event) {

    Entity entity = event.getEntity();
    Player player = event.getEntity().getKiller();

    if (player == null) {
      return;
    }

    ConfigurationSection mobs = this.getConfig().getConfigurationSection("mobs"); // The "mobs" section of the config file

    for (String mobKey: mobs.getKeys(false)) { // For ONE(one bc getKeys is set to true) mob key in the set
      String mobname = (String) mobs.get(mobKey + ".name"); // use specified path to retrieve name value
      String message = (String) mobs.get(mobKey + ".message");
      if (entity.getType().toString() == mobname) {
        for (String effectString: mobs.getStringList(mobKey + ".effects")) {

          //make sure there are no whitespaces in the "effectString"
          String[] values = effectString.split(",");

          //create PotionEffectType
          PotionEffectType type;
          //set default duration to 30 seconds
          int duration = 30;
          //set default strength to 1
          int strength = 1;

          //get type
          type = PotionEffectType.getByName(values[0].toUpperCase());

          //check, if type is null
          if (type == null) {
            System.err.println(effectString + " could not be interpreted into a correct PotionEffectType.");
            continue;
          }

          //set duration
          if (values.length > 1)
            duration = Integer.parseInt(values[1]);

          //set strength
          if (values.length > 2)
            strength = Integer.parseInt(values[2]);

          //check, if player already has potiontype
          if (player.hasPotionEffect(type))
            player.removePotionEffect(type);

          //create the effect
          PotionEffect effect = type.createEffect(duration * 20, strength);
          player.addPotionEffect(effect);
          player.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
        }
      }
    }
  }
  // THESE ARE THE FUNCTIONS THAT I WANT TO USE WITH DATA FROM CONFIG
  //if (entity.getType().toString() == "RABBIT") {
  //    player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&bmk7 Mob Effects&f] &aYou've been given &c&lLeaping: 15s &afor killing a &crabbit&a!"));
  //    player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 300, 2));
  //    }
  //if (entity.getType().toString() == "ENDERMAN") {
  //    player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&bmk7 Mob Effects&f] &aYou've been given &c&lRegeneration: 10s &afor killing a &cenderman&a!"));
  //    player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 2));
  //}
  //if (entity.getType().toString() == "CHICKEN") {
  //    player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&bmk7 Mob Effects&f] &aYou've been given &c&lFeather Falling: 10s &afor killing a &c&lchicken&a!"));
  //    player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 200, 1));
  //}
};

config.yml
reload:
   message:
      - "&f[&bmk7 Mob Effects&f] &a&lReloaded config!"

mobs:
  rabbit:
    name: rabbit
    message: "&f[&bmk7 Mob Effects&f] &aYou've been given &c&lLeaping: 15s &afor killing a &crabbit&a!"
    effects:
      - JUMP,15,2

please could I just have a hand in the right direction
Comment: I suggest you to use `mobs.getString()` instead of `mobs.get`
Answer: Please make the rabbit in line 7 a string. Add quotation marks.
reload:
   message:
      - "&f[&bmk7 Mob Effects&f] &a&lReloaded config!"

mobs:
  rabbit:
    name: "rabbit"
    message: "&f[&bmk7 Mob Effects&f] &aYou've been given &c&lLeaping: 15s &afor killing a &crabbit&a!"
    effects:
      - JUMP,15,2

Answer: Make sure you have deleted the old config file.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Can I approximate $\rho_n$ somehow so it satisfies this Bessel function conidition?

Question: While solving a PDE using the eigenfunction expansion method, I came across the following condition for $\rho _n$:
$$ J_0(\rho_n r_{max}) = J_2(\rho_n r_{max}) \tag 1$$
where $r_{max}$ is known. Is there any approximation I can use for $\rho_n$ so it approximately satisfies the above condition? I know for instance that the roots of the Bessel function of the first kind, order zero, can be approximated with $ n \pi - \pi / 4 + 1 / (8 n \pi - \pi / 4)$.
I found this out in this paper. I was hoping there was something similar I can use for this problem.
Comment: I am working this problem to avoid the use of Bessel functions.
Comment: Why the negative points? I gave context regarding my problem as well as its origin. If I didn't, nobody could have answered it, which is not the case. Please reconsider.
Answer: Let $x=\rho_n \,r_{max}$ and you want to find the zero's of function
$$f(x)=J_0(x)- J_2(x) $$
If you compute the very first ones (or plot the function), you will observe that they are closer and closer to
$$x_0^{(n)}=n\pi-1$$
If you want to improve it, use the first iteration of a Newton-like method ; this will give (using $c=\cos(1)$ and $s=\sin(1)$)
$$x_1^{(n)}=x_0^{(n)}+2\frac{J_0\big(x_0^{(n)}\big)-J_2\big(x_0^{(n)}\big)}{3 J_1\big(x_0^{(n)}\big)-J_3\big(x_0^{(n)}\big)}$$ Expanding for large values of $n$ and continuing with Taylor expansions
$$x_1^{(n)}=(n\pi-1)+\frac{s-c}{c+s}-\frac{9-4 c s}{4 \pi  n (c+s)^2}+O\left(\frac{1}{n^2}\right)$$that is to say
$$x_1^{(n)}=(n\pi-1)-\frac {4 \pi  n \cos (2)+(9-2 \sin
   (2)) }{4 \pi  n (1+\sin (2)) }+O\left(\frac{1}{n^2}\right)$$
A few numbers for illustration
$$\left(
\begin{array}{cccc}
 n & x_0^{(n)} & x_1^{(n)} & \text{solution} \\
 1 & 2.14159 & 2.06024 &  1.84118 \\
 2 & 5.28319 & 5.35149 &  5.33144 \\
 3 & 8.42478 & 8.54296 &  8.53632 \\
 4 & 11.5664 & 11.7095 &  11.7060 \\
 5 & 14.7080 & 14.8661 &  14.8636 \\
 6 & 17.8496 & 18.0176 &  18.0155 \\
 7 & 20.9911 & 21.1663 &  21.1644 \\
 8 & 24.1327 & 24.3133 &  24.3113 \\
 9 & 27.2743 & 27.4590 &  27.4571 \\
 10 & 30.4159 & 30.6040 &  30.6019 \\
\end{array}
\right)$$
Be sure that we could so much better. For example, the next term of the expansion would be
$$\frac{-67 \sin (1)+2 \sin (3)+195 \cos (1)+18 \cos (3)}{32 \pi
   ^2 n^2 (\sin (1)+\cos (1))^3}$$ and for $n=5$, it would give $14.8645$
Comment: Thank you very much!
Answer: I prefer to add a separate answer.
More or less, we want to find the zero's of function
$$f(t)=J_0(t)- J_2(t)$$
which are closer and closer to  $(n\pi-1)$ which is normal since these zero's are also those of
$$g(t)=t\, J_0(t)-J_1(t)$$
So, let
$$\large \color{blue}{ x_n=\rho_n\, r_{max}\,j_{0,n}}$$ and,  emprically, use
$$x_n=1+\sum_{k=1}^p \frac{a_k}{(n\pi-1)^k}$$
With $t=\frac 1 {n\pi -1}$
$$x_n=1-\frac{t}{35768}-\frac{3765 t^2}{3776}+\frac{1371
   t^3}{3877}-\frac{1092 t^4}{3167}-\frac{5258
   t^5}{3191}$$
The results using the exact values of $j_{0,n}$
$$\left(
\begin{array}{ccc}
n & \text{estimate} & \text{solution} \\
 1 & 1.841183798 &  1.841183781 \\
 2 & 5.331442543 &  5.331442771 \\
 3 & 8.536320547 &  8.536316357 \\
 4 & 11.70599581 &  11.70600490 \\
 5 & 14.86358308 &  14.86358863 \\
 6 & 18.01552771 &  18.01552786 \\
 7 & 21.16437382 &  21.16436986 \\
 8 & 24.31133342 &  24.31132686 \\
 9 & 27.45705857 &  27.45705057 \\
 10 & 30.60193159 &  30.60192297 \\
\end{array}
\right)$$
Now, look at this paper.
Comment: Very interesting. Your expression gives very close values to the true zeros, and it's easy to implement in Matlab. Thank you very much for all your efforts!


How can I ensure a referenced entity is cached separately per paragraph?

Question: I have a situation where two Paragraphs on single page may potentially reference the same entity.
The affected paragraphs have a field to change their colour, and this colour value is passed down to the referenced entity (via hook_preprocess_[entity-type]) for use in its template.

Node

field_paragraph

Paragraph1

field_colour
field_entity_reference (references entity:1234)

Paragraph2

field_colour
field_entity_reference (references entity:1234)

When I update Paragraph 1 to change its colour, this is currently affecting the colour of Paragraph 2 (because the entity is cached, including the colour value that is preprocessed into it).
I have tried adding a cacheable dependency (in hook_preprocess_[entity-type]) to transfer the cache tags for the paragraph to the entity, so that when the paragraph is updated, it invalidates the cache for the entity it is referencing:
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($variables, $referring_entity);

I have also tried replacing $variables in the above with $variables['elements'] and $variables['content'], but either way this does not seem to work as I expected.
Any advice appreciated.
Answer: So the easiest option likely is to just disable caching completely for the embedded entities.
In hook_entity_view(), unset $build['cache']['keys']. They are then still cached as part of the paragraph render cache, but don't have their own cache entry anymore.
To avoid not caching them when they are shown somewhere else, you should use a special view mode when you integrate them in paragraphs and only disable caching for that.
Note that you could also set max-age = 0 but that means "this content must not be cached at all", that information would bubble up to the paragraph and host entity and none of those would be cached anymore. That's not what you want.
Or you could change your approach and apply that color through a class that is set on the paragraph level, without changing the HTML of the embedded entity. Doesn't work for everything, but for a simple color change, that is likely easier to implement.
Comment: Thanks berdir, that is exactly the perspective I needed. In my case this content type is only ever displayed in the referenced context, so keeping a separate cache for the entity inside the paragraph made no sense.
Answer: The accepted answer worked for me, but I'd like to update with another method that also worked in my case and kept the rendered entities cached:
function hook_preprocess_paragraph(&$variables) {
  foreach (Element::children($variables['content']['field_your_field']) as $index) {
    $child = &$variables['content']['field_your_field'][$index];

    if (your view switching logic) {
      $child['#view_mode'] = 'your_new_view_mode';

      // Update cache keys
      array_pop($child['#cache']['keys']);
      $child['#cache']['keys'][] = $child['#view_mode'];
    }
  }
}


Usar drop ou iloc na modelagem para Machine Learning no Pandas?

Question: Estou aprendendo Machine Learning para Data Science através do Pandas. Fiz alguns poucos algoritmos e realizava a divisao das minhas variáveis previsoras e classe da seguinte forma:
dados = pd.read_csv(...)
(...)
previsores = dados.drop('income', axis=1)
classe = dados['income']

Porém, comecei a percerber algumas pessoas usando o iloc, por exemplo:
dados = pd.read_csv(...)
(...)
previsores = dados.iloc[:,0:14].values
classe = dados.iloc[:,14].values

Eu estava achando que ambos poderiam estar corretos, mas percebi que o type do primeiro era um DF do Pandas e o do segundo um numpy.array.
Alguém poderia me esclarecer se a forma como eu estava fazendo antes era errada, e quais as implicações de fazer de uma ou de outra forma?
Comment: André, bom dia! Não é questão de errado ou certo. Alguns algoritmos pedem um numpy array, outros você pode entregar como um data frame mesmo. No seu exemplo, caso você faça `dados['income'].values` também terá o array do numpy, independentemente de utilizar o `loc`ou `iloc`. Com iloc ou slicing geralmente você não precisa se preocupar com o nome das colunas.
Comment: Entendi, muito obrigado. No meu caso aqui eu tenho que usar o OneHotEncoder, portanto necessito de Arrays!
Answer: O que acontece é o seguinte, o iloc recebe dois parâmetros, linhas e columnas: iloc[linhas,colunas]. Linhas pode ser uma única linha ou mais de uma (o mesmo vale pra coluna). Se for apenas uma você simplesmente diz qual o número da linha, se for mais de uma você pode usar uma lista ou um intervalo, que no python se representa com :.
Como funciona esse intervalo: começo:fim:passo representa um intervalo que se inicia em começo termina antes de fim pulando de passo em passo, por exemplo 1:10:2 vai usar os números de 1 até 10, sem incluir o 10, pulando de 2 em 2, ou seja: 1,3,5,7,9. Quando você não define o passo, o python intende que ele é 1. Então 0:5 seria 0,1,2,3,4. O passo também pode ser negativo 4:1:-1 seria 4,3,2. quando você não define o começo, o python intende que o começo é 0. Portanto 0:14 é a mesma coisa que :14. Por último, se você não define o fim, o python entende que ele deve pegar o intervalo inteiro.
No caso do seu código nós temos dois intervalos sendo usados no iloc. O primeiro é dados.iloc[:,0:14] onde está sendo informado que para a coluna o intervalo é :, ou seja, nem o começo, nem o fim e nem o passo estão sendo definidos, o que significa que o python ira utilizar todas as linhas, da linha 0 até a última, inclusive. Para a coluna 0:14 indica que serão todas as colunas da coluna 0 até a coluna 14, sem incluir a coluna 14 (de 0 a 13). Então você tem várias linhas e 14 colunas. Ou seja, uma matriz de 2 dimensões. No segundo caso você tem iloc[:,14], que significa mais uma vez todas as linhas, mas apenas da coluna 14. Ou seja, você tem apenas uma dimensão.
Para o pandas, dados.iloc[:,14] seria ainda um DataFrame com uma única coluna, mas .values pede pro pandas te retornar os valores desse DataFrame e, segundo a definição do pandas, se esse DataFrame tem uma única dimensão, ele te retorna um array de numpy.
Comment: Muito boa a explicação, essa questão dos intervalos eu já estava entendendo, mas mesmo assim o seu comentário foi bem esclarecedor.
Minha dúvida era mais mesmo relacionada a qual seria a diferença em relação aos tipos e como isso influenciava no código, mas como responderam acima, para determinadas situações é melhor manter como DF (copiando e apenas dropando as colunas inuteis) e em outros casos é melhor array.

No meu caso, estou usando o OneHotEncoder, que necessita de arrays, portanto o meu método anterior estaria 'errado'.

Valeu pela explicação, vou até salvar o comentário kkkkk
Comment: Obrigado. Se você achou que ajudou peço, por favor, que marque como útil.
Comment: Marquei!! valeu aí
Comment: pra marcar como útil você precisa clicar uma vez na setinha para cima à esquerda da pergunta.


Typeahead.js not showing any results

Question: I'm trying to get Twitter's typeahead to work, but can't figure out how. As far as my knowledge goes, I've included the files correctly, but it still won't work.
My code looks like this:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <title></title>

    <input id="search"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <link rel="stylesheet" href="./views/css/index.css" media="screen" title="no title" charset="utf-8">

index.js
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

$(document).ready(function() {
  $('#search').typeahead({source: states});
})

Answer: JS fiddle sample (click):
var states = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: states
});

Typeahead.js not showing any results


Outlook API Limitations

Question: I am new to APIs and I want to make a program that will mark certain messages as being read with meating certain conditions. It this possible to do with the outlook api.
I am looking to have the user select a time duration and maybe a list of people that will mark read too.
Also if anyone has any resources for learning their api please post below.
Answer: You can develop an Outlook add-in or just automate Outlook from an external application to get the job done. The Outlook 2013 developer reference section in MSDN describes all the necessary information for developers.
See Walkthrough: Creating Your First Application-Level Add-in for Outlook to get started with an add-in. And the How to automate Outlook and Word by using Visual C# .NET to create a pre-populated e-mail message that can be edited page describes how to automate Outlook (C# app automates Outlook (CSAutomateOutlook)).
To find items that correspond to your conditions use the Find/FindNext or Restrict methods of the Items class.
Answer: Sure, set MailItem.UnRead property to false.
Comment: Is there a method to set that value or do you have to produce your own?
Comment: I am not sure I understand - you will need to write your own code that programmatically accesses the messages that satisfy your criteria and set the MailItem.UnRead property to false.

Outlook API Limitations


Alternate Criterias for MA in Music (or any other Degree that increases likelihood of getting Orchestras play my works)

Question: Greetings MusicStackExchange,
I put my intention first (I'm in HighSchool, You might need this information to understand why I'm asking this question) : I wish to work with Orchestras and Hopefully get them to play my compositions, But doing a BA in Music is highly improbable.
I read up related topics in MSE BA with no prior Musical Education, Is MA / PhD necessary at all? and How Composers get their Work Performed
I realize that Orchestras are really really big time and having an MA will not necessarily mean that Orchestra will play my work, But still-
.
Without BA in Music, Is it possible to Pursue MA in Music and continue with Other Music Stuff?
I will either be doing Physics for B or Major Computer Science and Minor Physics.
1. What are the Course Credits required for MA if I can take them as electives?
2. Or is knowledge in areas covered in BA and completing prerequisites unofficially enough?
3. Will Trinity Diplomas like the FMusTCL suffice?
4. Are there online courses for this purpose and will these be considered when Applying for MA in Music.
.
If all of these are valid options, I'd prefer going with 3. Mostly and taking 2. in the side too, because I can't be sure if the Required Courses will be there as Electives in the Universities I might be going for. I understand that the answer might vary from University to University, but I seek a general answer. Or if not MA, Is there anything else that serves the purpose? (I'm Trinity Grade 5 in Theory and 2 in Piano now and have IGCSE O Level in Music for which I did Guitar, Composition,and Theory Component consisted of (Not so Deep, Hardly Analysis) Analysis of Mendelsohn 5th and Overview of Latin American Music just in case these might shape the answer)
Comment: First decide whether you want a reliable job (physics) while attempting to compose.  Even with multiple music degrees,  99.9% of all aspiring composers fail to get even a single piece published.   It is not an easy life.
Comment: This question is way too broad. You have many different question, a lot of assumptions need to be made to even start answering some of the questions and to several of the question don't have objective answers.
Comment: To whoever Downvoted the Question, Can I please know where I can Improve the Question?

@CarlWitthoft, Yes I need a reliable Career (not job exactly) in Physics. By Physics I mean, BSc (Research) Course and not the BTech one. [Kind of Ambitious, but I'm working on all that I have to do for these two]
Answer: At least in the US, I can clarify that many schools, including conservatories, do allow Masters students that do not have Bachelors degrees in music. I've had Masters students whose Bachelors were in nursing, business, and even law. They tend to have a more difficult time navigating their Masters coursework since so much of the material is so new to them, but they have all gone on to do really great things in the musical world.
But ultimately, such a determination is up to the university itself. You would need to look into the schools you would consider for the Masters to see if they would be interested. Typically you will have to take an entrance exam of some kind to show that you can be successful in a musical program. Often there is both a theory exam and a music history exam to test your abilities, and in many schools doing poorly on these exams will remove you from consideration. And these exams are both in addition to the specifics of a program: an audition for performers, or a score submission (and perhaps analytic writing) for composers.
But like most things in music, it's not a piece of paper that matters, it's your skill. If you're good enough to get accepted into a Masters program in music, not having a sheet of paper (the Bachelors degree in music) typically won't hurt.
Which ultimately brings me to my next point: orchestras don't really care what your pieces of paper are, they just care about how good your music is. So don't think of the Masters as an entry point into having orchestras perform your pieces.
Instead, think of a degree program as an entry point into learning how the world of music works and how to network within that system. As Carl says, there are countless composers out there, and they're writing new pieces every day. Their pieces are performed because they've been working their way up the system: studying with famous composers, having their pieces performed by smaller ensembles (typically good ensembles at famous music schools), submitting their works and winning composition contests, slowly building a studio and a reputation of their own (which may demand a doctorate if you're teaching at a university), and landing commissions.
With that in mind, my suggestion is to be as active as you can right now so as to try and build a successful future as a composer.
Comment: Thank You for the Answer Sir. I got your point - It's more about How good my Music is and not How good my Resume is and I can always build it from scratch like how you pointed out - Studying Composers, Smaller Ensembles, Compo Compos. One thing : You said that you've had masters students who didnt have Bachelor's in Music right? Is there anything more than I can know? Were they required to have any of these before joining - Diploma/Grades in Music/Thorough Knowledge of BA Materials?
Answer: You have to ask yourself what is the point of a degree. Music is one of those things that does not really need a degree. What one needs is knowledge and skill, and both of those things can be achieved through study with a skilled private teacher, lots of reading/research, and LOTS of practice.
The benefit of school is that these things can often be done at a faster pace because, instead of trying to do it on one's own, one is directed through classes and syllabi and must meet deadlines. Also, while going to school, classes become most of the focus of life rather than adding self-initiated study onto an already-busy life full of outside responsibilities.
A Master's degree in music does not necessarily make one more successful as a performer/composer. It is most beneficial if one's future goals are teaching (often requiring going on for a PhD if looking for work at a university), or if one needs the networking like Richard mentioned.
Graduate school is an enormous endeavor, and if you are not at a really competitive skill level to qualify for scholarships or fellowships, a very expensive one. At minimum, you will need to have the knowledge and skill level a student with a Bachelor's in music achieves, or expect to put in the time and expense to make up for what you lack.
If your goal is to get a Master's in music, make a plan on how you will learn the theory and history you need to be prepared and how you will develop your skills as a composer enough to pass an audition. Though private lessons are usually available to all students, most of the upper-level Music Theory and Music History in undergraduate programs are not usually open to non-music majors, and they all require prerequisites, so you will need find a way to learn those topics on your own.


Error "from itsdangerous import json as _json ImportError: cannot import name 'json' from 'itsdangerous'"

Question: On deploying a Flask application to Google Cloud Platform, I get this error:
[ERROR] Exception in worker process from itsdangerous import json as _json ImportError: cannot import name 'json' from 'itsdangerous'

2022-02-18 08:00:30 default[20220218t132659]  Traceback (most recent call last):
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
  worker.init_process()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process
  super().init_process()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process
  self.load_wsgi()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
  self.wsgi = self.app.wsgi()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
  self.callable = self.load()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
  return self.load_wsgiapp()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
  return util.import_app(self.app_uri)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app
  mod = importlib.import_module(module)
File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
  return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/srv/main.py", line 16, in <module>
  from flask import Flask, render_template,make_response,jsonify, abort, send_from_directory, request, redirect
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/__init__.py", line 19, in <module>
  from . import json
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/json/__init__.py", line 15, in <module>
  from itsdangerous import json as _json
ImportError: cannot import name 'json' from 'itsdangerous' (/layers/google.python.pip/pip/lib/python3.7/site-packages/itsdangerous/__init__.py)

Comment: Importing itsdangerous.json is deprecated. Import Python's json module instead.
Answer: Flask 1.1.2 is set up to require itsdangerous >= 0.24. The latest released (itsdangerous) version (2.10) deprecated the JSON API.
To continue using Flask 1.1.2, you need to require at most itdangerous 2.0.1 (not 2.10). You can do this by adding
itsdangerous==2.0.1

...to your requirements.txt file (or wherever you list your dependencies).
itsdangerous 2.10 changelog
Answer: I just had the same issue and upgraded Flask to version 1.1.4, but then I got:

'soft_unicode' from 'markupsafe'

This issue seems to be related: ImportError: cannot import name 'soft_unicode' from 'markupsafe' in Release 1.38.0 #3661
Downgrading markupsafe to version 2.0.1 fixed it for me.
Comment: Ran into this same issue. Kept "flask=1.1.2" and specificied "itsdangerous==1.1.0" as per the recommendation here, it worked.
 https://cloud.google.com/functions/docs/writing/specifying-dependencies-python#pre-installed_packages
Answer: Either update Flask to 1.1.4, or fix itsdangerous version to 2.0.1
Comment: Is anyone by any chance also using connexion?  I am, and I see pip using Flask 1.1.4 but the markupsafe problem remains.  Just speculating that it might be from connexion?
Answer: I found the same problem today.
I used Flask in version 1.1.2. The problem disappeared after an update to version 1.1.4.
Comment: I see the markupsafe problem with Flask 1.1.4; maybe I'm using some other package that pins the version differently from what Flask wants?


hadoop h2o r, h2o.importHDFS, error

Question: Using R-hadoop which is hosted at 172.16.53.31:8787, I am trying to import file from HDFS to H2O which is hosted at 172.16.53.31:54331 (originally 54321).
This error happened. Any idea?

Or any advices?
Please and thanks.
Sincerely,
Newb
Answer: It's hard to read the screenshot error pasted into the screen, but it looks like InvalidProtocolBufferException.
In this case, it looks like the "hdfs://172.16.53.31:" is not well-formed.
Try "hdfs://172.16.53.31" with no port.
Or try adding the correct port for your Hadoop installation.
If you give a totally wrong port, the thing you point to won't speak protobuf.
This error can also happen when the Hadoop client version is too different from the Hadoop server version.  (Note that if you start H2O with the 'hadoop jar' method, the correct Hadoop libraries are put on the client classpath by 'hadoop jar'.)
If you start H2O using 'hadoop jar' then you generally pick up the name node from the environment, and can just give "hdfs:///path/to/file.csv" with no name node specified.
Answer: I did have the same problem.
Try to add the 9000 port number to your hdfs path.
Something like this:
<code>hdfs://<ip>:9000/<dataPath>/
</code>

hadoop h2o r, h2o.importHDFS, error


Football coaches who have won multiple FIFA World Cups

Question: Has there been any coach(manager) that has won the world cup more than once? If so, please provide the manager's name, winning years and team(s) managed.
Comment: See also Wikipedia: [FIFA World Cup records - Coaches: tournament position](http://en.wikipedia.org/wiki/FIFA_World_Cup_records#Coaches:_tournament_position). About players: [List of players who have won multiple FIFA World Cups](http://en.wikipedia.org/wiki/List_of_players_who_have_won_multiple_FIFA_World_Cups)
Answer: Italy's Vittorio Pozzo was the first person to have won two FIFA World Cups as a coach (1934, 1938)
Source: Wikipedia
Answer: Jill Ellis has won consecutive FIFA World Cups in 2015 and 2019 as a coach, the second person to do so.
Source: Wikipedia
Comment: Unless you wrote something wrong, that's not what "consecutive" means.


Multiple parameters in seed lambda expression

Question: I am utilizing the Seed() method to populate my database. I am trying to pre-populate one table with data based on two keys, not just one.
For example, I am doing this elsewhere and it is working fine:
foreach (var drug in Drugs)
{
    context.Drugs.AddOrUpdate(
        d => d.OrderId,
        drug
    );
}

Is it possible to do something like the following?
foreach (var pd in PatientDrugs)
{
    context.PatientDrugs.AddOrUpdate(
        (p => p.DispenseDate && p => p.DrugId),
        pd
    );
}

Answer: Did you try this?
foreach (var pd in PatientDrugs)
{
    context.PatientDrugs
        .AddOrUpdate(p => new { p.DispenseDate, p.DrugId }, pd);
}


Concatenating date and time fields

Question: I have a table invoices with this fields:
invDate -> a date field
invTime -> a time field

I need to do querys like
SELECT top 10 * from invoices WHERE DATETIME(invDate+invTime)
BETWEEN DATETIME('2013-12-17 17:58') AND DATETIME()

or something like that. I don't know how to concatenate the invDate and invTime to create a datetime field. The only thing that i could do is this horribly thing:
DATETIME( YEAR(invDate), MONTH(invDate), DAY(invDate), 17, 52 ) AS MyDatetime

Couldn't even get hour and time with hour(invTime) and minute(invTime):
DATETIME( YEAR(invDate), MONTH(invDate), DAY(invDate),
HOUR(invTime), MINUTE(invTime) ) AS MyDatetime

I'm doing the querys throught the VFP Odbc Driver via PHP.
Answer: You were pretty close.  If the value coming from PHP is not of a date/time, how could VFP interpret it properly.  VFP also has a function CTOT()  (character to time), and expects it in the format of 'yyyy-mm-ddThh:MM:ss??'
yyyy = 4 digit year
mm = 1 OR 2 digit month
dd = 1 OR 2 digit day
T -- literally the letter "T"
hh = 1 OR 2 digit hour (but typical is 2 anyhow)
MM = 1 or 2 digit minute (but typical is 2)
ss = 1 or 2 digit for seconds -- not required
?? = "AM" or "PM" if you wanted to explicitly provide that vs 24 hour clock

The MM and ss are optional, so if you finished with "T1" would be 1:00:00am
Now, to finish your query.
WHERE DATETIME(invDate+invTime)
BETWEEN DATETIME('2013-12-17 17:58') AND DATETIME()

Since this appears to be querying all invoices between a given date/time and NOW (via DateTime()), you don't even need between, you can do
WHERE YourTable.Column > CTOT( '2013-12-17T17:58')

If you specifically DID have a date/time range to consider, THEN you could do something like
WHERE YourTable.Column BETWEEN CTOT( '2013-12-05T10:00') AND CTOT( '2013-12-14T11:58')

PROBLEMS WITH your DATE() and TIME() implementations
The problem is Date() is a function to either return current date, or create based on y/m/d provided such as date( 2013, 12, 7 ).  If you are passing a string, use CTOD( 'mm/dd/yyyy' ) such as CTOD( 12, 7, 2013 ).
As for the TIME() function that just expects a number and is of no use for you.  From the OleDbProvider, your best bet is to just create a php function that builds a single string in the CTOT() format I've described and pass to the php function the date and time fields.  Then use that as your "CTOT( functionReturnResult )"
Comment: I need to use BETWEEN because the dates are coming from a form to generate reports. Thank you about the CTOT, it's working. The only thing i can't do at this time is concatenate the date and time into a single datetime field. DATETIME(invDate+invTime) is not working. Because if i try with AND invDate > DATE('2013-12-05') AND invTime > TIME('11:18') AND invDate < DATE('2013-12-07') AND invTime < TIME('12:00') is not working.
Comment: @CarlosGoce, see revision bottom of this answer
Answer: To add a Date  and a Time Field together you will need to convert them both to a same datatype 1st and than just simply add them together something like this....
DECLARE @D DATE = '2013-12-17'
DECLARE @T TIME = '17:58:00'

SELECT CAST(@D AS DATETIME) + CAST(@T AS DATETIME)

Result
2013-12-17 17:58:00.000

Your Query
SELECT top 10 *
from invoices
WHERE CAST(invDate AS DATETIME) + CAST(invTime AS DATETIME)
BETWEEN '20131217 17:58:00.000' AND GETDATE()

Comment: Sorry, i forgot to tell that i'm using vfp from PHP with the ODBC driver. Looks like i'm doing something wrong or is not supported if i try with CAST('2013-12-17' AS DateTime) i got "function name is missing". Or CAST(invdate AS DATETIME). That means that CAST didnt exists?

Concatenating date and time fields


Evaluating $\lim\limits_{x\to \infty}\frac{x^2}{2^x-1}$

Question:
I would like to evaluate
  $$\lim_{x\to \infty}\frac{x^2}{2^x-1}$$
  Without using L'HOSPITAL's rule nor series.

I tried more than one
technique such the sub
$$x=\frac{1}{y}$$
But i could not get the solution ?
Comment: For all integers $n$ we have, by the binomial theorem
$$2^n-1=(1+1)^n-1=\binom n1+\binom n2+\binom n3+\cdots\ge\binom n3=\frac{n(n-1)(n-2)}6.$$ Try with that!
Comment: Thank you @JyrkiLahtonen
Comment: it is very closed to this:  https://math.stackexchange.com/q/2587440
Answer: Using the hint provided by Jyrki Lahtonen in the comments, we may sneakily apply the binomial theorem in order to obtain
$$ 2^n - 1 = (1+1)^n - 1 = -1 + \sum_{k=0}^{n} \binom{n}{k} \ge \binom{n}{k} $$
for any choice of natural number $k$ less than $n$.  This implies that
$$ \frac{n^2}{2^n - 1} \le \frac{n^2}{\binom{n}{k}}. \tag{1}$$
By choosing $n$ large enough, it is possible to find a value of $k$ such that $\binom{n}{k} \gg n^2$.  For example, if $k = 3 < n$, then we have
$$ \binom{n}{3} = \frac{n!}{(n-3)!3!} = \frac{n(n-1)(n-2)}{3\cdot 2}. $$
Plugging this into (1), we get
$$\frac{n^2}{2^n - 1}
\le \frac{n^2}{\binom{n}{3}}
= 6 \frac{n^2}{n(n-1)(n-2)}
= \frac{6n^2}{n^3 - 3n^2 + 2n}.
$$
The expression that we want to limit is positive for any $n > 0$, thus applying the squeeze theorem we can take limits to get
$$ 0 \le
\lim_{n\to\infty} \frac{n^2}{2^n - 1}
\le \lim_{n\to\infty} \frac{6n^2}{n^3 - 3n^2 + 2n}
= \lim_{n\to \infty} \frac{\frac{6}{n}}{1 - {\frac{3}{n}} + \frac{2}{n^2}}
= 0.
$$
(The last expression, obtained via multiplication by $\frac{1/n^3}{1/n^3}$ is perhaps not strictly necessary, but I think that it aids in understanding—more generally, we might simply recall that the limit (at infinity) of a rational expression is 0 if the degree of the numerator is smaller than the degree of the denominator; $\infty$ if the numerator has greater degree, and some nonzero constant if the numerator and denominator have the same degree.)
EDIT:  I left off a step of the computation that seemed obvious to me, but for the sake of completeness, all that has been shown above is that if
$$ \lim_{x\to \infty} \frac{x^2}{2^x - 1} $$
exists, then it must be equal to 0.  To finish the argument, we might note that
$$ \frac{x^2}{2^x - 1}
\le \frac{\lceil x \rceil^2}{2^{\lfloor x \rfloor} - 1}
= \frac{(\lfloor x \rfloor + 1)^2}{2^{\lfloor x \rfloor} - 1}
= \frac{\lfloor x \rfloor^2}{2^{\lfloor x \rfloor} - 1} + \frac{2\lfloor x \rfloor + 1}{2^{\lfloor x \rfloor} - 1}. $$
The first term is exactly the one analyzed with $n = \lfloor x \rfloor$.  The second term can by analyzed similarly.
Alternatively, with
$$ f(x) = \frac{x^2}{2^x - 1}, $$
look at $f'(x)$, and note that $f'(x) < 0$ for $x$ sufficiently large (using the same kinds of estimates as above; this requires a little work, but is not unreasonably difficult).  Since the derivative is negative, the function is decreasing.  Moreover, the function is nonnegative for all $x > 1$, and so bounded below by zero.  As $f(x)$ is monotonically decreasing and bounded, it must have a limit.  By the above argument, the limit is zero.
Comment: You've shown that the limit when taken as $n \to \infty$ (where $n$ is a _natural_ number) is $0$. This does not imply that the limit as $x \to \infty$ (where $x$ is a _real_ number) is $0$ (at the very least, the argument is incomplete).
Comment: I've actually shown something slightly stronger:  if the limit exists, then it must be zero.  To prove that the limit exists, note that $2^x - 1 \ge 2^{\lfloor x \rfloor} - 1$ and $x^2 \le \lceil x \rceil ^2$.
Answer: Enforcing the changes of variables $ u= \frac{x\ln(2)}{2}$ gives $$\lim_{x\to \infty}\frac{x^2}{2^x-1} =\lim_{x\to \infty}\frac{x^2}{2^x}\cdot\frac{1}{1-\frac{1}{2^x}}= \lim_{x\to \infty}x e^{-x\ln(2)}\\= \lim_{x\to \infty}\frac{4}{\ln^2 2}\left(\frac{x\ln(2)}{2}e^{-\frac{x\ln(2)}{2}}\right)^2 =\lim_{u\to \infty} \frac{4}{\ln^2 2}\left(ue^{-u}\right)^2  =0$$
se also here  https://math.stackexchange.com/q/2587440.
Answer: Note that
$$\frac{x^2}{2^x-1}=\frac{2^x}{2^x-1}\cdot \frac{x^2}{2^x}\to1\cdot0=0$$
indeed
$$\frac{2^x}{2^x-1}=\frac{1}{1-\frac{1}{2^x}}\to 1$$
and since eventually, notably for $x>10$, we have that $2^x>x^3$
$$\frac{x^2}{2^x}<\frac{x^2}{x^3}=\frac1x\to0$$
EDIT
Proof by induction of $2^n>n^3$.
Base case
$n=10\implies2^{10}=1024>10^3=1000$
Induction step
We need to prove that
$2^n>n^3\implies 2^{n+1}>(n+1)^3$
Let observe that
$$2^{n+1}=2\cdot 2^n\stackrel{\text{inductive hypothesis}}\ge 2\cdot n^3 \stackrel{\text{?}}\ge (n+1)^3$$
and the last inequality is true since
$$2\cdot n^3 \ge (n+1)^3=n^3+3n^2+3n+1\iff n^3 \ge 3n^2+3n+1 \quad \square$$
Comment: @gimusi Did I miss something or you still have to prove $\log x /x < \log 2/3$ ?
Comment: How will you prove $2^x > x^3$ for $x > 10$ ?
Comment: @user45914123 I think the crux of the matter here is how OP defines $b^x$ for $b>0$, $x \in \mathbb{R}$.
Comment: @user45914123 it can be easily shown for example taking the loglog both side from$$2^x>x^3 \iff x\log 2>3\log x \iff \frac{\log x}{x}<\frac{\log 2}{3}$$
Comment: @user45914123 we need to show that $\log x/x \to 0$ that is easily from $e^x/x \to \infty$ that is easily from $e^n/n \to \infty$ by ratio test. Or maybe it is convenient derive directly $x^2/2^x\to 0$ from $n^2/2^n \to 0$. If Hussien Mohamed I will give others details, but I suppose he did this basic limits by himself.


Avoid duplicate pair of json array

Question: I am making a matchmaking system where entries will be matched if they have the same weight. My target is to avoid the multiple fights of my entries. As we can see on the result of my snippet. We can see that player 1 and player 2 got matched for the first time. After that, player 1 got matched again with player 2 for the second time. My target is to add another if statement to avoid the multiple entry. Any help will be appreciated. Thank you

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
  },
  {
    entryID: 2,
    entryName: "player1",
    weight: 1900,
  },
  {
    entryID: 3,
    entryName: "player2",
    weight: 1900,
  },
  {
    entryID: 4,
    entryName: "player2",
    weight: 1900,
  },

];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement);

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize &&
        accItem[0].weight + different >= item.weight &&
        !accItem.find((obj) => obj.entryName === item.entryName )
    );
    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }
    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {

    const key = [index, ...item.map((item) => item.weight)].join("_");
    acc[key] = item;
    return acc;
  }, {});

  return namedDataGroups;
}

console.log(combine(source));

This is the result of my snippet above:
{
  0_1900_1900: [{
  entryID: 1,
  entryName: "player1",
  weight: 1900
}, {
  entryID: 3,
  entryName: "player2",
  weight: 1900
}],
  1_1900_1900: [{   // player 1 and player 2 got matched again. I need to avoid multiple fight
  entryID: 2,
  entryName: "player1",
  weight: 1900
}, {
  entryID: 4,
  entryName: "player2",
  weight: 1900
}]
}

This is my target result: (
{
    0_1900_1900: [{
    entryID: 1,
    entryName: "player1",
    weight: 1900
  }, {
    entryID: 3,
    entryName: "player2",
    weight: 1900
  }],
    1_1900: [{
    entryID: 2,
    entryName: "player1",
    weight: 1900
  }],
    2_1900: [{
    entryID: 4,
    entryName: "player2",
    weight: 1900
  }]
  }

Comment: I'm sorry, i edited it right now. It is supposed to be 1900 too.
Comment: Can you please clearly define the criteria of matchmaking?  Why would players enter the competition more than once? Any why in your target result are you including / wanting `result[1]`'s entries to be wrapped as individual arrays? A clear explanation to the above may make the question easier to answer.
Answer: I'll code it this way instead, given the test set being what it is, I can't guarantee that this code is 100% valid
First answer
(with § used to distinguish the grouped list of entryName for testing purposes)

const source =
  [ { entryID: 1, entryName: 'player1', weight: 1900 }
  , { entryID: 2, entryName: 'player1', weight: 1900 }
  , { entryID: 3, entryName: 'player2', weight: 1900 }
  , { entryID: 4, entryName: 'player2', weight: 1900 }
  ]

console.log ( combine(source) )

function combine( data = [], different = 0, maxGroupSize = 2
                , sortedStatement = (a, b) => a.weight - b.weight )
  {
  const
    sortedData = [...data].sort(sortedStatement)
  , related = []
  , groups  = []
    ;
  sortedData.forEach((el,indx)=>
    {
    let place = groups.findIndex( g => g.names.length < maxGroupSize
                                    && !g.names.includes(el.entryName)
                                    && !related.includes(`${g.names.join('§')}§${el.entryName}`)
                                    && (el.weight - g.weight) <= different)

    if (place<0)
      {
      groups.push( { names: [ el.entryName], indxs: [indx], weight: el.weight } )
      related.push( el.entryName )
      }
    else
      {
      groups[place].names.push(el.entryName)
      groups[place].indxs.push(indx)
      related[place] += `§${el.entryName}`
      }
    })
  return groups.reduce((r,g,i)=>
    {
    let key = `${i}_` + g.indxs.map(x=>sortedData[x].weight).join('_')
    r[key] = []
    g.indxs.forEach(x=> r[key].push( sortedData[x]) )
    return r
    }, {} )
  }
.as-console-wrapper {max-height: 100%!important; top:0; }
.as-console-row::after { display:none !important; }

Second solution using js new Set() (no needs of §)

const source =
  [ { entryID: 1, entryName: 'player1', weight: 1900 }
  , { entryID: 2, entryName: 'player1', weight: 1900 }
  , { entryID: 3, entryName: 'player2', weight: 1900 }
  , { entryID: 4, entryName: 'player2', weight: 1900 }
  ]

console.log ( combine(source) )

function combine( data = [], different = 0, maxGroupSize = 2 )
  {
  const
    groups        = []
  , related       = []
  , sortedData    = [...data].sort((a, b) => a.weight - b.weight)
  , alreadyInRela = (setX,eName) =>
    {
    let list = [...setX, eName]
    return related.some(rela=>list.every(l=>rela.has(l)))
    };
  sortedData.forEach((el,indx)=>
    {
    let place = groups.findIndex( // find a place in a group forEach element, use indx as track
        g => g.names.size < maxGroupSize              // is the group incomplete ?
            && !g.names.has(el.entryName)             // is entryName not in the group list (names Set) ?
            && (el.weight - g.weight) <= different    // is the weight falls within the weight range ?
            && !alreadyInRela(g.names, el.entryName ) // is (entryName + group list) does not already used ?
        )
    if (place < 0) // not found -> create new group
      {
      let names = new Set().add(el.entryName)                      // create new group
      groups.push( { names, indxs: [indx], weight: el.weight } )  // group constitutive info
      related.push( names )                                      // keep track of group list
      }
    else // find a place in a group
      {
      groups[place].names.add(el.entryName)  // related list is also updated
      groups[place].indxs.push(indx)        // add indx to retreive element in sortedData
      }
    })
  return groups.reduce((r,g,i)=> // build result
    {
    let key = `${i}_` + g.indxs.map(x=>sortedData[x].weight).join('_')
    r[key] = []
    g.indxs.forEach(x=> r[key].push( sortedData[x]) )
    return r
    }, {} )
  }
.as-console-wrapper {max-height: 100%!important; top:0; }
.as-console-row::after { display:none !important; }
Comment: Thanks, i'll study about this if this is flexible for my code since in the future, i will add more validations. Thank you.
Comment: I have tested your code now and added my validations and it works perfectly. Just another question. What does this "§" mean? It's my first time to encounter that. Also. Is it okay to give a little explanation about what you did in order to improve my code? Thank you
Comment: @UlquiorraSchiffer this character only serves as a separator between the values of entryName, to ensure that they are always unique in each group. But rereading my code, I tell myself that I was a bit too fast, and I work on a second answer; but I miss an important information before: are the entryNames sufficient to determine the composition of the groups? (or in other words: can there be 2 identical entryNames but with 2 different weights, thus making 2 distinct entries?)
Comment: @UlquiorraSchiffer I added a new version with no use of `§` tricks. There is also more comments
Comment: Sorry super late reply. Understood. Thank you for these. I super appreciate it.
Comment: Hello @Mister Jojo. If you have some free time, i hope you can take a look at this problem of Mine. https://stackoverflow.com/questions/71491731/add-another-validation-to-avoid-joining-the-array

Just need more validation to achieve my target. I have used your code and i need to add more validation. Thank you

Avoid duplicate pair of json array


joining outputs in powershell

Question: I have the below and I want to join all the outputs into a single line - so the output would look something like:
TCPIP.sys version is $one "." $two "." $three "." $four
I try and join them in powershell but I get the below error:

PS C:\Windows> $one = (get-childitem c:\windows\system32
  \drivers\tcpip.sys).Versioninfo.ProductMajorPart | fl *
PS C:\Windows> $two = (get-childitem
  c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductMinorPart |
  fl *
PS C:\Windows> $three = (get-childitem
  c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductBuildPart |
  fl *
PS C:\Windows> $four = (get-childitem
  c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductPrivatePart
  | fl *

Error:

PS C:\Windows> write-host = $one $two
  = Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntr yData
Answer: Like this:
<code>$one = ((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductMajorPart).tostring()

$two = ((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductMinorPart).tostring()

$three = ((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductBuildPart).tostring()

$four = ((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductPrivatePart).tostring()

write-host "TCPIP.sys version is $one.$two.$three.$four"
</code>
But this do the same in one line:
<code>$a = (get-childitem c:\windows\system32\drivers\tcpip.sys).VersionInfo.ProductVersion
write-host "TCPIP.sys version is $a"
</code>
Comment: btw - I am doing the above as "ProductVersion" number is different to what the GUI reports when you right-click the driver file. Weird why Powershell does not report the same numbers - I am looking for the ProductPrivatePart - but that is just a number and don't want to confuse the customer so putting it into a "nice" format for them
Comment: for me it's the same value via powershell or via rightcliking on tcpip.sys.
Answer: There's no need to query tcpip.sys four times. You can get the info from the ProductVersion property:
<code>(get-childitem $env:windir\system32\drivers\tcpip.sys).Versioninfo.ProductVersion
</code>
You could also use the Join operator:
<code>$one,$two,$three,$four -join '.'
</code>

joining outputs in powershell


Por que tem tantos parênteses em macro?

Question: Vendo isto, intriga porque precisa desses parênteses que parecem desnecessários.  Qual a funcionalidade deles?
#define SUB(x, y) ((x) * (y))

Answer: Porque macro é só uma substituição de textos, não é uma construção da linguagem que considera a semântica do código, sem os parênteses o argumento pode se confundir com a expressão. Veja
#include <stdio.h>
#define SUB_UNSAFE(x, y) x * y
#define SUB(x, y) ((x) * (y))

int main(void) {
    printf("%d\n", SUB_UNSAFE(4 - 4, 2));
    printf("%d\n", SUB(4 - 4, 2));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá pra ver que se os parênteses tem situação que o cálculo é feito errado porque a precedência na expressão se confunde com o argumento e mistura tudo porque na verdade fica assim:
4 - 4 * 2

Para visualizar melhor:
4 - (4 * 2) => 4 - 8 => -4

Mas o correto é:
(4 - 4) * (2) => 0 * 2 => 0

Por que tem tantos parênteses em macro?


BIOS keyboard buffer

Question: I decided to do some fun with assembly and bare-metal to increase my programming skills for operating system development. So I decided to make game similar to 'space invaders'.
I have made some working code, but the problem comes with Interrupt 0x16 AH=0x01.From Ralf Brown's Interrupt List we can read that this interrupt does NOT clear keyboard buffer. Because of that after clicking any control key once, my game believe that this key is kept pressed, and other key press are ignored, causing my ship to go infinity into one direction.
I have tried using AH=0x00 and it worked perfectly, however this would stop the game until any key is pressed, and I do not want that because I wont be able to update enemies position without waiting for user input.
I concider it to be problem with int 0x16 AH=0x01 and that the buffer is not cleared, however it may be something with either my lup or with call keyPressControl.
By the way I am using bochs to test my code and compiling my code with nasm
This is my code:
org 0x7C00
bits 16

xor ax,ax
mov ds,ax
mov es,ax

mov bx,0x8000
cli
mov ss,bx
mov sp,ax
sti

cld
clc

;clear 0x7E00 so we can check is code loaded later
xor ah,ah
mov BYTE [0x7E00], AH

;this code suppose to load game into memory
mov ah,0x2
mov al,0x4
xor ch,ch
mov cl,0x2
xor dh,dh
xor bx,bx
mov es,bx
mov bx,0x7E00
int 0x13
;code above should load code just above bootloader
;check if code is loaded
mov AH,[0x7E00]
cmp AH,0x0
je error

;Use normal jumpbecause bochs doesnt support Far Jumps (code often crashes)
jmp 0x7E00
;if cpu dont jump somehow then it will execute error and then hopefully halt
error:
    ;fill the screen with red color - the screen is supposed to run in graphics mode 0x2
    mov ah,0x40
    mov al,' '
    cld
    mov bx,0xb800
    mov es,bx
    xor bx,bx
    mov di,bx
    mov cx,0x0FA0
    rep stosw
    stosw

cli
hlt

times 0x1FE - ($ - $$) db 0x0

db 0x55
db 0xAA

;==============================
;game code
;==============================

;the game is designed to run in 16 bit real mode
;hide text mode cursor
mov ah,0x1
mov cx,0x2607
int 0x10
;show 'menu'
call clearTextModeScr
xor ax,ax
mov DS,AX
mov AX,GameName
mov SI,AX
xor AL,AL
mov bl,0x10
call printInTextMode
mov AX,TextInfo01
mov si,ax
mov al,0x6
call printInTextMode
mov AX,TextInfo02
mov si,ax
mov al,0x7
call printInTextMode
mov AX,TextInfo03
mov si,ax
mov al,0x8
call printInTextMode
mov AX,TextInfo04
mov si,ax
mov al,0x9
call printInTextMode
mov AX,TextInfo05
mov si,ax
mov al,0xA
call printInTextMode
mov AX,TextInfo06
mov si,ax
mov al,0xB
call printInTextMode
mov AX,TextInfo07
mov si,ax
mov al,0x17
call printInTextMode

;wait for x to start the game
mov bl,'x'
call waitForKeyPress
;init 0x13 graphics mode
call initGraphicsMode

lup:
    ;draw ship
    xor ax,ax
    mov ds,ax
    mov si,ship
    mov bx, [shipPosX]
    mov al, [shipPosY]
    call DrawPicture

    call KeyPressControl
    jmp lup
cli
hlt
;game functions

;this function will update new location of ship on screen according to player keypress
;this function will be using BIOS buffer from keyboard to not suspend the game
KeyPressControl:
    pusha
    pushf
    mov ah,0x1
    int 0x16
    jz .end
    cmp al,'a' ;left
    je .left
    cmp al,'d' ;right
    je .right
    cmp al,'s' ;backwards
    je .backwards
    cmp al,'w' ;forwards
    je .forwards
    jmp .end
    .left:
        cmp WORD [shipPosX], 0x00
        je .end
        dec WORD [shipPosX]
        jmp .end
    .right:
        cmp WORD [shipPosX], 0x12D
        je .end
        inc WORD [shipPosX]
        jmp .end
    .backwards:
        cmp BYTE [shipPosY], 0xA9
        je .end
        inc BYTE [shipPosY]
        jmp .end
    .forwards:
        cmp BYTE [shipPosY], 0x00
        je .end
        dec BYTE [shipPosY]
        jmp .end
    .end:
        popf
        popa
        ret

;this function winn wait till right key is pressed
;bl - ASCII key

;All registers and flags should be left the same
waitForKeyPress:
    pusha
    pushf
    .loop:
        xor ah,ah
        int 0x16
        cmp al,bl
        jne .loop
    popf
    popa
    ret

;this function will clear text mode screen to white text with black background

;All registers should be left the same
clearTextModeScr:
    pusha
    mov ah,0x0F
    mov al,' '
    cld
    mov bx,0xb800
    mov es,bx
    xor bx,bx
    mov di,bx
    mov cx,0x0FA0
    rep stosw
    stosw
    popa
    ret

;holy shit

;this function will generate pseudo random value
; Following registers will be changed:
;   AX - random generated number
random:
    push DX
    push BX
    ;multiplier is get by Read Time Stamp
    RDTSC
    mov BX,AX
    mov AX,[randomSeed]
    mul BX
    add ax,0xB7FF
    and ax,0x7FFF
    ;ax is random number
    mov WORD [randomSeed], ax
    pop BX
    pop DX
    ret

;this function will draw image on screen
;DS:SI - address of the picture start
;AL - Y coordinate (height)
;BX - X coordinate (width)

;Note that this funciton wont check for 0x13 graphics mode
DrawPicture:
    pusha
    mov cx,0x140
    mul cx
    add AX,BX
    ;AX is now offset on the screen
    mov bx,0xA000
    mov es,bx
    mov di,ax
    ;memory location of screen is now written in ES:DI
    ;now we need to get the size of picture
    lodsw ;get WORD into AX
    ;AL - X size
    ;AH - Y size
    xor cx,cx
    mov CL,AL
    cld
    .loopY:
        push ax
        push es
        push di
        push cx
        .loopX:
            lodsb
            stosb
            loop .loopX
        pop cx
        pop di
        pop es
        mov ax,0x140
        add di,ax
        pop ax
        dec ah
        cmp ah,0x0
        jne .loopY
    popa
    ret

;this function will draw box on screen
;AL - Y coordinate (height)
;BX - X coordinate (width)
;CL - X size
;DL - colour
;DH - Y size

;All registers should be left the same
DrawBox:
    pusha
    ;calculate the start point in memory
    ;multiply Y coordinate by 0x140 (width of each Y line)
    push bx
    mov bx,0x140
    mul bx
    pop bx
    ;add X
    add AX,BX
    ;AX is now offset on the screen
    mov bx,0xA000
    mov es,bx
    mov di,ax
    cld
    xor CH,CH
    .loopY:
        push es
        push di
        push cx
        ;.loopX will be repeated `CL` times
        .loopX:
            stosb
            loop .loopX
        pop cx
        pop di
        pop es
        mov ax,0x140
        add di,ax
        ;decrease dh
        dec dh
        ;repeat loop `DH` times
        cmp dh,0x0
        jne .loopY
    popa
    ret

;this function will return length of string in CX
;DS:SI - address of the text

; Following registers will be changed
;   DS:SI   - location of last byte of the string in memory
;   CX      - length of the string
getStringLenght:
    push ax
    xor cx,cx
    .loop:
        lodsb
        ;check is it terminate character
        cmp al,'#'
        ;if yes then finish
        je .end
        ;increase CX (length) and execute loop again
        inc cx
        jmp .loop
    .end:
        pop ax
        ret

;this function will not check is text mode set
;DS:SI - address of the text
;AL - Y coordinate (start)
;BL - X coordinate (start)

;text should be terminated with # sign
;
;All registers and flags should be left the same
printInTextMode:
    pusha
    pushf
    push bx
    mov bl,0x50
    mul bl
    pop bx
    xor bh,bh
    add ax,bx
    mov bx,0x2
    mul bx
    mov di,ax
    mov bx,0xb800
    mov es,bx
    mov ah,0x0F ;white colour on black background
    cld
    .loop:
        lodsb
        cmp al,'#'
        je .end
        stosw
        jmp .loop
    .end:
        popf
        popa
        ret

SYSerror:
    ;set text mode graphics
    call initTextMode
    ;if text mode graphics could not be set, then halt the CPU straight away
    jc .fullerror
    ;fill the screen with red color
    mov ah,0x40
    mov al,' '
    cld
    mov bx,0xb800
    mov es,bx
    xor bx,bx
    mov di,bx
    mov cx,0x0FA0
    rep stosw
    stosw
    ;halt the CPU
    .fullerror:
        cli
        hlt

;if error occured then carry flag will be set
;if function runned properly then carry flag will be cleared
;
;All registers should be left the same
initTextMode:
    pusha
    ;setgup graphics mode 0x02
    xor ah,ah
    mov al,0x2
    int 0x10
    ;get graphics mode
    mov ah,0x0F
    int 0x10
    ;check if the graphics mode is actually 0x02
    cmp al,0x02
    jne .err
    ;clear carry flag and return
    popa
    clc
    ret
    ;error set carry flag and return
    .err:
        popa
        stc
        ret

;if error occured then carry flag will be set
;if function runned properly then carry flag will be cleared
;
;All registers should be left the same
initGraphicsMode:
    pusha
    ;setup mode 0x13
    xor ah,ah
    mov al,0x13
    int 0x10
    ;get graphics mode
    mov ah,0x0F
    int 0x10
    ;check if the graphics mode is actually 0x13
    cmp al,0x13
    jne .err
    popa
    clc
    ret
    .err:
        popa
        stc
        ret

cli
hlt
;game data
;'variables'

randomSeed dw 0xBEAF
shipPosX dw 0x0000
shipPosY db 0x00

;Game texts
GameName db 'Lasers Lasers Lasers... And Even More Lasers#'
TextInfo01 db 'Controls:#'
TextInfo02 db 'A - Left#'
TextInfo03 db 'D - Right#'
TextInfo04 db 'W - Forward#'
TextInfo05 db 'S - Backward#'
TextInfo06 db 'Q - Weapon#'
TextInfo07 db 'Press x to begin game#'

;Game Pictures... YES PICTURES

;structure of pictures
;First WORD is size of picture. It is in following format

;ship 17x29 (0x11 * 0x1D) (1D is height, 11 is width)

ship:
    dw 0x1F13
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x2A, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x2A, 0x29, 0x29, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x2A, 0x29, 0x29, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x2A, 0x29, 0x29, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x29, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00
    db 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00, 0x00
    db 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00
    db 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x1E, 0x00
    db 0x00, 0x0F, 0x0F, 0x0F, 0x2A, 0x2A, 0x2A, 0x1E, 0x0F, 0x0F, 0x0F, 0x0F, 0x2A, 0x2A, 0x2A, 0x1E, 0x0F, 0x1E, 0x00
    db 0x00, 0x00, 0x0F, 0x29, 0x2A, 0x2A, 0x2A, 0x29, 0x1E, 0x0F, 0x0F, 0x29, 0x2A, 0x2A, 0x2A, 0x29, 0x1E, 0x00, 0x00
    db 0x00, 0x00, 0x0F, 0x29, 0x29, 0x2A, 0x29, 0x29, 0x1E, 0x0F, 0x0F, 0x29, 0x29, 0x2A, 0x29, 0x29, 0x1E, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x29, 0x29, 0x2A, 0x29, 0x29, 0x00, 0x1E, 0x00, 0x29, 0x29, 0x2A, 0x29, 0x29, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x29, 0x29, 0x00, 0x1E, 0x00, 0x29, 0x29, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x29, 0x29, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00
    db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

times 0x1000 - ($ - $$) db 0x0

Answer: I think what you're asking for is a way of checking for keypresses and removing them from the buffer without waiting?
Just use int 0x16/AH=01 to check for a key and if a keypress is in the buffer use int 0x16/AH=00 to clear it from the buffer. Your detection of keys will be limited by key repeat rate and delay, however.
In practice, most (old...) games trapped int 9 (I think it was) to detect key press/release, and then queried the keyboard controller directly (using port I/O), rather than using the BIOS routines - which are not really designed with games in mind.
Comment: http://stackoverflow.com/questions/24988886/scan-the-keyboard-to-obtain-scan-codes

BIOS keyboard buffer


Rules and Facts contradictory descriptions

Question: Standing to definitions :
A fact is a sentence that states that a relation holds between individuals. A rule is a relation that holds between individuals provided that some other relations hold.
According to this, why it is not possible to
construct contradictory descriptions using facts and rules ?
For example, i can use as facts the fact that a = b and a = not(b) and i have a contradiction....
Comment: I do not think. You have made many similar questions in the last few days: at least twelve. Most of them received answers: no vote (up or down), no accept; no requests for clarification; no feed-back at all. *If you are not interested in answers, why ask questions* ?
Comment: A [fact](https://plato.stanford.edu/entries/facts/) is a *fact* (a part of teh world) and not a sentence. A rule in logic is not "something that holds between individuals": this is a relation.
Comment: [Tird account of the day ?](https://math.stackexchange.com/questions/2647254/intended-model-vs-interpretation)
Comment: Im sorry if it's a problem. But im obsessed with knowledge :)
Comment: A *sentence* expresses a fact, i.e. something that holds or not. In FOL, an *atomic* sentence expresses a relation between *individual*: e.g. $x=x, P(a), R(x,y)$, etc.
Comment: Two *sentences* $\varphi$ and $\lnot \varphi$ are said to be *contradictory*. Thus, e.g., $a=b$ and $\lnot (a = b)$ are contradictory sentences.
Comment: In FOL we negate formulas and **not** "objects", i.e. (individual) variables and constants.
Comment: If i write the rule a(x) <-- not(a(x)) expressed as a definite sentence, this is unsatisfiable. So why using the language of definite programs, it is not possible to construct contradictory descriptions ?
Comment: The *rules* of logic must be *sound*, i.e. they must "transfer the *truth*", i.e. they must produce *true* conclusion from *true* premises. Thus, if the rule is sound and the conclusion is false, there must be some false premise.
Answer: Who on earth says "A fact is a sentence that states that a relation holds between individuals"?
At least in my neck of the woods, there are two common views about facts -- namely that facts are true propositions (true declarative sentences), or that facts are truth-makers, the sort of thing that makes a true proposition true. But on either view, truth comes into it! A sentence that states that a relation between individuals can be false, and so is neither a fact-qua-true-sentence, nor does it correspond to a fact-qua-truth-maker.
Comment: "Who says...?"  Logical Programmers do.
Comment: Shocked, I am, shocked I say! :)
Answer: You define a fact as an expression that says that some relation holds ... as such you can only express positive claims, and not any negations, i.e. you cannot express that some relation does not hold. The same is true for the rules: they apparently can only say that some relation holds when other relations holds, and so you cannot make any negations part of rules either. It is therefore impossible to use that $a \not = b$ as a fact, or make that part of a rule. And indeed, without negations you cannot get any contradictions at all.
Comment: This property of rules , is it connected to the fact that we use definite clauses to express rules ?
Comment: @Qwerto Well, it's because by only using positive claims you obtain a system for which you can define very efficient algorithms for checking logical consequence ... I assume this came up in the context of a logic programming course?
Comment: If a rule can say that some relation holds when other relations holds, why cant a rule say something as "if a(fact) so not(a)" ?
Comment: @qwerto if you say $a \not = b$ then you are not saying that some relation holds,but rather that some relation does not hold.
Comment: Maybe i've finally understood: everything we just said about facts and rules rest on the implicit principle that facts and rules are true ? It is that right ?


Triangles and Semicircles.

Question: Given any acute angled triangle $ABC$, let points $X, Y, Z$ be located as follows: $X$ is
the point, where the altitude from $A$ on $BC$ meets the outward facing semicircle
on $BC$ as diameter. Points $Y$ and $Z$ are defined similarly. Prove the result:
$[BCX]^2 + [CAY]^2 + [ABZ]^2 = [ABC]^2$, where the notation $[.]$ denotes the area of the figure.
A question from pathfinder for olympiad mathematics.
My Solution attempt:
using $\angle XGC = \theta=\angle XCG \implies \angle XGD=2\theta \ and \ \angle XGC=\pi - \theta
 $
Thus we get,by cosine rule,
$XD = XC^2(a^2-XC^2)$
Now i calculated the area of the triangle $BXC$ but couldnt go any furter, kindly proceed this.
Comment: Does this answer your question? [Prove that :$[BCA']^2+[CAB']^2+[ABC']^2=[ABC]^2$, where \[•\] denote the area.](https://math.stackexchange.com/questions/1937055/prove-that-bca2cab2abc2-abc2-where-denote-the-area)
Comment: @MyMolecules Some Links are missing in this.It would have been helpful if those links still existed.
Comment: Dear @MohitKumar , I edited them to working  links soon after I posted my comment. Please check again.
Comment: Thanks! It would surely help!
Answer: Let the orthocentre of the original triangle be $H$. Observe that, $AE\cdot EC=HE\cdot BE$ since $\triangle AEB\sim \triangle HEC$.
Thus, $EY^2=AE\cdot EC=HE\cdot BE$
Hence, $[\triangle ACY]^2=\frac {1}{4} AC^2\cdot HE\cdot BE=\left(\frac{1}{2} AC\cdot HE\right)\left(\frac {1}{2}AC\cdot BE\right)=[\triangle AHC]\cdot [\triangle ABC]$
Similarly,
$[\triangle BXC]^2=[\triangle BHC]\cdot [\triangle ABC]$
$[\triangle ABZ]^2=[\triangle AHB]\cdot [\triangle ABC]$
Adding these up gives the desired result.

Triangles and Semicircles.