SelectListItem com atributos costumizados

Question: Criei um DropDownList através do método abaixo:
private void PopulateDropDown() {
  //Chamo o método que obtém a lista de clientes da API
  List<Models.Cliente> clientes = new Business.Cliente().Get();

  //Rotorno a lista de clientes para a view
  ViewData["Clientes"] = new SelectList(clientes, "Id", "Nome", "IdGrupoCliente");

}

Classe Cliente:
public class Cliente{
  public int Id { get; set; }
  public string Nome { get; set; }
  public int IdGrupoCliente { get; set; }
}

View:

      Selecione o cliente:

   @Html.DropDownList("IdCliente", (SelectList)ViewData["Clientes"], new { @class = "form-control" })

Preciso criar um atributo costumizado nas options do meu select,  porém não estou sabendo a melhor forma de fazer isso. A minha ideia era adicionar um data-IdGrupoCliente como no exemplo abaixo:
<select class="form-control" id="IdCliente" name="IdCliente">
   <option value="1" data-IdGrupoCliente="10">Cliente Abc</option>
</select>

Comment: E se fizesse um método que fosse inteligente e carregasse a informação de uma classe padrão.?
Comment: Sugeriram sobrescrever o método do `DropDownList ` para prever esse tipo de situação, acho que é mais ou menos o que você quis dizer mas com outro método. Se quiser posta o que você está imaginando é bom ter varias soluções xD
Answer: Você precisa ter em mente que nem tudo pode ou deve ser escrito usando os HTML Helpers, eles servem para dar uma facilitada nas coisas, mas nos casos em que se precisa de mais liberdade é melhor optar não usá-los.
Ao invés de usar um SelectList, use uma List<Cliente> simples e crie as options da tag select manualmente através de um laço.
Veja um exemplo
Cliente.cs
public class Cliente
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public int IdGrupoCliente { get; set; }
}

HomeController.cs
public class HomeController : Controller
{
    private List<Cliente> _clientes = new List<Cliente>
    {
        new Cliente { Id = 1, Nome = "Julius", IdGrupoCliente = 2 },
        new Cliente { Id = 2, Nome = "Chris", IdGrupoCliente = 1 },
        new Cliente { Id = 3, Nome = "Drew", IdGrupoCliente = 2 },
        new Cliente { Id = 4, Nome = "Tonya", IdGrupoCliente = 1 },
        new Cliente { Id = 5, Nome = "Rochelle", IdGrupoCliente = 2 }
    };

    [HttpGet]
    public ActionResult Index()
    {
        ViewData["Clientes"] = _clientes;
        return View();
    }
}

Index.cshtml

   <select class="form-control" name="@Html.NameFor(model => model.IdCliente)" id="@Html.IdFor(model => model.IdCliente)">
      @foreach(var cliente in ViewData["Clientes"] as List<Sample.Cliente>)
      {
          <option data-id-grupo-cliente="@cliente.IdGrupoCliente" value="@cliente.Id">@cliente.Nome
          </option>
      }
   <select>

Veja funcionando no .NET Fiddle
Comment: Brooklyn + 1987
Answer: A solução que encontrei foi passar a lista de clientes através de um viewData[] e criar o <select> diretamente na View.
ViewData["Clientes"] = new Business.Cliente().Get(idDistribuidor);

Percorri a lista de clientes com um for preenchendo as <option> com o atributo costumizado a cada iteração:

 @using (Html.BeginForm("Index", "Importacao", FormMethod.Post, new { enctype = "multipart/form-data" })) {
   @Html.AntiForgeryToken()

                  Selecione o cliente:

               <select name="IdCliente" id="IdCliente" class="form-control">
                  <option value="-1">Selecione</option>
                  @{
           System.Collections.Generic.List<InpartSaude.Negociacao.Models.Cliente> clientes = (System.Collections.Generic.List<InpartSaude.Negociacao.Models.Cliente>)ViewData["Clientes"];
                      for (int i = 0; i < clientes.Count; i++) {
                         <option value="@clientes[i].Id" data-IdGrupoCliente="@cliente[i].IdGrupoCliente">
                            @clientes[i].Nome
                         </option>
                      }
                   }
                </select>

 }


Memory Exhausted after Drush install

Question: I've made a drush install of drupal 7.28 on my AWS server. I can confirm that the memory is set to 128M, all green on the reports -> site status page. The website will function normally and sporadically return no data, looking at the logs a tremendous amount of memory is trying to be allocated (assuming an infinite loop somewhere). Given that this is a basic install, no modules have yet been added what might be causing this?
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 140008587493184 bytes) in Unknown on line 0

Answer: Note that Drush and Drupal use different php.ini files.  This behavior is inherited from php, which allows for different configuration for commandline tools vs. web servers, so that your web server can be more locked down than your dev tools.
Use the drush status command to see the path to the php.ini file that Drush is using.
Use the drush status-report command to see the commandline equivalent of the reports -> site status page.  This will show you the real memory limit that is set for Drush.
Odds are, all you will need to do is change the memory limit setting in the php.ini file that Drush is using, and all will be well.
Comment: Are you using Drush 5 or older? `drush ev 'print ini_get("memory_limit");'`
Comment: I ran the status command, Drush is running off a php.ini that is set to -1 (unilimited) I know thats not good practice but Drush has the warpspeeds. Still having intermittent memory outages.
Comment: `drush ev 'return ini_get("memory_limit");'` should return -1 if in fact Drush is using the php.ini you think it is.  If this is the case, maybe you really are running out of memory for some reason.
Comment: That command didn't return anything, though its not Drush that is causing the memory issue (at least as I see it) the site while being used via a web browser is causing the memory errors
Comment: Greg, you da man! Was using drush 4.5 (default from the installer) updated to 5.0-dev and that ev command returns -1 so the memory is still unrestricted. I'll retry the install on the site and hopefully that'll fix it. Thank you!

Memory Exhausted after Drush install


Prove a tensor product's component is zero

Question: Suppose we have $R$-module elements $m\in M,n\in N$ with $m\otimes n=0\in M\underset{R}\otimes N$. Is it necessarily true that $m=0$ or $n=0$? I can't seem to prove it using the basic tensor product relations.
Edit: Okay, what about if $M$ and $N$ are vector spaces?
Comment: For the vector space case, it is indeed true that $m$ or $n$ must be zero. For assume they are not. Then pick $f\in M^*$, $g \in N^*$ with $f(m)=g(n)=1$ (which we can do because we are in a vector space and so for example we can extend $m$ to a basis of $M$ and define $f$ to be 0 on the other basis elements). Then $f\otimes g:M\otimes N\rightarrow \mathbb{F}$ sending $x\otimes y$ to $f(x)g(y)$ is a linear map which is not zero on $m\otimes n$, and hence $m\otimes n$ is not zero.
Answer: No. Consider $2 \otimes 1$ in $Z \otimes (Z/2)$.
Comment: By $Z/2$, do you mean $\mathbb{Z}/2\mathbb{Z}$? And if yes, do you claim $2 \otimes \bar 1$ is really _zero_ in $\mathbb{Z}\otimes\mathbb{Z}_{2}$?


Retrieve Magento order comments through API

Question: I need to retrieve Magento order comments from another web application.
The Magento API documentation seems to have two ways to do this, through REST and SOAP.
The REST documentation is sparse. It only says that the URL structure is like: http://magentohost/api/rest/orders/:orderid/comments
Also, the default REST response is in XML, but I need it in JSON.
I already have an API user set up in Magento and I've created comments from this 'other' web application using SOAP.
My question, using REST:

How do I get the response in JSON rather than XML?
How do I authenticate?
Answer: How to retrive Magento Order Comments with REST Api
Here is the sample code for REST API Authentication and Retrive Order Comments.
Magento Test File
<?php
session_start();
$mageFilename = '../app/Mage.php';

require $mageFilename;
Mage::app();

// $callbackUrl is a path to your file with OAuth authentication example for the Admin user
$callbackUrl = "http://magentohost/extrafiles/oauth-test.php";
//oAuth Initiate URL
$temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
//oAuth Authorize
$adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
//oAuth Token URL
$accessTokenRequestUrl = 'http://magentohost/oauth/token';
//API Url
$apiUrl = 'http://magentohost/api/rest';

//Consumer Key
$consumerKey = '{{PUT_YOUR_CONSUMER_KEY}}';
//Consumer Secret
$consumerSecret = '{{CONSUMER_SECRET}}';

if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1)
{
    $_SESSION['state'] = 0;
}
try
{
    $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
    $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
    $oauthClient->enableDebug();

    if (!isset($_GET['oauth_token']) && !$_SESSION['state'])
    {
        $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
        $_SESSION['secret'] = $requestToken['oauth_token_secret'];
        $_SESSION['state'] = 1;
        header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
        exit;
    }
    else if ($_SESSION['state'] == 1)
    {
        $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
        $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
        $_SESSION['state'] = 2;
        $_SESSION['token'] = $accessToken['oauth_token'];
        $_SESSION['secret'] = $accessToken['oauth_token_secret'];
        header('Location: ' . $callbackUrl);
        exit;
    }
    else
    {
        $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);

       $resourceUrl = "$apiUrl/orders/21833/comments";

       $oauthClient->fetch($resourceUrl, array(), 'GET', array('Accept' => '*/*'));
       echo $oauthClient->getLastResponse();
    }
}
catch (OAuthException $e)
{
    print_r($e->getMessage());
    echo "
";
    print_r($e->lastResponse);
}

exit;
?>

RESPONSE :
[
  {
    "created_at": "2016-12-06 15:53:28",
    "comment": "On order, Following Activity is done By: XXX Captured amount of $2,669.97 online. Transaction ID: \"XXXXXXX\".",
    "is_customer_notified": "2",
    "is_visible_on_front": "0",
    "status": "processing"
  },
  {
    "created_at": "2016-12-06 15:53:28",
    "comment": "Order is Created with following : Order is Created By: XXX Grand Total: $2669.97",
    "is_customer_notified": null,
    "is_visible_on_front": "0",
    "status": "processing"
  }
]


Supply different JVM options to different runnable in Apache Twill

Question: In a Twill application lets say I have two types of runnables. One runnable has a 3GB container size and a different runnable has a 6GB container size. Now I want to set different -Xms option for these two runnable types. How do I supply different JVM options to different runnable types?
All I can find is this setJVMOptions function but it supplies the JVM options to all the runnables.
Answer: This not possible in versions 0.11.0 and earlier.  This is fixed in trunk and will be in version 0.12.0.  See ticket TWILL-241 for details.


Powershell command did not include error in output file

Question: I have the code below, to be used in Powershell; it performed well, except that I need the output file to also include the error messages whenever the IPs did not resolve to names.
Get-Content inputfile.txt |
    foreach-object { [System.Net.Dns]::GetHostEntry($_)  } |
    out-file -filepath outputfile.txt

At the moment, I'm able to see the red error messages displayed on Powershell window. But I want these to appear in the output file along with the results  for each item listed in the input file.
Thanks in advance!
Comment: If a command produces errors and you want them as part of stdout, you can join errors with stdout by use `2>&1` for example `get-process 2>&1` this simply puts stderr (2) into the stdout (1) stream. This is remnant of command line. The more PowerShell way would involve using the $error variable to spit out the last error as you wish. $error has many properties that you can break apart as you want. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-error?view=powershell-7.2 ... You probably need a try catch block to ensure errors only go out when they happen.
Comment: The exceptions produced by `GetHostEntry` don't give you a hint as to which IP failed to be resolved
Comment: @SantiagoSquarzon Is there a way around this? :(
Answer: Since .GetHostEntry(..) doesn't give you a clear hint as to which IP failed to be resolved it's better if you create an object that associates the IP Address you're trying to resolve with the method call. This also allows you to have a better export type, instead of plain .txt file, you can export your objects as .csv with Export-Csv.
Below example uses .GetHostEntryAsync(..) which allow us to query multiple hosts in parallel!
using namespace System.Collections.Generic
using namespace System.Collections.Specialized

(Get-Content inputfile.txt).ForEach{
    begin { $tasks = [List[OrderedDictionary]]::new() }
    process {
        $tasks.Add([ordered]@{
            Input    = $_
            Hostname = [System.Net.Dns]::GetHostEntryAsync($_)
        })
    }
    end {
        do {
            $id = [System.Threading.Tasks.Task]::WaitAny($tasks.Hostname, 200)
            if($id -eq -1) { continue }
            $thisTask = $tasks[$id]
            $thisTask['Hostname'] = try {
                $thisTask.Hostname.GetAwaiter().GetResult().HostName
            }
            catch { $_.Exception.Message }
            $tasks.RemoveAt($id)
            [pscustomobject] $thisTask
        } while($tasks)
    }
} | Export-Csv outputfile.csv -NoTypeInformation

Comment: This is a really nice combination of PowerShell, .NET, and Async/Task +1
Comment: @Santiago I have marked the answer as the solution. Thanks again. I might ask at least one  more networking-related question using PowerShell in a few hours, I hope you participate again :)
Comment: Thanks @Daniel, I have a similar function in [this repo](https://github.com/santysq/PowerShell-Network-Scanners) you might find them useful :)


Analyzing Effect in a Bayesian Model (Rjags)

Question: "Consider below the number of actuarial claims data for three groups of insurance
policyholders,
year: 1 2 3 4 5
Grp1: 9 7 6 13 12
Grp2: 6 4 2 8 10
Grp3: 8 8 3 4 9

Run R and Jags to apply the following hierarchical model to analyze the data:
Yij ∼ Poisson(λij )
λij = Pijθj
θij ∼ Ga(α, β) Pij ∼ Ga(γ, δ)
α ∼ Ga(5, 5) γ ∼ U(0, 100)
β ∼ Ga(25, 1) δ ∼ U(0, 100),
where i = 1, 2, 3 and j = 1, . . . , 5.

What's your conclusion about the group effect and the year effect?"
I have my model specifications drafted to be pulled into R using JAGS.  My question is, how do I code in R to test for the effect of Group and the effect of Year separately? I've only ever used jags for one variable.
Here is my cookie-cutter JAGS code:
library(rjags)

forJags<-list(                  )

inits<-list(                     )

foo<jags.model(file="m2n4.bug",data = forJags,inits=inits)

out<-coda.samples(model=foo, variable.names = c(                ),     n.iter=50000,thin=5)

summary(out)

Here is my model:
model
{
for (i in 1:3,j in 1:5){
Y[i,j] ~ dpois(lambda[i,j])
lambda[i,j] = P[i,j]*theta[i,j]
theta[i,j] ~dgamma(alpha,beta)
P[i,j] ~ dgamma(gamma,delta)
}
alpha ~ dgamma(5,5)
beta ~ dgamma(25,1)
gamma ~ dunif(0,100)
delta ~ dunif(0,100)
}

Any input informing me of how to code such that I test for the effects separately would be huge.
Answer: Define your model as:
model
{
for (j in 1:5){P[j] ~ dgamma(gamma,delta)}
for (i in 1:3){
for(j in 1:5){
Y[i,j] ~ dpois(lambda[i,j])
lambda[i,j] = P[j]*theta[i,j]
theta[i,j] ~ dgamma(alpha,beta)
}
}
alpha ~ dgamma(5,5)
beta ~ dgamma(25,1)
gamma ~ dunif(0,100)
delta ~ dunif(0,100)
}

and then run:
library(rjags)

Y<-rbind(c(9, 7, 6, 13, 12),c( 6 ,4 ,2 ,8 ,10),c(8 ,8, 3, 4, 9))

forJags<-list('Y' = Y)

foo<-jags.model(file="m2n4.bug",data = forJags)

out<-coda.samples(model=foo, variable.names = c("theta","P"),n.iter=50000,thin=5)

summary(out)

You will then be able to see the separate effect for P (the year) and the single effect (theta)


ThreadLocalRandom with shared static Random instance performance comparing test

Question: In our project for one task we used static Random instance for random numbers generation goal. After Java 7 release new ThreadLocalRandom class appeared for generating random numbers.
From spec:

When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

and also:

When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.

So I've made my little test:
public class ThreadLocalRandomTest {

private static final int THREAD_COUNT = 100;
private static final int GENERATED_NUMBER_COUNT = 1000;
private static final int INT_RIGHT_BORDER = 5000;
private static final int EXPERIMENTS_COUNT = 5000;

public static void main(String[] args) throws InterruptedException {
    System.out.println("Number of threads: " + THREAD_COUNT);
    System.out.println("Length of generated numbers chain for each thread: " + GENERATED_NUMBER_COUNT);
    System.out.println("Right border integer: " + INT_RIGHT_BORDER);
    System.out.println("Count of experiments: " + EXPERIMENTS_COUNT);

    int repeats = 0;
    int workingTime = 0;
    long startTime = 0;
    long endTime = 0;

    for (int i = 0; i < EXPERIMENTS_COUNT; i++) {
        startTime = System.currentTimeMillis();
        repeats += calculateRepeatsForSharedRandom();
        endTime = System.currentTimeMillis();
        workingTime += endTime - startTime;
    }
    System.out.println("Average repeats for shared Random instance: " + repeats / EXPERIMENTS_COUNT
            + ". Average working time: " + workingTime / EXPERIMENTS_COUNT + " ms.");

    repeats = 0;
    workingTime = 0;
    for (int i = 0; i < EXPERIMENTS_COUNT; i++) {
        startTime = System.currentTimeMillis();
        repeats += calculateRepeatsForTheadLocalRandom();
        endTime = System.currentTimeMillis();
        workingTime += endTime - startTime;
    }
    System.out.println("Average repeats for ThreadLocalRandom: " + repeats / EXPERIMENTS_COUNT
            + ". Average working time: " + workingTime / EXPERIMENTS_COUNT + " ms.");
}

private static int calculateRepeatsForSharedRandom() throws InterruptedException {
    final Random rand = new Random();
    final Map<Integer, Integer> counts = new HashMap<>();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {

                for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                    int random = rand.nextInt(INT_RIGHT_BORDER);
                    if (!counts.containsKey(random)) {
                        counts.put(random, 0);
                    }
                    counts.put(random, counts.get(random) + 1);
                }
            }
        };
        thread.start();
        thread.join();
    }

    int repeats = 0;
    for (Integer value : counts.values()) {
        if (value > 1) {
            repeats += value;
        }
    }

    return repeats;
}

private static int calculateRepeatsForTheadLocalRandom() throws InterruptedException {
    final Map<Integer, Integer> counts = new HashMap<>();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {

                for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                    int random = ThreadLocalRandom.current().nextInt(INT_RIGHT_BORDER);
                    if (!counts.containsKey(random)) {
                        counts.put(random, 0);
                    }
                    counts.put(random, counts.get(random) + 1);
                }
            }
        };
        thread.start();
        thread.join();
    }

    int repeats = 0;
    for (Integer value : counts.values()) {
        if (value > 1) {
            repeats += value;
        }
    }

    return repeats;
}

}
I've also added test for non-shared Random and got next results:
Number of threads: 100
Length of generated numbers chain for each thread: 100
Right border integer: 5000
Count of experiments: 10000
Average repeats for non-shared Random instance: 8646. Average working time: 13 ms.
Average repeats for shared Random instance: 8646. Average working time: 13 ms.
Average repeats for ThreadLocalRandom: 8646. Average working time: 13 ms.

To me it's little strange, as I expected at least speed increasing when using ThreadLocalRandom comparing to shared Random instance, but see no difference at all.
Can someone explain why it works that way, maybe I haven't  done testing properly. Thank you!
Comment: well, first of all your threads are not parallel as you `join` to a thread right after starting one before starting another.
Comment: **much less overhead and contention** does not mean **it's faster** it just means *under certain types and levels of stress there may be improved throughput and stability*.
Comment: Let me parrot the experts: microbenchmarking is hard to get right. If you want to try, use [Caliper](https://code.google.com/p/caliper/) to do it.
Comment: If you're still interested in a micro-benchmark result, this blog shows the challenges of benchmarking such things: http://niklasschlimm.blogspot.ch/2012/01/java-7-how-to-write-really-fast-java.html and from an OS perspective: http://java-performance.info/java-util-random-java-util-concurrent-threadlocalrandom-multithreaded-environments/
Answer: Your testing code is flawed for one. The bane of benchmarkers everywhere.
thread.start();
thread.join();

why not save LOCs and write
thread.run();

the outcome is the same.
EDIT: If you don't realize the outcome from the above, it means that you're running single threaded tests, there's no multithreading going on.
Answer: You're not running anything in parallel because you're waiting for each thread to finish immediately after starting it. You need a waiting loop outside the loop that starts the threads:
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < THREAD_COUNT; i++) {
    Thread thread = new Thread() {
        @Override
        public void run() {

            for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                int random = rand.nextInt(INT_RIGHT_BORDER);
                if (!counts.containsKey(random)) {
                    counts.put(random, 0);
                }
                counts.put(random, counts.get(random) + 1);
            }
        }
    };
    threads.add(thread);
    thread.start();
}

for (Thread thread: threads) {
    thread.join();
}

Answer: Maybe it would be easier to just have a look at what actually happens. Here is the source for ThreadLocal.get() which is also called for the ThreadLocalRandom.current().
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null)
            return (T)e.value;
    }
    return setInitialValue();
}

Where ThreadLocalMap is a specialized HashMap-like implementation with optimizations.
So what basically happens is that ThreadLocal holds a map Thread->Object - or in this case Thread->Random - which is then looked up and either returned or created. As this is nothing 'magical', the timing will be equal to a HashMap-lookup + the initial creation overhead of the actual Object to be returned. Since a HashMap lookup (in this optimized case) is linear, the cost for a lookup is k, where k is the calculation cost of the hash function.
So you can make some assumptions:

ThreadLocal will be faster than creating the object each time in each Runnable, unless the creation cost is much smaller than k. So looking up Random is a good thing, putting an int inside might not be so smart.
ThreadLocal will be better than using your own HashMap, as such a generic implementation can be assumed to be equal to k or worse.
ThreadLocal will be slower than using any lookup with a cost < k. Example: store everything in an array first, then do myRandoms[threadID].
But then this assumes that you know which threads will be processing your work in the first place, so this isn't a real candidate for ThreadLocal anyways.


Leetcode matching pairs

Question: The match method takes in a string and the index of opening parentheses. The method needs to return the index of the matching parentheses. If the given index is not to open parentheses, or there are no matching parentheses, return -1. See the examples below.
Example:
ParenthesesMatcher.match("(())", 1) => 2
The given index is for the second parentheses.
The matching is the closing parentheses at index 2.

ParenthesesMatcher.match("(())", 0) => 3
The given index is for the first parentheses.
The matching is the last closing parentheses at index 3.

ParenthesesMatcher.match("asdf", 0) => -1
The given index is not an opening parentheses. Return -1.

ParenthesesMatcher.match("(()", 0) => -1
The given index does not have a matching parentheses. Return -1.

Coherent solution #1: Short, one-method, simple.
def match(string, start)
  return -1 unless str[start] == ?(
    open = 0
    str[start..-1].each_char.with_index do |c, i|
      if c == ?(
        open += 1
      elsif c == ?)
        open -= 1
        return start + i if open == 0
      end
    end

    -1
  end

end

Comment: What's the problem id?
Comment: It's not on Leetcode, had an acquaintance send it to me because they were given it today. He said I should try it because he couldn't figure it out during his interview and he couldn't find any similar problems on Leetcode. I'm at a loss here too.
Comment: Basically, -1 means something unexpected happens, and the method caller should check it not equals -1. And some language don't take -1 as a valid index. And I think a stack probably could help.
Answer: I write a small python program to demonstrate the idea using stack here. You save the indices of '(' seen in the stack, and when you see a ')' comes, you pop a '(' from the stack.
def match_parentheses(s, index):
    stack = []
    marker = -1
    for i in range(len(s)):
        if i != index:
            if s[i] == '(':
                stack.append(i)
            elif s[i] == ')':

                # in our processed ()s, there are more ')' than '(',
                # just ignore it, the stack is guaranted to be empty
                if len(stack) == 0:
                    continue
                peek = stack[-1]
                if marker >= 0 and peek == marker:
                    return i
                else:
                    stack.pop()
        else:
            if s[i] == ')':
                return stack[-1] if len(stack) > 0 else -1
            elif s[i] == '(':
                marker = i
                stack.append(i)
            else:
                return -1
    return -1
match_parentheses("(())", 1)
match_parentheses("(())", 0)
match_parentheses("abcd", 0)
match_parentheses("(()", 0)
match_parentheses("())", 2)
match_parentheses("(())()()", 7)

Ouput:
2 3 -1 -1 -1 6

Answer: OK, trying to understand. I'm seeing strings being handled as arrays, not key/value pairs.
What I'd do, and this is fairly naive, I know, is first check to make sure the index is for an open paren, then increment and decrement a number as you run through the string/array, starting at the given index, so that you reach 0 when you find the matching parent. Like, for "((((())))" and you want to find the match for index 1, you have a variable called inc that has an initial value of 0. At index 1, it increments to 1, at index 2 to 2, at 3 to 3, at 4 to 4, at 5 it decrements to 3, at 6 to 2, at 7 to 1, and at 8 to 0, so that 8 is the match for 1.
My head's too full of Java right now to come up with coherent Ruby code, I'd wind up throwing in a bunch of random semicolons.
But it feels like that isn't the whole problem. Is there more explaining it?
The word, by the way, is syntactically, not syntaxically.
Comment: This is actuallly pretty good for me to work with. I'll try this out and yolo into it I guess. (This is probably the 30th Leetcode problem I've done ever so I'm not exactly an expert at what I'm doing lol) Pretty much all the leetcode problems I've done so far included K/V arrays so that's the closest I have to this as far as familiarity goes. If it's a string, then I should probably implement a split function for it to separate them into individual and sequential values to iterate through? The rest of the explanation is just test it via rspec.
Comment: You can handle strings as arrays in Ruby, iirc.
Answer: This is tagged as a Ruby question, so I thought I'd post a Ruby answer. I really liked @lincr's stack-based method above, but I've simplified it a little. It analyses the input string to produce an array of the start and end offsets of each pair of paretheses. Then it just iterates over the list looking for a matching start point.
def paren_pairs(sample)
  pairs = []
  stack = []
  sample.chars.each_with_index do |chr, i|
    stack.push i if chr == '('
    pairs.append [stack.pop, i] if chr == ')'
  end
  pairs
end

def match_parens(sample, i)
  paren_pairs(sample).reduce(-1) { |result, pair| pair[0] == i ? pair[1] : result }
end

So:
tests = [['(())', 1, 2],
         ['(())', 0, 3],
         ['asdf', 0, -1],
         ['(()', 0, -1]]

tests.each do |test|
  sample, index, expected = test
  puts "#{sample}, #{index}, expected #{expected}, got #{match_parens sample, index}"
end

Results:
(()), 1, expected 2, got 2
(()), 0, expected 3, got 3
asdf, 0, expected -1, got -1
((), 0, expected -1, got -1

Comment: It's just an array, but it's being used as a stack in this instance. Think of those spring-loaded plate dispensers you see in cafeterias. Ruby arrays have a number of aliased methods that do the same thing, so I used ```push``` and ```pop``` because they describe the stack behaviour we want.
Comment: Perfect. This is "sort of" where I was trying to go with my method, but I've never even used stack before so I was trying to do a inc/dec process to match them.

Leetcode matching pairs


Unable to install OSSEC - Error: pcre2.h: No such file or directory

Question: I am trying to install OSSEC on my linux server OS Red Hat Enterprise Linux Server release 5.6 (Tikanga), and PCRE is a requirement. I have already downloaded the files for OSSEC v3.7.0 and PCRE2 v10.37, but when trying to install I get the error:

In file included from ./headers/shared.h:215, from client-agent/agentd.c:10:
./os_regex/os_regex.h:19:19: error: pcre2.h: No such file or directory
In file included from ./headers/shared.h:215, from client-agent/agentd.c:10:
./os_regex/os_regex.h:47: error: expected specifier-qualifier-list before 'pcre2_code'
./os_regex/os_regex.h:57: error: expected specifier-qualifier-list before 'pcre2_code'
./os_regex/os_regex.h:68: error: expected specifier-qualifier-list before 'pcre2_code'
make: *** [client-agent/agentd.o] Error 1
Error 0x5.
Building error. Unable to finish the installation.

This is what I did:

ossec-hids-3.7.0]#mv ../pcre2-10.37.tar.gz .
ossec-hids-3.7.0]#tar -zxvf pcre2-10.37.tar.gz -C src/external/
ossec-hids-3.7.0]#sudo PCRE2_SYSTEM=yes ./install.sh

Should pcre.h be as a file on my zip folder? Because I did not find it there.
Is there any way to make this work?
Comment: Advice to newcomers: If an answer solves your problem, please accept it by clicking the large check mark (✓) next to it and optionally also up-vote it (up-voting requires at least 15 reputation points). If you found other answers helpful, please up-vote them. Accepting and up-voting helps future readers. See [the relevant help-center article](https://stackoverflow.com/help/someone-answers)
Answer: You need pcre-devel:
$ dnf whatprovides */pcre2.h
[..]
pcre2-devel-10.32-2.el8.i686 : Development files for pcre2
Repo        : baseos
Matched from:
Filename    : /usr/include/pcre2.h

pcre2-devel-10.32-2.el8.x86_64 : Development files for pcre2
Repo        : baseos
Matched from:
Filename    : /usr/include/pcre2.h


How to theme output of node_view_multiple()?

Question: If I want to theme the output of node_view_multiple() I can just set the #theme element of the renderable array generated by the node_view_multiple() function.
But, what if I'm not the one that called the node_view_multiple()? Is there a tpl file for that?
A good example would be a taxonomy term page. The taxonomy-term.tpl.php allows to theme only the term itself, not the actual list of nodes. So how can I theme that list of nodes?
Note that I don't want to theme individual nodes (that's not the scope of the question). I want to theme the list of nodes.
Answer: The return from node_view_multiple is supposed to be a dumb collection of node render arrays, it's not meant to be themeable in and of itself (at least not on a generic level, obviously case-by-case you can do it). The function sepecifically doesn't get involved with the theming, as that should be up to the caller to determine. So using #theme or #theme_wrappers on the outer array is the correct thing to do.
There isn't anything you can do to target other modules' use of node_view_multiple() in this respect, short of:

Patching the module code
Patching node_view_multiple itself so it has a default theme function, which you can then hook into.
Use a broader attack like hook_page_alter() to make specific changes to specific arrays when it makes sense to.
Comment: Option 1 makes little sense as I need generic solution.
Option 2 would be the best option, but there is no change this would go into the core :(
Option 3 the same as option 1 - would work only for predetermined situations.
Anyway, thanks for the clues.


$\operatorname{Spec}(k[x])$ has infinite points.

Question:
Let $k$ be a field. I have to prove that $\operatorname{Spec}(k[x])$ has infinite points.

If $k$ is infinite it is obvious: in fact there are infinite maximal ideals $(x-\alpha_i)$, with $a_i \in k$. But if $k$ is a finite field, how can I prove my claim? Is there a general argument like the proof of the infinitude of primes of $\mathbb{Z}$?
Comment: See http://math.stackexchange.com/questions/585201/ for a generalization.
Answer: The maximal ideals in $k[x]$ are principal, generated by irreducible polynomials. Then you have to prove that there are infinitely many (non-associate) irreducible polynomials. In order to do this use the Euclid's trick for proving that there are infinitely many primes.
Comment: +1. Euclid's trick works for $k[x]$ because we know the units of $k[x]$. (It doesn't apply for a DVR for instance).
Answer: You can reduce the finite case to the infinite case.
Consider the morphism  $\mathrm{Spec}(\overline{k}[x]) \to \mathrm{Spec}(k[x])$. The fiber of $(0)$ is $\mathrm{Spec}(\overline{k}(x))$, just one point, and the fiber of $(f)$ with $f \in k[x]$ irreducible is $\mathrm{Spec}(\overline{k}[x]/(f))$, which is a finite set. It follows that if $\mathrm{Spec}(\overline{k}[x])$ is infinite, the same is true for $\mathrm{Spec}(k[x])$, and they have the same cardinality.
Actually this "geometric" proof can be made more "algebraic": There are infinitely many elements in $\overline{k}$. Since every polynomial over $k$ has only finitely many roots in $\overline{k}$, there are also infinitely many elements in $\overline{k}$ which are not conjugate to each other (pairwise). Hence, their minimal polynomials generate pairwise distinct maximal ideals in $k[x]$.
Comment: +1 In the present case it may be necessary to also prove the known fact that $\overline{k}$ is infinite even though $k$ is finite. This has been done e.g. [here](http://math.stackexchange.com/q/56397/11619).
Comment: Yes, I assumed the trivial fact that algebraically closed fields are infinite.
Comment: @MartinBrandenburg But what's is wrong if I use the same method if the field is finite? Why I have to pass to $\bar{k}[x]$?


Clonar uma lista em Java

Question: Tenho uma classe que lê um arquivo csv e coloco os dados da tabela em uma lista.
public class Gerenciador {

    public LinkedList<Acidentes> listAcidentes;

    public Gerenciador() {
        listAcidentes = new LinkedList<>();
    }

    public void readFile(String nomeArq) {
        try {
            Path path1 = Paths.get(nomeArq);

            BufferedReader reader = Files.newBufferedReader(path1, Charset.forName("utf8"));

            String line = reader.readLine();
            while ((line = reader.readLine()) != null) {
                line = line.replace(",", ".");
                String[] dados = line.split(";");

                //Variaveis para criação do objeto acidente
                String log1 = dados[1]; //Endereço 1
                String log2 = dados[2]; //Endereço 2

                int hora = Integer.parseInt(dados[30]); // Intervalo de hora cheia

                DiaNoite turno = null;                  //Verificação de dia ou noite
                if (dados[21].equalsIgnoreCase("NOITE")) {
                    turno = DiaNoite.NOITE;

                } else {
                    turno = DiaNoite.DIA;

                }

                String dia = dados[28]; //Dia do acidente
                String mes = dados[29]; //Mes do acidente
                String ano = dados[30]; //Ano do acidente

                Clima clima = null; //Verificação do clima (BOM/NULBADO/CHUVOSO)
                if (dados[23].equalsIgnoreCase("BOM")) {
                    clima = Clima.BOM;
                } else if (dados[23].equalsIgnoreCase("NUBLADO")) {
                    clima = Clima.NUBLADO;
                } else {
                    clima = Clima.CHUVOSO;
                }

                DiaSemana diaSemana = null; //Verificação do dia da semana do acidente
                switch (dados[8]) {
                    case "SEGUNDA-FEIRA":
                        diaSemana = DiaSemana.SEGUNDA;
                        break;
                    case "TERÇA-FEIRA":
                        diaSemana = DiaSemana.TERCA;
                        break;
                    case "QUARTA-FEIRA":
                        diaSemana = DiaSemana.QUARTA;
                        break;
                    case "QUINTA-FEIRA":
                        diaSemana = DiaSemana.QUINTA;
                        break;
                    case "SEXTA-FEIRA":
                        diaSemana = DiaSemana.SEXTA;
                        break;
                    case "SABADO":
                        diaSemana = DiaSemana.SABADO;
                        break;
                    case "DOMINGO":
                        diaSemana = DiaSemana.DOMINGO;
                        break;

                }

                //String tipoAcid = dados[5];
                TipoAcid tipoAcid = null;
                switch (dados[5]) {
                    case "CHOQUE":
                        tipoAcid = TipoAcid.CHOQUE;
                        break;
                    case "ABALROAMENTO":
                        tipoAcid = TipoAcid.ABALROAMENTO;
                        break;
                    case "COLISAO":
                        tipoAcid = TipoAcid.COLISAO;
                        break;
                    case "QUEDA":
                        tipoAcid = TipoAcid.QUEDA;
                        break;
                    case "ATROPELAMENTO":
                        tipoAcid = TipoAcid.ATROPELAMENTO;
                        break;
                    case "EVENTUAL":
                        tipoAcid = TipoAcid.EVENTUAL;
                        break;
                }

                double lat = Double.parseDouble(dados[35]); //Latitude
                double lon = Double.parseDouble(dados[36]); //Longitude
                GeoPosition pos = new GeoPosition(lat, lon); //Localização do acidente

                Dia d = new Dia(hora, turno, dia, mes, ano, clima, diaSemana); //Criação do dia, para criar um acidente
                Acidentes a = new Acidentes(log1, log2, d, tipoAcid, pos); //Criação do objeto acidente

                listAcidentes.add(a);

            }
        } catch (IOException x) {
            System.err.format("Erro de E/S: %s%n", x);
        }
    }

    @Override
    public String toString() {
        return super.toString();
    }

Preciso clonar a lista para uma classe de testes, para eu fazer a manipulação desses dados, porém não sei como fazer isso.
Já testei o método clone e não funcionou (Ou então usei ele errado)
Comment: O `clone()` funciona sim. Onde vc está utilizando ele?
Answer: Tente da seguinte forma
LinkedList segundaLista = new LinkedList();
segundaLista = (LinkedList) listAcidentes.clone();

Answer: Olá,
Vc quer clonar a lista pra uma classe de testes, mas se vc fizer uma instância da sua classe Gerenciador na sua classe de testes vc terá lista sem a necessidade de clona-la.
Acredito que não ficou mt claro como seria esse teste que vc quer fazer, mas de qualquer forma o clone() funciona. Na sua classe Gerenciador, vc poderia fazer o seu método readFile retornar a lista. Assim:
public LinkedList<Acidentes> readFile(String nomeArq) {

    try {

        // CÓDIGO DO SEU MÉTODO.

    } catch (IOException x) {
            System.err.format("Erro de E/S: %s%n", x);
      }
    return listAcidentes;
}

Dessa forma na chamada do método em outra classe vc pode fazer o clone da lista e usar na sua classe de testes:
//INSTÂNCIA DAS CLASSES
ClasseTeste classeTeste = new ClasseTeste();
Gerenciador gerenciador = new Gerenciador();

//LISTA ORIGINAL
LinkedList lista = gerenciador.readFile(nomeDoArquivo);

//CLONANDO A LISTA
LinkedList listaClonada = new LinkedList();
listaClonada = (LinkedList) lista.clone();

//UTILIZANDO A LISTA CLONADA NA CLASSE DE TESTES
classeTeste.testar(listaClonada);

Não sei se é realmente isso que vc busca, espero ter ajudado.

Clonar uma lista em Java


How sort stings in alphabetical and numerical order?

Question: I have a vector of strings, which I want to sort alphabetically, and then sort by the number, which is at the end of the strings.
Final output should be "AGSHIM1", "AGSHIU1", "AGSHIZ1","AGSHIH2", "AGSHIM2","AGSHIU2", "AGSHIZ2"
d<-c("AGSHIZ2", "AGSHIZ1", "AGSHIU1", "AGSHIM1", "AGSHIH2", "AGSHIM2",
"AGSHIU2")
d[order(d,as.numeric(substr(d, nchar(d), nchar(d))))]

>"AGSHIH2" "AGSHIM1" "AGSHIM2" "AGSHIZ1" "AGSHIZ2" "AGSHIU1" "AGSHIU2"

Answer: What you can do is separate the number from the string, and sort by the number first, and then within each group of numbers sort alphabetically:
sortSpecial <- function(d) {
  df <- data.frame(
    original = d,
    chars = gsub("[[:digit:]]", "", d),
    nums = gsub("[^[:digit:]]", "", d)
  )
  df <- df[with(df, order(nums, chars)),]
  return(df$original)
}

d <- sortSpecial(d)

d
# [1] "AGSHIM1" "AGSHIU1" "AGSHIZ1" "AGSHIH2" "AGSHIM2" "AGSHIU2" "AGSHIZ2"

There should be a more elegant approach, I just don't know it. Nevertheless, let me know if it helps.
Update
I could not help but get inspired by Karthik S's approach. If you don't want to generate the function first, you can do the same steps as before using dplyr:
library(dplyr)
d <- data.frame(d = d) %>%
  mutate(
    chars = gsub("[[:digit:]]", "", d),
    nums = gsub("[^[:digit:]]", "", d)
  ) %>%
  arrange(nums, chars) %>%
  pull(d)

Again, the steps are identical so the choice of approach is a matter of preference.
Answer: Another approach. But I am sure a shorter solution most likely exists.
library(dplyr)
library(stringr)
library(tibble)
d %>% as.tibble() %>%
   transmute(dig = str_extract(value,'\\d'), ltrs = str_remove(value, '\\d')) %>% type.convert(as.is = 1) %>%
     arrange(dig,ltrs) %>% transmute(d = str_c(ltrs,dig, sep = '')) %>% pull(d)
[1] "AGSHIM1" "AGSHIU1" "AGSHIZ1" "AGSHIH2" "AGSHIM2" "AGSHIU2" "AGSHIZ2"

Comment: Just a comment, I believe if you use `mutate` in place of the first `transmute` then you won't need the second `transmute` operation. You would need to `pull(value)` instead of `pull(d)`, however.
Answer: Here is one base R option using gsub + order
> d[order(as.numeric(gsub("\\D", "", d)), d)]
[1] "AGSHIM1" "AGSHIU1" "AGSHIZ1" "AGSHIH2" "AGSHIM2" "AGSHIU2" "AGSHIZ2"


Any suggestions on the best way to improve raw speed on the field?

Question: Any ideas on workouts or exercises for improving speed on the field?
I say "on the field" because targeting a specified distance (40yd, 100m, etc) can lead to an emphasis on a particular start or technique.
Some examples:

Running sprints (40yd or other)
Squatting weight or other lifts
Learning to lean when accelerating to create better shin angles
Etc
Comment: Thanks, @corsiKa. This question is related to improving top speed over short distances. Useful for almost all field sports (soccer, football, baseball, etc).
Comment: Wanted to create new tags "sprinting" and "speed," but I can't because I don't have enough reputation...
Answer: If you run 10km++ you can focus on three kinds of running:
Intervals
Do 1 minute at a high pace (70% of max?) and then 30 secs of slow running. Then, increase your high pace with 0.2kmh. Do this until you fall off the threadmill. The session should be 30 minutes so don't start off with too high pace.
Lactate threshold
Longer runs with variations in pace just over and just under your lactate threshold pace. Let's say 10 minutes on each. Your lactate threshold should be around your half marathon pace, maybe a 25km run. And then your two paces should be 0.7kmh over and under this pace.
This is very important for pushing your threshold.
Long easy runs
Just relax on these sessions but make sure they are at least 90 minutes
Comment: Why do you want to do Lactate Threshold and LSR for sprint training? Doesn't that "enhance" the wrong types of muscles?
Comment: if this is all about sprint training I wouldnt go for lactate, not at all. Josh didn't say what distance. I may have misread the question
Comment: Not to worry... He did say 40yd, 100m... I would still do the intervals, though
Comment: btw, I saw from other questions that you were competing in marathons. In that case I would definitely go for lactate threshold training
Comment: And I do :-) Using Jack Daniels work: http://www.coacheseducation.com/endur/jack-daniels-june-00.htm
Comment: I thought it was implied in the original post, but I'm talking about improving top speed over short distances... sprints.
Comment: Both posts have suggested intervals, but I'm interested in more specifics. For top speed improvements, do you suggest 10 seconds at 100% effort, 20 seconds of walking? 10-10? 10 sprint, 20 at light jog? Other?
Answer: Certain types of training sessions can improve running speed:

Interval running
Fartlek running
Hill running

Basically going for high quality / high intensity sessions will do much more to improve your speed than lots of junk miles, i.e. long, slow runs (assuming that you want to target speed over a relatively short distance, e.g. 100m - 1/2 marathon).
Examples of running interval session plans (from my running club's website at http://www.serpentine.org.uk/pages/tuesday_threshold_sessions.html):

2 sets of 10 ( 1min @ 10k pace; 1 min @ tempo pace; continuous running); 2 mins recovery
2x 5 min (50 secs); 2 x 4 mins (40 secs); 2 x 3 mins (30 secs); 2 x 2 mins (20 secs) all at LT pace
12 x 600m @ LT pace; 40 secs recovery
6 x 1 mile @ LT pace pace; 60 secs recovery
2 sets of 10 ( 1min @ 10k pace; 1 min @ tempo pace; continuous running); 2 mins recovery
2 x 5 min (50 secs); 2 x 4 mins (40 secs); 2 x 3 mins (30 secs); 2 x 2 mins (20 secs) all at LT pace; 4 mins rest; then 1 mile as fast as possible
12 x 600m @ LT pace; 30 secs recovery
6 x 1 mile @ 10k pace pace; 90 secs recovery

Note that these sessions are designed to improve speed at races between 10K and marathon distance.
Comment: You are saying that intervals and fartleks will increase top speed? What might these intervals look like?
Comment: Both posts have suggested intervals, but I'm interested in more specifics. For top speed improvements, do you suggest 10 seconds at 100% effort, 20 seconds of walking? 10-10? 10 sprint, 20 at light jog? Other?


Sharepoint com Angular. Estamos fazendo certo? Qual a melhora forma de integrar?

Question: Olá,
Aqui na empresa temos o Sharepoint 2013 com Angular.
Cheguei depois do projeto iniciar.
Bom,
Aqui eles usam as Web Parts para cuspir tags angular nas páginas.
E a partir daí temos toda a execução no Angular e não no Sharepoint Web Parts sabe.
Como não passei por isto antes, seria por aí mesmo a união do Sharepoint ao Angular?
Obrigado.
Answer: A melhor maneira de implementar uma aplicação é utilizando as metodologias e práticas que a equipe já possui e está confortável com.
Isso dito, o Sharepoint 2013 possui uma interface REST. Seria interessante neste caso utilizar esta interface para implementar soluções com uma melhor divisão de camadas - onde o Angular é responsável pelo aspecto SPA e o Sharepoint pelo backend.
Answer: Este meio de desenvolvimento é bastante promissor por conta da separação das camadas back-end e front-end.
A própria Microsoft incentiva este tipo de desenvolvimento e como o Sharepoint tem uma API REST. Além da API REST o Sharepoint conta com o CSOM.
No sharepoint on-line este é o melhor caminho de desenvolvimento já que você perder o poder de customizar o back-end, diferente do on-premisse.


Preventing frequently updated nodes from keeping them on the top of View

Question: I have a view that lists content profile node and set the sort criteria to node:Updated date.
However, the problem is that some of the users updates their content profile node everyday to keep it on the top of the list.
I need to user sort criteria to node:Updated date but is there any way to prevent their nodes from being on the top of view?
Lest's say for example, within one week after their last update even if they update it again it stays where it is now and doesn't get to the top or somthing.
Answer: Not possible using views out of the box! Because updated date is stored as a single value in the database. If a user updates again the new value overrides old value.
So, there is no way views can track within one week after their last update even if they update it again .
You need to use hook_nodeapi either to track all updates in separate table and query that table to list users.


how to repeat a loop a certain number of times to get the Nth derivative?

Question: I am trying to get the Nth derivative for coefficients and powers of a polynomial equation given in a dictionary. In the dictionary, the key is the power and the value is the coefficient of the given polynomial.
Here is my code, that works for a first order derivative:
'''
def differentiate(polynomial, order):

        derivative = {}

        for power, coeff in poly.items():

            new_coeff = poly[power] * power

            new_power = power - 1

            derivative[new_power] = new_coeff

            if derivative[new_power] == 0:

                del derivative[new_power]

        return derivative

if __name__ == "__main__":
        poly = {-5: 4.0, 2: 3.5, 1: 10.0}
        print(differentiate(poly, 2))  # {-7: 120.0, 0: 7.0}

'''
How would I repeat the loop to get a derivative of Nth order?
I tried to use the range function but I can't seem to make it work.
Any leads?
Answer: This is how I managed this
def differentiate(polynomial, order):
    derivative = {}
    counter = 1
    _dict = polynomial

    while counter <= order:
        for power, coeff in _dict.items():
            new_coeff = _dict[power] * power
            new_power = power - 1
            derivative[new_power] = new_coeff
            if derivative[new_power] == 0:
                del derivative[new_power]
        counter += 1
        _dict = derivative
        derivative = {}
    return _dict

Comment: oh I think it works ! thanks a lot !!


Android Driver Event Listener like WebDriverEventListener

Question: I'm working with Selenium Webdriver, Listener and MyEventListener who implements WebDriverEventListener. This MyEventListener is register on EventFiringWebDriver like this:
EventFiringWebDriver myTestDriver = new EventFiringWebDriver(
        web_driver);
myListener = new MyEventListener(this.getClass().getName());
myTestDriver.register(myListener);
driver = myTestDriver;

Now I must work with an AndroidDriver for mobile and I want the same structure. I have found the AppiumWebDriverEventListener. MyEventListener implements AppiumWebDriverEventListener, but now I can't make the same structure because the EventFiringWebDriver is not compatible with AndroidDriver. I try this:
myDriver = (AndroidDriver) new      BQAquarisDriver().returnDriver(driverPlace, new BQAquarisDriver());
EventFiringWebDriver myTestDriver = new
EventFiringWebDriver(myDriver);
myListener = new MyEventListener(this.getClass().getName());
myTestDriver.register(myListener);
myDriver = myTestDriver;

But does not work.
Answer: Appium has this interface "AppiumWebDriverEventListener" which is the same as "WebDriverEventListener".
And you can find in this GitHub repository everything about Appium Listeners, what interfaces to implement and how to use.
Comment: I know it spent a while but...this options was deprecated for Appium. Do you know any alternative?
Comment: Hi @j.barrio,
Just wrote an article for you :)
https://nael-marwan.medium.com/selenium-webdriverlistener-4f6889804256
Answer: We can implement using EventFiringWebDriverFactory: https://appiumlistener.blogspot.com/
AndroidDriver driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
driver = EventFiringWebDriverFactory.getEventFiringWebDriver(driver, new ActivityCapture());


Solve the logarithmic equation by $x$

Question: Solve the eqation for all real $x$:
$\log_2(x^2+7)+\log_3(x+6)=6$.
What I tried:
$\log_2(x^2+7)=a$ and $\log_3(x+6)=b$, then $a+b=6$ and $2^a=3^{2b}-4\cdot3^{b+1}+43$.
But the problem is $a$ and $b$ don't have to be integers...
It is easy to show that for $x>3$ and $3>x\ge 0$ there are no soultions. Which leaves us only with the interval $0>x>-6$.
Answer: Take derivative and consider where left part increases and decreases, where are extrema (at least approximately). After proving that it has a single root, we can guess that it is $x=3$.
Answer: Hint: $x$ is a natural number. Also $log_2(x^2+7)$ and $log_3(x+6)$ are natural numbers. You will end up with $4+2=6$
Comment: Why are $x$ and the logarithms natural numbers?
Comment: Well, if thats it what would be easy.
But why does x has to be a natural number and the other two too?
Comment: $x$ is really a natural number. $3^2+7=16=2^4,3+6=9=3^2$.
Comment: @kryomaxim There exists a solution that is a natural number, but you haven't proved that there couldn't be non-natural solutions.
Comment: http://www.mathe-fa.de/de#result; "English"; plot the function for the right Hand side (a constant function) and another for the left Hand side and you will see that there is only 1 solution (I have checked that on mathe-fa.de).

Solve the logarithmic equation by $x$


I want to check the content of textarea must contains previous inputs' words using javascript

Question: Is it possible to check the content of textarea must contain previous inputs' all words using javascript or jquery? and if not contains all words than the value of textarea is invalid or will not submit.
Please reply me soon.
Thanks.
Comment: i tried this http://stackoverflow.com/questions/3495735/compare-array-of-words-to-a-textarea-input-with-javascript but it not works i want the same which is mentioned here.
Comment: can you add some of your code to the question?
Comment:
Comment: user must type those 35 input words in textarea which are previously given as an values of those 35 inputs
Comment: Alright, check out the edited answer. It checks against an array.
Answer: In JavaScript you can access the value of the textareas inner text by accessing the value.
Ex: document.getElementById("myTextarea").value = "Fifth Avenue, New York City";
You can then check this as you would any other JavaScript and on submit run the tests
Comment: okay i got this but i am basic at javascript so if possible can you provide me the code. as user must utilize previous 35 inputs for textarea statement else it can not submit textarea value.
Answer: This will check the value of the text entered on each keyup event against the value you define. If that returns true the submit property will not be disabled, otherwise it will be.
$('input[type="submit"]').prop('disabled', true);
    $("textarea").on("keyup", function(){
    if($(this).val() == 'value to check against'){
       $('input[type="submit"]').prop('disabled' , false);
       }
    else{
       $('input[type="submit"]').prop('disabled' , true);
       }
    })

https://jsfiddle.net/bgdogf2c/
If checking for an item in an array:
$('input[type="submit"]').prop('disabled', true);
    $("textarea").on("keyup", function(){
    if($.inArray($(this).val(), [ "one", "two", "three"] ) != -1){
       $('input[type="submit"]').prop('disabled' , false);
    }else{
       $('input[type="submit"]').prop('disabled' , true);
       }
    })

https://jsfiddle.net/yz2q6zga/1/
Comment: pretty much similar but not what i want. i want user must utilize all previous inputs in textarea . and it can add any other text also but the previous inputs value are necessary for submission of textarea statement.
Answer: I think I understand what it is you're trying to get done: You want the user to utilize the previously given input of 35 words which is retrieved from input fields, but also give the user the option to add more. This addition is optional.
Check it out here
To be clear
input: 1, 2, 3 | textarea: 1, 2, 3 | returns true
input: 1, 2, 3 | textarea: 1, 2, 3, 4 | returns true
input: 1, 2, 3 | textarea: 1, 3, 2 | returns true
input: 1, 2, 3 | textarea: 3, 2, 1 | returns true
input: 1, 2, 3 | textarea: 2, 2, 1 | returns false
input: 1, 2, 3 | textarea: 1, 2    | returns false
JS
$("#submit").prop("disabled", true);

$(".input").on("keyup", function () {
    var input1 = document.getElementById("input1").value;
    var input2 = document.getElementById("input2").value;
    var input3 = document.getElementById("input3").value;
    var finalinput1 = input1 + " " + input2 + " " + input3;
    var finalinput2 = input1 + " " + input3 + " " + input2;
    var finalinput3 = input2 + " " + input1 + " " + input3;
    var finalinput4 = input2 + " " + input3 + " " + input1;
    var finalinput5 = input3 + " " + input1 + " " + input2;
    var finalinput6 = input3 + " " + input2 + " " + input1;
});

$("#area").on("keyup", function () {
    var content2 = $("#area").val();
    var input1 = document.getElementById("input1").value;
    var input2 = document.getElementById("input2").value;
    var input3 = document.getElementById("input3").value;
    var finalinput1 = input1 + " " + input2 + " " + input3;
    var finalinput2 = input1 + " " + input3 + " " + input2;
    var finalinput3 = input2 + " " + input1 + " " + input3;
    var finalinput4 = input2 + " " + input3 + " " + input1;
    var finalinput5 = input3 + " " + input1 + " " + input2;
    var finalinput6 = input3 + " " + input2 + " " + input1;
    if (content2.indexOf(finalinput1) >= 0 || content2.indexOf(finalinput2) >= 0 || content2.indexOf(finalinput3) >= 0 || content2.indexOf(finalinput4) >= 0 || content2.indexOf(finalinput5) >= 0 || content2.indexOf(finalinput6) >= 0) {
        $("#submit").prop("disabled", false);
    } else {
        $("#submit").prop("disabled", true);
    }
});

$("#submit").click(function () {
    var content2 = $("#area").val();
    var input1 = document.getElementById("input1").value;
    var input2 = document.getElementById("input2").value;
    var input3 = document.getElementById("input3").value;
    var finalinput1 = input1 + " " + input2 + " " + input3;
    var finalinput2 = input1 + " " + input3 + " " + input2;
    var finalinput3 = input2 + " " + input1 + " " + input3;
    var finalinput4 = input2 + " " + input3 + " " + input1;
    var finalinput5 = input3 + " " + input1 + " " + input2;
    var finalinput6 = input3 + " " + input2 + " " + input1;
    if (content2.indexOf(finalinput1) >= 0 || content2.indexOf(finalinput2) >= 0 || content2.indexOf(finalinput3) >= 0 || content2.indexOf(finalinput4) >= 0 || content2.indexOf(finalinput5) >= 0 || content2.indexOf(finalinput6) >= 0) {
        $("#output").text("Succes!");
    } else {
        $("#output").text("Values are not the same!");
    }
});

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/80824/discussion-on-answer-by-theonlyerror-i-want-to-check-the-content-of-textarea-mus).


Python : Object attributes overwritten when creating a new object

Question: Here is a code I'm working on:
class Node:
    count = 0

    def __init__(self):
        Node.id = Node.count
        Node.count += 1

    @classmethod
    def get_count(cls):
        return Node.count

class Element:

    count = 0

    def __init__(self, type = "MTH20", group = 0):
        self.type = type
        self.group = group
        Element.count += 1

    def define_element(self):
        self.nodes = [-1]*3

        for l in range(len(self.nodes)):
            if self.nodes[l] == -1:
                self.nodes[l] = Node()
                print(self.nodes[l].id)

        for l in range(len(self.nodes)):

            print(self.nodes[l].id)

ga = Element()

ga.define_element()

I would expect the output of this code to be:
0
1
2
0
1
2

However I get this:
0
1
2
2
2
2

My conclusion is that somehow the id attribute of a node object is overwritten when constructing a new node. However, I don't understand why it would do so, or how to avoid that.
Can anyone point out what I did wrong?
Comment: Possible duplicate of [Python: Difference between class and instance attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes)
Comment: Replace Node.id = Node.count with self.id = Node.count
Comment: When you set `Node.id = Node.count`, you're setting a _class attribute_. You want the id to be an _instance_ attribute, so use `self.id = Node.count`.
Answer: With Node.id you are accessing a class attribute. You want to store ids as instance attributes by doing self.id.
class Node:
    count = 0

    def __init__(self):
        self.id = Node.count # We want id to be an attribute of that specific node
        Node.count += 1

About your code
I want to point out that your Element.define_element method could be written in a more concise natural way.
class Element:

...

def define_element(self):
        self.nodes = [Node() for _ in range(3))]

        for node in self.nodes:
                print(node)


How can I add player parameters to a core oembed field for a youtube video?

Question: For example, if I enter this url that contains the player parameters to remove controls and autoplay, oembed field on my media type does not allow it ("The given URL does not match any known oEmbed providers.".
<code>https://youtu.be/9ot0rIlhbNE?autoplay=1&fs=0&controls=0&modestbranding=1
</code>

If I paste just the base url, then it works.
Any thoughts?
Edit: Based on Yuseferi answer, I have isolated the Youtube section if the providers.json.
<code>{
    "provider_name": "YouTube",
    "provider_url": "https:\/\/www.youtube.com\/",
    "endpoints": [
        {
            "schemes": [
                "https:\/\/*.youtube.com\/watch*",
                "https:\/\/*.youtube.com\/v\/*",
                "https:\/\/youtu.be\/*"
            ],
            "url": "https:\/\/www.youtube.com\/oembed",
            "discovery": true
        }
    ]
}
</code>
Comment: looks like validator fails, maybe try just youtube.com/token?autoplay=0 test with this module toohttps://www.drupal.org/project/soembed
Comment: Thanks for sharing that module. Unfortunately that module uses core oembed and therefore core oembed does the validation. That module is only usful for converting youtube urls via the text formats
Comment: is that just one field on you have a couple of this fields?
can you share your form_id and field machine name with me?
Comment: form id =media-type-edit-form     field machine name=field_media_oembed_video
Answer: I had the same problem before with a local provider. So I share the solution I used and hope it works for you too.
The Drupal core, fetch providers form https://oembed.com/providers.json automatically. So you need to change the provider to what you want.
Oembed Providers module helps to add custom providers too.

Add custom oEmbed providers via an admin user interface (providers are
stored in configuration)
Global enable/disable of providers
Modify the provider list URL (which is > defaulted to
https://oembed.com/providers.json)
Disable the fetching of the
provider list (useful in an instance where only custom providers are
used)
Provides hook_oembed_providers_alter() to alter provider
definitions

So, all you need is to add a new provider for your custom provider "youtu.be" with your parameters too.
try it and let me know if you need more details.;)
Screenshots that shows it's working without any validation error:

what I did, was just add "oembed_providers" module and enabled it
Comment: I added the info found in providers.json (in my original question above. Based on the schema, it should allow player parameters, no? or should I add the parameters to the schema Appended  like this? *?autoplay=*&fs=*&controls=*&modestbranding=*
Comment: @NigelWaters I think what you done based on my answer is correct. it that working for you now?
Comment: That is the default ones already in providers.json. It doesn;t make sense why it's not validation, as an * is appended. Theoretically it should be fine, but there seems to be a secondary validation somewhere
Comment: @NigelWaters "*" is the case here.
if you want to exactly what you want it's better to add a custom validator to your form.
Comment: @NigelWaters do you still need more help or we're done?
Comment: My apoligies, I was on vacation. The challenge is not adding validators,; it's removing core from validating it. That module, is based on oembed core for the 2.x version. This means core, is doing the heavy lifting/validation and that module, just exposes a UI to core and ability to add new ones.
Comment: @NigelWaters as you can see in the question screenshot, it return an error on the custom URL that you provided as data. These custom providers help you.
but if you want to have a validator that validates the pattern you exactly want maybe it could be another question that I can help you too.
Comment: I don't need a validator. I need to bypass core's oembed validator
Comment: @NigelWaters then it must work for you. I tried it and on my project, it's worked with your given URL. sorry, but I confused what is the problem now?
Comment: do you think you share a screenshot of your attempt?
Comment: I awarded the bounty as it was about to expire. Thank you for your great work so far, however I am still not there yet. When I add the URLs as mentioned above in the "Endpoint schemes", it says https://youtu.be/* is not valid. If you managed to get this working, would you mind sharing a screenshot of your custom oEmbed provider settings where it works? It would greatly be appreciated.
Comment: @NigelWaters sorry I was away from the system. I revert the changes after I saw it's working. I'll plan to it one more time for you and I'll screenshot of the result.
do you mind if I'll do it tonight?
Comment: No problem at all. I just really appreciate the help. This one has me stumped.
Comment: @NigelWaters question updated with two screenshots
Comment: thanks for doing that. I was hoping you could post a screenshot of your custom provider settings? I can't get it to accept mine
Comment: thanks for screenshots but I was hoping for a shot of your custom parameter settings as mine don't seem to be working as formatted. This is the last piece of my project and I appreciate the help so far.
Comment: Does doing it this way actually respect the parameters? My validation is all working but when I use a URL like this it doesn't actually respect these "?autoplay=1&mute=1&controls=0&showinfo=0&rel=0&loop=1&modestbranding=1&wmode=transparent"
Comment: Hi, I also have the contrib module working but the parameters are not respected. I need to disable the shortcuts on the video player by add disablekb=1 to youtube video's and keyboard=false to vimeo video's I tried adding these in the url:
https://vimeo.com/672844590?keyboard=false but this doesn't work. Did anyone solve this issue?


Does K-means incorporate the K-nearest neighbour algorithm?

Question: I was watching this tutorial on K-means clustering and from what I understand K-means is:

Randomly generate the centroids for k clusters
Create a classification model dividing into k regions (Do we use kNN here?).
Generate new centroids for each region
Repeat 2-3.

In the video I was watching regarding K-means, it appears that the lecturer may have used kNN to create the dividing regions though I can't see anything online regarding if kNN is used in K-means.
Answer: No, definitely not; kmeans and kNN are two completely different things, and kmeans doesn't use kNN at all.  In step 2 of the kmeans algorithm as you have defined it (and BTW, except for this minor confusion, your summary is otherwise basically accurate), the kmeans function loops through each of the $n$ data points, and tests the distance (usually Euclidian, but it doesn't have to be, it could be Manhattan distance, or Chebyshev, or Minkowski or whatever you like, really) of each point from each of the $m$ centroids.  The closest centroid "wins", and each point is grouped with its winning centroid, as computed on the previous iteration, in order to compute the new values of all the centroids for the next iteration.
The kNN algorithm answers a somewhat different question.  Suppose I give you a so-called "training data set" which consists of a table with multiple columns.  In the first column is a so-called "class value", basically a label which you might think of as identifying different types of real-world objects that you would like a computer to be able to automatically recognize.  All of the other columns in the table specify the values of various "features" associated with each object; for example, it's length, mass, aspect ratio, brightness, color, or whatever other quantity you may choose to measure.  Now, suppose that I give you a second data set, a so-called "test" data set, where all of the values in the data columns have been measured in just the same way as in the training data set, BUT the labels have all gone missing!  I would like you to infer the labels which are missing from the test data set by comparing the features of the test data set to those of known examples in the training set, and looking for patterns of similarities between them.
This second type of problem which I have just described is known as "classification", or sometimes, "supervised machine learning", and there are many different strategies for dealing with it.  The kNN algorithm is one of the simplest of those strategies.  Basically, the kNN algorithm considers each unknown object in the test data set, and it finds the $k$ "nearest" (by whatever distance metric the user specifies) examples in the training set.  Then, whichever label was most common among those top $k$ examples within the training set, that is the label which is assigned to the unknown object in the test set.
Bottom line, kNN is a completely different thing, and has nothing to do with subdividing a previously undifferentiated data set into empirically defined clusters.
Answer: You're sort of right. Both kNN and k-means commonly use Euclidean distance for their respective distance metrics, which is why they seem similar. Keep in mind, however, that k-means is not a classification model, as that is a supervised learning algorithm (since the grouping variable is known). K-means and other clustering methods are used when the grouping variable is unknown.


Number of decimal with select_avg() in CodeIgniter

Question: Is there any way to show only one decimal using select_avg() in CodeIgniter?
 $this->db
      ->select_avg('Stars')
      ->from('Reviews')
      $query=$this->db->get();
      return $query->result();

Comment: Show your code please
Comment: Check answer below
Comment: Could [number_format()](http://php.net/manual/en/function.number-format.php) help in controller or view?
Answer: Try like this
$this->db->select_avg(ROUND('Nr_stele'))->from('Recenzii as r');
$query = $this->db->get();
return $query->result_array();

Check SQL ROUND() Function and $this->db->select_avg() in codeigniter
Comment: I don't want ROUND, I just want it to be 4.5 not  4.5000


Set different color for each bubble in Bubble-Map

Question: In Higchart's Bubble-Map chart, Is it possible to set different color for each bubble ? If yes then please update this jsfiddle link.
series : [{
            name: 'Countries',
            mapData: mapData,
            color: '#E0E0E0',
            enableMouseTracking: false
        }, {
            type: 'mapbubble',
            mapData: mapData,
            //color : 'red' // This color applies for all the bubbles but i want different color for each bubble
            name: 'Population 2013',
            joinBy: ['iso-a2', 'code'],
            data: data,
            minSize: 4,
            maxSize: '12%',
            tooltip: {
                pointFormat: '{point.code}: {point.z} thousands'
            }
        }]

Answer: You can put the color in the data string, eg
var data = [{
       code: "AF",
       z: 30552,
       color: '#642288'
    }, /*.... etc */
]

Since the data in the example is being loaded from elsewhere, I copied it into the fiddle and added the colors.
Updated JS Fiddl
Comment: This was exactly what I wanted. Thanks !


Log-likelihood for multinominal normal distribution

Question: Given $n$ jointly-normal random variables $X_1, X_2, \dots, X_n$, with
$$\mu_i=\mu\forall i \in\mathbb{N}^+$$
$$\sigma_i=\sigma\forall i$$
$$\rho_{i,j}=\rho\forall i,j \mbox{ with } i\neq j$$
what is their log-likelihood function?
My idea is the following:
Be $\mathbf{x}=(X_1,X_2, \dots,X_n)^T$ the vector of observed values and $\mu=(\mu, \dots,\mu)^T$ a $n\times1$-Vektor. Then the $n\times n$ covariance matrix is given by $\Sigma$ with all diagonal elements being $\sigma^2$ and all other entries $\rho\sigma^2$.
The log-likelihood is given by:
$$ L(\mu, \sigma, \rho) =\log [ exp(\frac{-1}{2}(\mathbf{x}-\mu)^T)\Sigma^{-1}(\mathbf{x}-\mu))]$$
Is this correct?
Comment: What do you mean by $\rho_i$? If you mean by that a correlation parameter, then it should have a double index (the correlation is really a measure of dependence between two variables).
Comment: @nullUser Please see my edit.
Comment: @Learner My mistake, I edited the question. It should have a double index.
Answer: Assuming $\boldsymbol{x}= \left(\begin{array}{c}
  x_1\\
  \vdots\\
  x_n
\end{array}\right)$ (here, this means one observation of the $n$-dimensional
multivariate normally distributed vector), then the log-likelihood is
proportional to
$$ - \frac{1}{2} \log ( \left| \boldsymbol{\Sigma} \right|) -
   \frac{1}{2} \left(
   \boldsymbol{x}-\boldsymbol{\mu} \right)^T
   \boldsymbol{\Sigma}^{- 1} \left(
   \boldsymbol{x}-\boldsymbol{\mu} \right) $$
$\left| \boldsymbol{\Sigma} \right|$ is the determinant of
$\boldsymbol{\Sigma}$ and including it is essential.
Please note that in the typical setup, you would have say $N$ vectors
$\boldsymbol{x}_1, \ldots, \boldsymbol{x}_N$.


Nested AJAX calls to a site

Question: I've been making this cordova app against this casting agency website, and I've come across this nasty situation where I need to list each user's created nodes. For this purpose, I have created a view with the contextual filter uid and it's taking the uid from the logged user. I also have this fiddle where I am trying to list each user's nodes. However, it's returning empty (2nd ajax call). The weird thing is, it lists the nodes by the logged in user on this URL username is tolga and password is 111222.
The steps I have taken to debug:

Hardcode the username and password.
Hardcode the uid in the 2nd ajax call without deleting the 1st one.
Delete the 1st ajax call.
After deleting the 1st call, hardcode the uid in the 2nd call.
After deleting the 1st call, not pass the uid at all because I have configured the contextual filter to take the uid from the logged in user.

Nothing worked. Am I missing something? Do I need to use something like Services Views?
UPDATE: I tried using Services Views, and I ended up a whole lot of 404: Resource not found messages. Docs for the module and views say different things for path; docs say http://www.example.com/<endpoint-path>/views/<view-name> while the view says to put the path name after the endpoint path (in my case, services)
Comment: @DMAC my bad, the URL was not showing `nodes` as empty, I had changed the view and it was because of that.
Comment: Just to clarify.. Is the issue the ajax contextual filter value is not working with the view? In the fiddle it is showing your list of nodes [like your example data](http://www.rejicast.com/user?destination=oyuncularim.json) via console (which is a success in your 2nd ajax call)
Comment: @DMAC are you seeing `nodes` as empty? Because it's not empty. I see it empty as well.
Comment: You don't need to use views in between end point. Your path would be like http:// www.example.com/ /  and need to enable  services for this views service.
Answer: I found out the hard way that what was not working on jsfiddle.net was actually working on mobile. I wasted my own evening on this issue :S Thanks for all the comments though guys.

Nested AJAX calls to a site


How to prevent VSC from adding "require"?

Question: While editing some JS files, VSC systematically adds "require()" calls, which I have to remove as quickly
How to prevent VSC from adding theses lines with "require"?
Thanks
Didier
Answer: You can create a jsconfig.json file inside your project and set "javascript.suggest.autoImports" to false as documented here to disable auto-import IntelliSense in your code-base.
You can alternatively disable it globally by going to VSC settings (Ctrl + ,), search for "javascript auto import" and disable there.


uppersemilattice end extensions

Question: I'm trying to modify an argument in Jockush and Slaman's paper On the $\Sigma_2$ theory of the upper semilattice of the Turing degrees. One of the major hurdles is that I don't actually see why a claim they make is true. In particular, they claim an equivalence relation is a congruence relation, but I don't see why.
Let $\mathcal{M},\mathcal{N}$ be finite uppersemilattices, so that $\mathcal{N}$ is an end-extension of $\mathcal{M}$. The goal is to show that $\mathcal{N}$ is a subUSL of a simple end extension (simple means generated by a single new element) of a free extension of $\mathcal{M}$.
Firstly enumerate $\mathcal{N}\setminus\mathcal{M}= \{b_1,\ldots,b_n\}$, let $x_1,\ldots,x_n$ be new elements, and let $g$ take $b_i$ to $x_i$. Let $\mathcal{M}_1$ denote the free extension of $\mathcal{M}$ by $\{x_1,\ldots,x_n\}$ (I'll give a formal definition at the end). Define a map $h:\mathcal{M}_1\rightarrow \mathcal{N}$ by
$$
h(a \vee \bigvee X) = a \vee_{\mathcal{N}}\bigvee_{\mathcal{N}}\{b_i:g(b_i)=x_i\in X\}.
$$
One can check this is a USL homomorphism.
Now, let $c$ be new and let $\mathcal{M}_2$ be the free extension of $\mathcal{M}_1$ by $c$. We define $\sim$ on $\mathcal{M_2}$ by $e_1 \sim e_2$ iff $e_1 = e_2$ or $$
(\exists d_1,d_2\in\mathcal{M}_1)[e_1 = d_1 \vee_{\mathcal{M}_2} c, e_2 = d_2 \vee_{\mathcal{M}_2}c\text{ and }h(d_1)=h(d_2)].
$$
One can check this is an equivalence relation. The authors claim this is a congruence relation (they want to define $\mathcal{N}_2$ be the quotient of $\mathcal{M}_2$ by $\sim$ and then $\mathcal{N}_2$ will be the simple extension they are after).
Suppose $e_1\sim e_1'$ and $e_2\sim e_2'$, we want to show $e_1\leq e_2$ iff $e_1'\leq e_2'$. We can write each element, uniquely, as the join of some $d\in \mathcal{M}$ and a subset of $\{c\}$, we do this as $e_1 = d_1 \vee Y_1$ with the obvious changes to subscripts and primes.
Its easy to see that if $e\in\mathcal{M}_2$ is in $\mathcal{M}_1$ (or more precisely, it is of the form $d \vee \emptyset$) then its $\sim$ equivalence class is just itself. So if $e_2\in\mathcal{M_1}$, then, as free extensions are also end extensions, $e_1\in\mathcal{M_1}$ and so $e_2=e_2',e_1=e_1'$. But, as soon as $e_2\neq e_2'$ I get stuck. Working through the definition of $\sim$ one derives that $h(d_2)=h(d_2')$ and as $e_1\leq e_2$ we know $d_1\leq d_2$, so that $h(d_1)\leq h(d_2)=h(d_2')$ as $h$ is a homomorphism. But, of course, I can't pull back $h(d_1)\leq h(d_2')$ to $d_1\leq d_2'$, because homomorphisms don't work backwards with relations.
Anyone see what I'm missing?

Given a USL $\mathcal{M}$ and a set $X$ the free extension of $\mathcal{M}$ by $X$ can be realised as the structure with elements of the form $a \vee Y$ where $Y$ is a finite subset of $X$. You say $a\vee Y\leq a'\vee Y'$ iff $a\leq_\mathcal{M} a'$ and $Y\subseteq Y'$, and define $(a\vee Y) \vee (a'\vee Y')$ to be $(a\vee_{\mathcal{M}} a')\vee (Y\cup Y')$. One can naturally identify $\mathcal{M}$ with $\mathcal{M}\times\{\emptyset\}$ in the new structure.
Answer: So, with further reflection, I have come to the conclusion that $\sim$ is not a congruence with respect to the $\leq$ structure. I even have a counter-example.
$\newcommand{\M}{\mathcal{M}}\newcommand{\N}{\mathcal{N}}$
Let $\M = \{0\}$ and let $\N$ be the diamond $\{0,a,b,a\lor b\}$, clearly an end-extension of $\M$. $\M_1$ will be the free extension of $\M$ generated by $x_1,x_2$ and $x_3$ corresponding to $a,b$ and $a\lor b$ respectively.
Now let $c$ be new, and consider elements $e_1 = (0 \lor \bigvee \{x_1\})\lor c, e_2 = (0\lor\bigvee\{x_1,x_2\})\lor c$, and $e_2' = (0\lor \bigvee\{x_3\})$. Note that $e_1\leq e_2$ yet $e_1\nleq e_2'$. However, $e_2 \sim e_2'$, as their corresponding $d$s are $0\lor \bigvee\{x_1,x_2\}$ and $0\lor \bigvee\{x_3\}$, which map, via $h$ to $0 \lor_\N \bigvee_\N \{a,b\} = a\bigvee_\N b$ and $0 \lor_\N \bigvee_\N \{a\lor b\}= a\lor b$. Consequently, $\sim$ is not congruent for $\leq$.
However, $\sim$ is congruent for $\lor_{\M_2}$, and so this descends, and you can use this to define a binary relation $\leq$ on the quotient given by $[a] \leq [b]$ iff $[a]\lor [b] ( = [a\lor b]) = [b]$, one can show this is a partial order and $\lor$ is the join operator. Hopefully we can still embed $\N$ in the quotient.

uppersemilattice end extensions


exclude 0 in MAPE calculation in matlab

Question: I have two time series. one is predicted and one is original. To calculate prediction accuracy, i want to calculate MAPE(mean absolute percentage error).
The mean absolute percentage error (MAPE), also known as mean absolute percentage deviation (MAPD), is a measure of prediction accuracy of a forecasting method in statistics, for example in trend estimation. It usually expresses accuracy as a percentage, and is defined by the formula:

I am doing this in MATLAB as follows:
function m = mape(testY, pred)
% Compute mean absolute percent error
%
% m = mape(actual, pred)
%
% actual is a column vector of actual values
% pred is a matrix of predictions (one per column)
%
% m is the mean absolute percent error (ignoring NaNs) for each column of
% pred.

err = abs(bsxfun(@minus, pred, testY));
pcterr = bsxfun(@rdivide, err, testY);
m = nanmean(pcterr,1);
end

But when there is a 0 in Actual series, function returns -INF in result.
I want to exclude that 0 and corresponding value in other sequence and calculate MAPE value.
Answer: You can use logical indexing in the nanmean to exclude the zero values in testY
m = nanmean(pcterr(testY~=0),1);

exclude 0 in MAPE calculation in matlab


NGINX+wordpress: CSS being served but not applied

Question: Cheers fellow stackers,
I kinda have to get wordpress running in a self hosted nginx environment.
More or less exactly using the suggested config from NGINX wordpress doc.
server {
    listen 443 ssl;
    server_name _;
    ssl_certificate /var/lib/nginx/PKI/www/server/cert.pem;
    ssl_certificate_key /var/lib/nginx/PKI/www/server/key.pem;
    root /var/lib/nginx/www/wordpress;
    index index.php;
    location / {
            try_files $uri uri/ /index.php?$args;

    }
    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_intercept_errors on;
        fastcgi_pass php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
    }
}

Everything works mostly as expected, except for the styling. No styling seems to be applied on the site (also applies to the admin login/quickstart wizard).
Inside of the admin dashboard, everything looks fine.
CSS files are being served properly by NGINX.
Comment: If you post a link to your site we can have a look directly, which would be easier
Answer: My nginx config did not include the mime.types defaults.
That seems to be affecting the nginx "Content-Type" response header, leading to it being "text/plain" instead of "text/css" ...
... which is unfortunate because none of the wordpress templates specify the content type in the request, e.g:
<link rel='stylesheet' id='wp-block-library-css'  href='https://censored.net/wp-includes/css/dist/block-library/style.css?ver=5.8' media='all' />

Should probably look anything like this, but oh well
<link rel="styleseeht" type="text/css" ...>

Comment: Please Improve your Answer, tell us what you have changed because it would help to answer this question, even IMHO this would only fit on Superuser
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.


Observables return data over time?

Question: Im going through the angular.io docs and some other material trying to get up to speed with angular.  One thing that has not quite sunk into my head yet is observables.  Im reading this
Observable help us to manage async data. You can think of Observables as an array of items, which arrive asynchronously over time.
from here   https://www.tektutorialshub.com/angular-http-tutorial-with-rxjs-observables/
I understand sync vs async, but this sounds as though possibly some array items arrive at different times?  Is that the case, or is it that the calling thread is allowed to continue while the that which is being observed is allowed to finish processing then resume where it left off when its ready?
Comment: Possible duplicate of [How does RxJava Observable "Iteration" work?](https://stackoverflow.com/questions/29711347/how-does-rxjava-observable-iteration-work)
Answer: Yes with Observables some items could arrive at different times. For example, say you are observing input element value changes. The user could type, pause, and type more. So the items arrive at different times.
However, when using Observables with Http, the Observables are "one and done". This means that it gets just the one response from the backend as "one" observable entry. It can then map that one response into an array of data.
For example, say you are retrieving a set of products via Http. You will get the entire set of products back as one response object that is then one Observable in the observable sequence. That response can then be mapped into the appropriate array of product objects. But the Observable still only sees it as "one" thing.
Make sense?
Comment: So nice to hear! Thanks! I'm in the process of updating it to use the CLI and the new version 4.3 HttpClientModule and HttpClient service.
Comment: DeborahK - love your Angular course on Pluralsight!  Its been a big help
Answer: Observables in RxJs can observe items arriving at different times.  You can observe things such as key-strokes, where items will continue to trickle in as they happen.  You can also observe things like a single AJAX request, where you will only be getting 1 response.
There are a few distinctions to be made with Observables:

Hot vs. Cold Observables
In short, with cold observables, when you subscribe to them, you are triggering an action.  An example would be an AJAX request.  The request will not fire until the observable is subscribed to.

Finite Observables:
Observables will be either finite or infinite.  A finite observable (such as an AJAX request) will invoke the subscription's complete callback when it is done.  Other observables, such as observing keyDown events, will only end when it is unsubscribed from.  These will continue to invoke the onNext callback every time there is a keydown event.

Observables return data over time?


(calculus) show the following infinite series diverges

Question:
$$\sum_{n=1}^\infty\frac{(3n)!}{n!(n+1)!(n+2)!}$$

please explain me how to solve this
Comment: Do the terms approach $0$?  Always a good thing to check.
Comment: And what have you tried?  We don't answer your problems for free, you have to show us what you've tried.  See [How to ask a good question?](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer: HINT: Show that $$\lim_{n\to \infty}\frac{(3n)!}{(n!(n+1)!(n+2)!}=\infty$$
Answer: Ratio of consecutive terms is
${3n+1}(3n+2)(3n+3)/((n+1)(n+2)(n+3))
\to 27$
so it diverges pretty violently.
Answer: Use one of the criteria for convergence or divergence
Like ratio test:
$$ \lim _{ n->inf }{ \left| \frac { { a }_{ n+1 } }{ { a }_{ n } }  \right|  } =\lim _{ n->inf }{\frac { 3(n+1)! }{ (n+1)!(n+2)!(n+3)! } \frac { n!(n+1)!(n+2)! }{ 3n! }} $$
$$ \lim _{ n->inf }{ \frac { (3n+1)(3n+2)(3n+3)(3n)! }{ (n+1)(n+2)(n+3)n! }  } =\lim _{ n->inf }{ \frac { (3n+1)(3n+2)(3n+3) }{ (n+1)(n+2)(n+3) }  } =\lim _{ n->inf }{ \frac { (3+1/n)(3+2/n)(3+3/n)(3/n) }{ (1+1/n)(1+2/n)(1+3/n) }  } =\lim _{ n->inf }{ \frac { (3+0)(3+0)(3+0) }{ (1+0)(1+0)(1+0) }  }  $$
In ratio test you have to proof if it is less than 1 or if it is bigger tan 1, here you can see that it is bigger, that means that the series diverges.
(Please proof my calculation)
Hope this helps!


Deduplicate forwarded emails sent to mutiple distribution groups

Question: I have 2 distribution groups set up listening on 2 different email addresses:
email@example.com and firstname.lastname@example.com. I have one (Shared, if it makes a difference) mailbox set up Emails. This mailbox is configured to forward emails to an external address through the Exchange Admin Centre: email@example.com.
If someone sends an email to firstname.lastname@example.com and CCs firstname.lastname@example.com then I my Exchange instance receives 2 copies of the email. The system appears to be smart enough to only keep one of the instances as far as the Emails mailbox is concerned, but the email gets forwarded to the external address twice.
Is there a way to configure this so that the email only gets forwarded once?
Comment: a mail comes and and gets out as addressed. it's just a simple command line that will be put on a server, aslong as you don't have a filter module or similar, it will send 2 or more times
Answer: Yes. Even if you are setting up mail flow rules, there is no action to delete duplicate messages.


Quais são os pros e contras de utilizar jquery no desenvolvimento mobile?

Question: Estou iniciando no desenvolvimento hibrido utilizando o Cordova (com visual studio) e em minhas pesquisas sobre frameworks javascript, tenho encontrado muitas pessoas utilizando AngularJS, e me surpreendi pelo fato de não encontrar ninguém que usa e recomenda JQuery (não JQuery Mobile). Porque não usar ? existe um porque ?
Comment: Olá,
não sei dizer porque não viu nenhum APP mobile com jQuery mais eu já....
e bem usado mais existe vários outros que acaba dependendo do programador escolher qual acha mais fácil. estou usando agora o framework do Google (;D) http://materializecss.com/about.html eu recomendo usar o jQuery mobile para fazer app ou este acima.
Comment: Olá Felipe, realmente existem diversos apps que utilizam o jQuery, porem não como binding de dados, a minha pergunta tinha sido mau explicada, sanei minhas dúvidas sobre binding, e hoje estou utilizando angularJs para tal, porem, ainda utilizo jQuery, mesmo porque estou utilizando materialize css também, e fica impossível sem o mesmo.
Answer: Esta página recomenda não usar jQuery por se tratar de uma biblioteca pesada, e mesmo as versões jQuery UI e jQuery Mobile apresentam performance ruim, sendo que jQuery Mobile em particular impõe muita rigidez.
Esta página fornece alguns motivos pelos quais não se deve usar jQuery Mobile (que tem o jQuery como dependência) em aplicativos móveis, entre os quais ser pesado, pouco performático, mal documentado e ter muitos bugs, e segundo o site a razão é porque jQM é voltado para websites móveis e não aplicativos. Na seção de comentários alguns discordam dessa não-recomendação.
Lembro também de já ter lido algo sobre o jQuery tratar eventos de click e não de touch, que seria o mais adequado em aplicativos móveis. Clicks têm um delay de 300 milissegundos, o que prejudica muito a responsividade do aplicativo.


Hook Page Alter using Page ID

Question: Is it possible to use a Page ID to target a specific page i.e.
function module_pageid_page_alter(&page){
}

Answer: By page ID I guess you mean the page path? There isn't a hook like the one you've suggested but you can do basically the same thing in a standard hook_page_alter() like so:
function MYMODULE_page_alter(&$page) {
  if ($_GET['q'] == 'node/1') {
    // Do something for node 1
  }
  else if ($_GET['q'] == 'admin') {
    // Do something for the root admin page
  }
}

Hook Page Alter using Page ID


liblinear one vs rest learn parameters

Question: Liblinear (http://www.csie.ntu.edu.tw/~cjlin/liblinear/) does not support for probability estimates.
Say I have three classes C1, C2 and C3. I want to learn the model paramters for each 'one vs rest' cases:
       C1 vs C2&C3,
       c2 vs C1&C3 and
       C3 vs C1&C2

How can I do it?
Answer: To make 'one-vs-rest' comparisons, simply relabel all the classes you're comparing against.  So in your first comparison, C1 stays C1 and C2 and C3 are grouped together as some new class like C4.
Comment: My advice would be either to use LibSVM or to look for implementations of [Lin's revision to Platt's solution](http://www.csie.ntu.edu.tw/~cjlin/papers/plattprob.pdf) or to follow the linked directions on the Liblinear website.
Comment: But then how can I compare the final results? (thats why I mentioned that liblinear does not support for probability estimates). I need the probability estimates to get the final classification results.
Comment: What classifier are you using in Liblinear?  I assume not an SVM else you would be using LibSVM, or might follow the Liblinear team's [directions](http://www.csie.ntu.edu.tw/~cjlin/liblinear/FAQ.html)
Comment: I am using SVM classification using libLinear. The problem is LibSVM supports probability estimates but libLinear does not support (supports probability estimates only for regression problems)

liblinear one vs rest learn parameters


JavaScript + Canvas

Question: Olá,
Gente estou estudando canvas com HTML5 então que me surgiu o seguinte problema, quando eu importo o arquivo externo do JavaScript dentro da tag "head" ele não reconhece. Só quando eu coloco dentor do body.
var canvas = document.getElementById('myCanvas');

if (canvas.getContext) {
  var context = canvas.getContext("2d");
  context.fillStyle = "rgb(200,0,0)";
  context.fillRect(10, 10, 55, 50);

  context.fillStyle = "rgba(0, 0, 200, 0.5)";
  context.fillRect(30, 30, 55, 50);
}

Quando eu coloco:

Dentro da tag head ele não funciona, só no fim do corpo(body)
Answer: Isso acontece porque quando o browser lê o head e corre o script, o document.body ainda não existe. Ou seja document.getElementById('myCanvas'); só pode correr depois de o browser ter lido esse HTML.
Podes deixar ficar no head mas dentro de uma callback para só correr quando o DOM estiver pronto, ou como estás a fazer no body.
Para deixar no head:
window.onload = function(){
    var canvas = document.getElementById('myCanvas');
    if (canvas.getContext) {
      var context = canvas.getContext("2d");
      context.fillStyle = "rgb(200,0,0)";
      context.fillRect(10, 10, 55, 50);

      context.fillStyle = "rgba(0, 0, 200, 0.5)";
      context.fillRect(30, 30, 55, 50);
    }
}

JavaScript + Canvas